• 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.CallbackExecutor;
27 import android.annotation.IntDef;
28 import android.annotation.LongDef;
29 import android.annotation.NonNull;
30 import android.annotation.Nullable;
31 import android.annotation.RequiresPermission;
32 import android.annotation.SdkConstant;
33 import android.annotation.SdkConstant.SdkConstantType;
34 import android.annotation.SuppressAutoDoc;
35 import android.annotation.SuppressLint;
36 import android.annotation.SystemApi;
37 import android.annotation.SystemService;
38 import android.annotation.TestApi;
39 import android.annotation.WorkerThread;
40 import android.app.PendingIntent;
41 import android.app.role.RoleManager;
42 import android.compat.Compatibility;
43 import android.compat.annotation.ChangeId;
44 import android.compat.annotation.EnabledAfter;
45 import android.compat.annotation.UnsupportedAppUsage;
46 import android.content.ComponentName;
47 import android.content.Context;
48 import android.content.Intent;
49 import android.database.Cursor;
50 import android.net.ConnectivityManager;
51 import android.net.Uri;
52 import android.os.AsyncTask;
53 import android.os.Binder;
54 import android.os.Build;
55 import android.os.Bundle;
56 import android.os.Handler;
57 import android.os.IBinder;
58 import android.os.ParcelFileDescriptor;
59 import android.os.PersistableBundle;
60 import android.os.Process;
61 import android.os.RemoteException;
62 import android.os.ResultReceiver;
63 import android.os.SystemProperties;
64 import android.os.WorkSource;
65 import android.provider.Settings.SettingNotFoundException;
66 import android.service.carrier.CarrierIdentifier;
67 import android.sysprop.TelephonyProperties;
68 import android.telecom.CallScreeningService;
69 import android.telecom.InCallService;
70 import android.telecom.PhoneAccount;
71 import android.telecom.PhoneAccountHandle;
72 import android.telecom.TelecomManager;
73 import android.telephony.Annotation.ApnType;
74 import android.telephony.Annotation.CallState;
75 import android.telephony.Annotation.CarrierPrivilegeStatus;
76 import android.telephony.Annotation.NetworkType;
77 import android.telephony.Annotation.RadioPowerState;
78 import android.telephony.Annotation.SimActivationState;
79 import android.telephony.Annotation.UiccAppType;
80 import android.telephony.CallForwardingInfo.CallForwardingReason;
81 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
82 import android.telephony.data.ApnSetting;
83 import android.telephony.data.ApnSetting.MvnoType;
84 import android.telephony.emergency.EmergencyNumber;
85 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
86 import android.telephony.ims.ImsMmTelManager;
87 import android.telephony.ims.aidl.IImsConfig;
88 import android.telephony.ims.aidl.IImsMmTelFeature;
89 import android.telephony.ims.aidl.IImsRcsFeature;
90 import android.telephony.ims.aidl.IImsRegistration;
91 import android.telephony.ims.feature.MmTelFeature;
92 import android.telephony.ims.stub.ImsRegistrationImplBase;
93 import android.text.TextUtils;
94 import android.util.Log;
95 import android.util.Pair;
96 
97 import com.android.ims.internal.IImsServiceFeatureCallback;
98 import com.android.internal.annotations.GuardedBy;
99 import com.android.internal.annotations.VisibleForTesting;
100 import com.android.internal.telephony.CellNetworkScanResult;
101 import com.android.internal.telephony.IBooleanConsumer;
102 import com.android.internal.telephony.INumberVerificationCallback;
103 import com.android.internal.telephony.IOns;
104 import com.android.internal.telephony.IPhoneSubInfo;
105 import com.android.internal.telephony.ISetOpportunisticDataCallback;
106 import com.android.internal.telephony.ISms;
107 import com.android.internal.telephony.ISub;
108 import com.android.internal.telephony.ITelephony;
109 import com.android.internal.telephony.IUpdateAvailableNetworksCallback;
110 import com.android.internal.telephony.OperatorInfo;
111 import com.android.internal.telephony.PhoneConstants;
112 import com.android.internal.telephony.RILConstants;
113 import com.android.internal.telephony.SmsApplication;
114 import com.android.telephony.Rlog;
115 
116 import java.io.FileInputStream;
117 import java.io.IOException;
118 import java.lang.annotation.Retention;
119 import java.lang.annotation.RetentionPolicy;
120 import java.util.ArrayList;
121 import java.util.Collections;
122 import java.util.HashMap;
123 import java.util.List;
124 import java.util.Locale;
125 import java.util.Map;
126 import java.util.Objects;
127 import java.util.UUID;
128 import java.util.concurrent.Executor;
129 import java.util.function.Consumer;
130 import java.util.regex.Matcher;
131 import java.util.regex.Pattern;
132 
133 /**
134  * Provides access to information about the telephony services on
135  * the device. Applications can use the methods in this class to
136  * determine telephony services and states, as well as to access some
137  * types of subscriber information. Applications can also register
138  * a listener to receive notification of telephony state changes.
139  * <p>
140  * The returned TelephonyManager will use the default subscription for all calls.
141  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
142  * <code>
143  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
144  * </code>
145  * <p>
146  * Note that access to some telephony information is
147  * permission-protected. Your application cannot access the protected
148  * information unless it has the appropriate permissions declared in
149  * its manifest file. Where permissions apply, they are noted in the
150  * the methods through which you access the protected information.
151  *
152  * <p>TelephonyManager is intended for use on devices that implement
153  * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
154  * that do not implement this feature, the behavior is not reliable.
155  */
156 @SystemService(Context.TELEPHONY_SERVICE)
157 public class TelephonyManager {
158     private static final String TAG = "TelephonyManager";
159 
160     /**
161      * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
162      * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
163      */
164     @ChangeId
165     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
166     private static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
167 
168     /**
169      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
170      * into the ResultReceiver Bundle.
171      * @hide
172      */
173     public static final String MODEM_ACTIVITY_RESULT_KEY = "controller_activity";
174 
175     /**
176      * The process name of the Phone app as well as many other apps that use this process name, such
177      * as settings and vendor components.
178      * @hide
179      */
180     public static final String PHONE_PROCESS_NAME = "com.android.phone";
181 
182     /**
183      * The allowed states of Wi-Fi calling.
184      *
185      * @hide
186      */
187     public interface WifiCallingChoices {
188         /** Always use Wi-Fi calling */
189         static final int ALWAYS_USE = 0;
190         /** Ask the user whether to use Wi-Fi on every call */
191         static final int ASK_EVERY_TIME = 1;
192         /** Never use Wi-Fi calling */
193         static final int NEVER_USE = 2;
194     }
195 
196     /** @hide */
197     @Retention(RetentionPolicy.SOURCE)
198     @IntDef(prefix = {"NETWORK_SELECTION_MODE_"},
199             value = {
200                     NETWORK_SELECTION_MODE_UNKNOWN,
201                     NETWORK_SELECTION_MODE_AUTO,
202                     NETWORK_SELECTION_MODE_MANUAL})
203     public @interface NetworkSelectionMode {}
204 
205     public static final int NETWORK_SELECTION_MODE_UNKNOWN = 0;
206     public static final int NETWORK_SELECTION_MODE_AUTO = 1;
207     public static final int NETWORK_SELECTION_MODE_MANUAL = 2;
208 
209     /** The otaspMode passed to PhoneStateListener#onOtaspChanged */
210     /** @hide */
211     static public final int OTASP_UNINITIALIZED = 0;
212     /** @hide */
213     static public final int OTASP_UNKNOWN = 1;
214     /** @hide */
215     static public final int OTASP_NEEDED = 2;
216     /** @hide */
217     static public final int OTASP_NOT_NEEDED = 3;
218     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
219     /** @hide */
220     static public final int OTASP_SIM_UNPROVISIONED = 5;
221 
222     /**
223      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
224      * available for use in ePDG links.
225      *
226      * @hide
227      */
228     @SystemApi
229     static public final int KEY_TYPE_EPDG = 1;
230 
231     /**
232      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
233      * available for use in WLAN links.
234      *
235      * @hide
236      */
237     @SystemApi
238     static public final int KEY_TYPE_WLAN = 2;
239 
240     /** @hide */
241     @Retention(RetentionPolicy.SOURCE)
242     @IntDef(prefix = {"KEY_TYPE_"}, value = {KEY_TYPE_EPDG, KEY_TYPE_WLAN})
243     public @interface KeyType {}
244 
245     /**
246      * No Single Radio Voice Call Continuity (SRVCC) handover is active.
247      * See TS 23.216 for more information.
248      * @hide
249      */
250     @SystemApi
251     public static final int SRVCC_STATE_HANDOVER_NONE  = -1;
252 
253     /**
254      * Single Radio Voice Call Continuity (SRVCC) handover has been started on the network.
255      * See TS 23.216 for more information.
256      * @hide
257      */
258     @SystemApi
259     public static final int SRVCC_STATE_HANDOVER_STARTED  = 0;
260 
261     /**
262      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has successfully completed.
263      * See TS 23.216 for more information.
264      * @hide
265      */
266     @SystemApi
267     public static final int SRVCC_STATE_HANDOVER_COMPLETED = 1;
268 
269     /**
270      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has failed.
271      * See TS 23.216 for more information.
272      * @hide
273      */
274     @SystemApi
275     public static final int SRVCC_STATE_HANDOVER_FAILED   = 2;
276 
277     /**
278      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has been canceled.
279      * See TS 23.216 for more information.
280      * @hide
281      */
282     @SystemApi
283     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
284 
285     /**
286      * A UICC card identifier used if the device does not support the operation.
287      * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
288      * eUICC, or the eUICC cannot be read.
289      */
290     public static final int UNSUPPORTED_CARD_ID = -1;
291 
292     /**
293      * A UICC card identifier used before the UICC card is loaded. See
294      * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
295      * <p>
296      * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
297      */
298     public static final int UNINITIALIZED_CARD_ID = -2;
299 
300     private final Context mContext;
301     private final int mSubId;
302     @UnsupportedAppUsage
303     private SubscriptionManager mSubscriptionManager;
304     private TelephonyScanManager mTelephonyScanManager;
305 
306     /** Cached service handles, cleared by resetServiceHandles() at death */
307     private static final Object sCacheLock = new Object();
308 
309     /** @hide */
310     private static boolean sServiceHandleCacheEnabled = true;
311 
312     @GuardedBy("sCacheLock")
313     private static IPhoneSubInfo sIPhoneSubInfo;
314     @GuardedBy("sCacheLock")
315     private static ISub sISub;
316     @GuardedBy("sCacheLock")
317     private static ISms sISms;
318     @GuardedBy("sCacheLock")
319     private static final DeathRecipient sServiceDeath = new DeathRecipient();
320 
321     /** Enum indicating multisim variants
322      *  DSDS - Dual SIM Dual Standby
323      *  DSDA - Dual SIM Dual Active
324      *  TSTS - Triple SIM Triple Standby
325      **/
326     /** @hide */
327     @UnsupportedAppUsage(implicitMember =
328             "values()[Landroid/telephony/TelephonyManager$MultiSimVariants;")
329     public enum MultiSimVariants {
330         @UnsupportedAppUsage
331         DSDS,
332         @UnsupportedAppUsage
333         DSDA,
334         @UnsupportedAppUsage
335         TSTS,
336         @UnsupportedAppUsage
337         UNKNOWN
338     };
339 
340     /** @hide */
341     @UnsupportedAppUsage
TelephonyManager(Context context)342     public TelephonyManager(Context context) {
343       this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
344     }
345 
346     /** @hide */
347     @UnsupportedAppUsage
TelephonyManager(Context context, int subId)348     public TelephonyManager(Context context, int subId) {
349         mSubId = subId;
350         Context appContext = context.getApplicationContext();
351         if (appContext != null) {
352             if (Objects.equals(context.getAttributionTag(), appContext.getAttributionTag())) {
353                 mContext = appContext;
354             } else {
355                 mContext = appContext.createAttributionContext(context.getAttributionTag());
356             }
357         } else {
358             mContext = context;
359         }
360         mSubscriptionManager = SubscriptionManager.from(mContext);
361     }
362 
363     /** @hide */
364     @UnsupportedAppUsage
TelephonyManager()365     private TelephonyManager() {
366         mContext = null;
367         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
368     }
369 
370     private static TelephonyManager sInstance = new TelephonyManager();
371 
372     /** @hide
373     /* @deprecated - use getSystemService as described above */
374     @Deprecated
375     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDefault()376     public static TelephonyManager getDefault() {
377         return sInstance;
378     }
379 
getOpPackageName()380     private String getOpPackageName() {
381         // For legacy reasons the TelephonyManager has API for getting
382         // a static instance with no context set preventing us from
383         // getting the op package name. As a workaround we do a best
384         // effort and get the context from the current activity thread.
385         if (mContext != null) {
386             return mContext.getOpPackageName();
387         } else {
388             ITelephony telephony = getITelephony();
389             if (telephony == null) return null;
390             try {
391                 return telephony.getCurrentPackageName();
392             } catch (RemoteException ex) {
393                 return null;
394             } catch (NullPointerException ex) {
395                 return null;
396             }
397         }
398     }
399 
getAttributionTag()400     private String getAttributionTag() {
401         // For legacy reasons the TelephonyManager has API for getting
402         // a static instance with no context set preventing us from
403         // getting the attribution tag.
404         if (mContext != null) {
405             return mContext.getAttributionTag();
406         }
407         return null;
408     }
409 
isSystemProcess()410     private boolean isSystemProcess() {
411         return Process.myUid() == Process.SYSTEM_UID;
412     }
413 
414     /**
415      * Returns the multi SIM variant
416      * Returns DSDS for Dual SIM Dual Standby
417      * Returns DSDA for Dual SIM Dual Active
418      * Returns TSTS for Triple SIM Triple Standby
419      * Returns UNKNOWN for others
420      */
421     /** {@hide} */
422     @UnsupportedAppUsage
getMultiSimConfiguration()423     public MultiSimVariants getMultiSimConfiguration() {
424         String mSimConfig =
425                 TelephonyProperties.multi_sim_config().orElse("");
426         if (mSimConfig.equals("dsds")) {
427             return MultiSimVariants.DSDS;
428         } else if (mSimConfig.equals("dsda")) {
429             return MultiSimVariants.DSDA;
430         } else if (mSimConfig.equals("tsts")) {
431             return MultiSimVariants.TSTS;
432         } else {
433             return MultiSimVariants.UNKNOWN;
434         }
435     }
436 
437     /**
438      * Returns the number of phones available.
439      * Returns 0 if none of voice, sms, data is not supported
440      * Returns 1 for Single standby mode (Single SIM functionality).
441      * Returns 2 for Dual standby mode (Dual SIM functionality).
442      * Returns 3 for Tri standby mode (Tri SIM functionality).
443      * @deprecated Use {@link #getActiveModemCount} instead.
444      */
445     @Deprecated
getPhoneCount()446     public int getPhoneCount() {
447         return getActiveModemCount();
448     }
449 
450     /**
451      * Returns the number of logical modems currently configured to be activated.
452      *
453      * Returns 0 if none of voice, sms, data is not supported
454      * Returns 1 for Single standby mode (Single SIM functionality).
455      * Returns 2 for Dual standby mode (Dual SIM functionality).
456      * Returns 3 for Tri standby mode (Tri SIM functionality).
457      */
getActiveModemCount()458     public int getActiveModemCount() {
459         int modemCount = 1;
460         switch (getMultiSimConfiguration()) {
461             case UNKNOWN:
462                 modemCount = 1;
463                 // check for voice and data support, 0 if not supported
464                 if (!isVoiceCapable() && !isSmsCapable() && !isDataCapable()) {
465                     modemCount = 0;
466                 }
467                 break;
468             case DSDS:
469             case DSDA:
470                 modemCount = 2;
471                 break;
472             case TSTS:
473                 modemCount = 3;
474                 break;
475         }
476         return modemCount;
477     }
478 
479     /**
480      * Return how many logical modem can be potentially active simultaneously, in terms of hardware
481      * capability.
482      * It might return different value from {@link #getActiveModemCount}. For example, for a
483      * dual-SIM capable device operating in single SIM mode (only one logical modem is turned on),
484      * {@link #getActiveModemCount} returns 1 while this API returns 2.
485      */
getSupportedModemCount()486     public int getSupportedModemCount() {
487         return TelephonyProperties.max_active_modems().orElse(getActiveModemCount());
488     }
489 
490     /**
491      * Gets the maximum number of SIMs that can be active, based on the device's multisim
492      * configuration.
493      * @return 1 for single-SIM, DSDS, and TSTS devices. 2 for DSDA devices.
494      * @hide
495      */
496     @SystemApi
getMaxNumberOfSimultaneouslyActiveSims()497     public int getMaxNumberOfSimultaneouslyActiveSims() {
498         switch (getMultiSimConfiguration()) {
499             case UNKNOWN:
500             case DSDS:
501             case TSTS:
502                 return 1;
503             case DSDA:
504                 return 2;
505         }
506         return 1;
507     }
508 
509     /** {@hide} */
510     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)511     public static TelephonyManager from(Context context) {
512         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
513     }
514 
515     /**
516      * Create a new TelephonyManager object pinned to the given subscription ID.
517      *
518      * @return a TelephonyManager that uses the given subId for all calls.
519      */
createForSubscriptionId(int subId)520     public TelephonyManager createForSubscriptionId(int subId) {
521       // Don't reuse any TelephonyManager objects.
522       return new TelephonyManager(mContext, subId);
523     }
524 
525     /**
526      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
527      * phone account.
528      *
529      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
530      * if the phone account does not correspond to a valid subscription ID.
531      */
532     @Nullable
createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle)533     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
534         int subId = getSubscriptionId(phoneAccountHandle);
535         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
536             return null;
537         }
538         return new TelephonyManager(mContext, subId);
539     }
540 
541     /** {@hide} */
542     @UnsupportedAppUsage
isMultiSimEnabled()543     public boolean isMultiSimEnabled() {
544         return getPhoneCount() > 1;
545     }
546 
547     //
548     // Broadcast Intent actions
549     //
550 
551     /**
552      * Broadcast intent action indicating that the call state
553      * on the device has changed.
554      *
555      * <p>
556      * The {@link #EXTRA_STATE} extra indicates the new call state.
557      * If a receiving app has {@link android.Manifest.permission#READ_CALL_LOG} permission, a second
558      * extra {@link #EXTRA_INCOMING_NUMBER} provides the phone number for incoming and outgoing
559      * calls as a String.
560      * <p>
561      * If the receiving app has
562      * {@link android.Manifest.permission#READ_CALL_LOG} and
563      * {@link android.Manifest.permission#READ_PHONE_STATE} permission, it will receive the
564      * broadcast twice; one with the {@link #EXTRA_INCOMING_NUMBER} populated with the phone number,
565      * and another with it blank.  Due to the nature of broadcasts, you cannot assume the order
566      * in which these broadcasts will arrive, however you are guaranteed to receive two in this
567      * case.  Apps which are interested in the {@link #EXTRA_INCOMING_NUMBER} can ignore the
568      * broadcasts where {@link #EXTRA_INCOMING_NUMBER} is not present in the extras (e.g. where
569      * {@link Intent#hasExtra(String)} returns {@code false}).
570      * <p class="note">
571      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
572      * broadcast in version 1.0, but it is no longer sticky.
573      * Instead, use {@link #getCallState} to synchronously query the current call state.
574      *
575      * @see #EXTRA_STATE
576      * @see #EXTRA_INCOMING_NUMBER
577      * @see #getCallState
578      */
579     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
580     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
581     public static final String ACTION_PHONE_STATE_CHANGED =
582             "android.intent.action.PHONE_STATE";
583 
584     /**
585      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
586      * call. By default, the device's default SMS app consumes this message and sends a text message
587      * to the caller. A third party app can also provide this functionality by consuming this Intent
588      * with a {@link android.app.Service} and sending the message using its own messaging system.
589      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
590      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
591      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
592      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
593      * set of phone numbers if there are multiple recipients. For example, {@code
594      * smsto:2065551234}.</p>
595      *
596      * <p>The intent may also contain extras for the message text (in {@link
597      * android.content.Intent#EXTRA_TEXT}) and a message subject
598      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
599      *
600      * <p class="note"><strong>Note:</strong>
601      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
602      * that requires the
603      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
604      * <p>For example, the service that receives this intent can be declared in the manifest file
605      * with an intent filter like this:</p>
606      * <pre>
607      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
608      * &lt;service android:name=".HeadlessSmsSendService"
609      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
610      *          android:exported="true" >
611      *   &lt;intent-filter>
612      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
613      *     &lt;category android:name="android.intent.category.DEFAULT" />
614      *     &lt;data android:scheme="sms" />
615      *     &lt;data android:scheme="smsto" />
616      *     &lt;data android:scheme="mms" />
617      *     &lt;data android:scheme="mmsto" />
618      *   &lt;/intent-filter>
619      * &lt;/service></pre>
620      * <p>
621      * Output: nothing.
622      */
623     @SdkConstant(SdkConstantType.SERVICE_ACTION)
624     public static final String ACTION_RESPOND_VIA_MESSAGE =
625             "android.intent.action.RESPOND_VIA_MESSAGE";
626 
627     /**
628      * The emergency dialer may choose to present activities with intent filters for this
629      * action as emergency assistance buttons that launch the activity when clicked.
630      *
631      * @hide
632      */
633     @SystemApi
634     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
635     public static final String ACTION_EMERGENCY_ASSISTANCE =
636             "android.telephony.action.EMERGENCY_ASSISTANCE";
637 
638     /**
639      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
640      * call settings page launched by
641      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
642      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
643      * which would also like to manage voicemail settings should set this meta-data to {@code true}
644      * in the manifest registration of their application.
645      *
646      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
647      * @see #ACTION_CONFIGURE_VOICEMAIL
648      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
649      */
650     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
651             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
652 
653     /**
654      * Open the voicemail settings activity to make changes to voicemail configuration.
655      *
656      * <p>
657      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} to
658      * configure voicemail.
659      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
660      * API if set.
661      *
662      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
663      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
664      */
665     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
666     public static final String ACTION_CONFIGURE_VOICEMAIL =
667             "android.telephony.action.CONFIGURE_VOICEMAIL";
668 
669     /**
670      * The boolean value indicating whether the voicemail settings activity launched by {@link
671      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
672      * used by dialer implementations which provides their own voicemail settings UI, but still
673      * needs to expose device specific voicemail settings to the user.
674      *
675      * @see #ACTION_CONFIGURE_VOICEMAIL
676      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
677      */
678     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
679             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
680 
681     /**
682      * @hide
683      */
684     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
685 
686     /**
687      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
688      * for a String containing the new call state.
689      *
690      * <p class="note">
691      * Retrieve with
692      * {@link android.content.Intent#getStringExtra(String)}.
693      *
694      * @see #EXTRA_STATE_IDLE
695      * @see #EXTRA_STATE_RINGING
696      * @see #EXTRA_STATE_OFFHOOK
697      */
698     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
699 
700     /**
701      * Value used with {@link #EXTRA_STATE} corresponding to
702      * {@link #CALL_STATE_IDLE}.
703      */
704     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
705 
706     /**
707      * Value used with {@link #EXTRA_STATE} corresponding to
708      * {@link #CALL_STATE_RINGING}.
709      */
710     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
711 
712     /**
713      * Value used with {@link #EXTRA_STATE} corresponding to
714      * {@link #CALL_STATE_OFFHOOK}.
715      */
716     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
717 
718     /**
719      * Extra key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
720      * for a String containing the incoming or outgoing phone number.
721      * <p>
722      * This extra is only populated for receivers of the {@link #ACTION_PHONE_STATE_CHANGED}
723      * broadcast which have been granted the {@link android.Manifest.permission#READ_CALL_LOG} and
724      * {@link android.Manifest.permission#READ_PHONE_STATE} permissions.
725      * <p>
726      * For incoming calls, the phone number is only guaranteed to be populated when the
727      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_RINGING}.
728      * If the incoming caller is from an unknown number, the extra will be populated with an empty
729      * string.
730      * For outgoing calls, the phone number is only guaranteed to be populated when the
731      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_OFFHOOK}.
732      * <p class="note">
733      * Retrieve with
734      * {@link android.content.Intent#getStringExtra(String)}.
735      * <p>
736      *
737      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
738      * to retrieve the phone number for calls instead.  Apps performing call screening should use
739      * the {@link CallScreeningService} API instead.
740      */
741     @Deprecated
742     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
743 
744     /**
745      * Broadcast intent action indicating that call disconnect cause has changed.
746      *
747      * <p>
748      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
749      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
750      *
751      * <p class="note">
752      * Requires the READ_PRECISE_PHONE_STATE permission.
753      *
754      * @see #EXTRA_DISCONNECT_CAUSE
755      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
756      *
757      * @hide
758      */
759     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
760     public static final String ACTION_CALL_DISCONNECT_CAUSE_CHANGED =
761             "android.intent.action.CALL_DISCONNECT_CAUSE";
762 
763     /**
764      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
765      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
766      * containing the disconnect cause.
767      *
768      * @see DisconnectCause
769      *
770      * <p class="note">
771      * Retrieve with
772      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
773      *
774      * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
775      * @hide
776      */
777     @Deprecated
778     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
779 
780     /**
781      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
782      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
783      * containing the disconnect cause provided by the RIL.
784      *
785      * @see PreciseDisconnectCause
786      *
787      * <p class="note">
788      * Retrieve with
789      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
790      *
791      * @hide
792      */
793     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
794 
795     /**
796      * Broadcast intent action for letting the default dialer to know to show voicemail
797      * notification.
798      *
799      * <p>
800      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
801      * voicemail is received on.
802      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
803      * voicemails.
804      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
805      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
806      * will call the voicemail number when sent. This extra will be empty if the voicemail number
807      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
808      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
809      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
810      * available when the voicemail number is not set.
811      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
812      * notification.
813      *
814      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
815      * @see #EXTRA_NOTIFICATION_COUNT
816      * @see #EXTRA_VOICEMAIL_NUMBER
817      * @see #EXTRA_CALL_VOICEMAIL_INTENT
818      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
819      * @see #EXTRA_IS_REFRESH
820      */
821     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
822             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
823 
824     /**
825      * The extra used with an {@link #ACTION_CONFIGURE_VOICEMAIL} and
826      * {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify the
827      * {@link PhoneAccountHandle} the configuration or notification is for.
828      * <p class="note">
829      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
830      */
831     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
832             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
833 
834     /**
835      * The number of voice messages associated with the notification.
836      */
837     public static final String EXTRA_NOTIFICATION_COUNT =
838             "android.telephony.extra.NOTIFICATION_COUNT";
839 
840     /**
841      * The voicemail number.
842      */
843     public static final String EXTRA_VOICEMAIL_NUMBER =
844             "android.telephony.extra.VOICEMAIL_NUMBER";
845 
846     /**
847      * The intent to call voicemail.
848      */
849     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
850             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
851 
852     /**
853      * The intent to launch voicemail settings.
854      */
855     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
856             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
857 
858     /**
859      * Boolean value representing whether the {@link
860      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
861      * notification. Notification refresh happens after reboot or connectivity changes. The user has
862      * already been notified for the voicemail so it should not alert the user, and should not be
863      * shown again if the user has dismissed it.
864      */
865     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
866 
867     /**
868      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
869      * successfully handed over from WIFI to LTE.
870      * <p>
871      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
872      * The {@link Bundle} parameter is expected to be null when this connection event is used.
873      * @hide
874      */
875     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
876             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
877 
878     /**
879      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
880      * successfully handed over from LTE to WIFI.
881      * <p>
882      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
883      * The {@link Bundle} parameter is expected to be null when this connection event is used.
884      * @hide
885      */
886     public static final String EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI =
887             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI";
888 
889     /**
890      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
891      * handed over from LTE to WIFI.
892      * <p>
893      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
894      * The {@link Bundle} parameter is expected to be null when this connection event is used.
895      * @hide
896      */
897     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
898             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
899 
900     /**
901      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
902      * audio because the data limit was reached.
903      * <p>
904      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
905      * The {@link Bundle} parameter is expected to be null when this connection event is used.
906      * @hide
907      */
908     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
909             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
910 
911     /**
912      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
913      * audio because the data was disabled.
914      * <p>
915      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
916      * The {@link Bundle} parameter is expected to be null when this connection event is used.
917      * @hide
918      */
919     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
920             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
921 
922     /**
923      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
924      * the user when an international call is placed while on WFC only.
925      * <p>
926      * Used when the carrier config value
927      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
928      * is on WFC (VoLTE not available) and an international number is dialed.
929      * <p>
930      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
931      * The {@link Bundle} parameter is expected to be null when this connection event is used.
932      * @hide
933      */
934     public static final String EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
935             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
936 
937     /**
938      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
939      * forwarded to another number.
940      * <p>
941      * Sent in response to an IMS supplementary service notification indicating the call has been
942      * forwarded.
943      * <p>
944      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
945      * The {@link Bundle} parameter is expected to be null when this connection event is used.
946      * @hide
947      */
948     public static final String EVENT_CALL_FORWARDED =
949             "android.telephony.event.EVENT_CALL_FORWARDED";
950 
951     /**
952      * {@link android.telecom.Connection} event used to indicate that a supplementary service
953      * notification has been received.
954      * <p>
955      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
956      * The {@link Bundle} parameter is expected to include the following extras:
957      * <ul>
958      *     <li>{@link #EXTRA_NOTIFICATION_TYPE} - the notification type.</li>
959      *     <li>{@link #EXTRA_NOTIFICATION_CODE} - the notification code.</li>
960      *     <li>{@link #EXTRA_NOTIFICATION_MESSAGE} - human-readable message associated with the
961      *     supplementary service notification.</li>
962      * </ul>
963      * @hide
964      */
965     public static final String EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION =
966             "android.telephony.event.EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION";
967 
968     /**
969      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
970      * the type of supplementary service notification which occurred.
971      * Will be either
972      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_1}
973      * or
974      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_2}
975      * <p>
976      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
977      * @hide
978      */
979     public static final String EXTRA_NOTIFICATION_TYPE =
980             "android.telephony.extra.NOTIFICATION_TYPE";
981 
982     /**
983      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
984      * the supplementary service notification which occurred.
985      * <p>
986      * Depending on the {@link #EXTRA_NOTIFICATION_TYPE}, the code will be one of the {@code CODE_*}
987      * codes defined in {@link com.android.internal.telephony.gsm.SuppServiceNotification}.
988      * <p>
989      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
990      * @hide
991      */
992     public static final String EXTRA_NOTIFICATION_CODE =
993             "android.telephony.extra.NOTIFICATION_CODE";
994 
995     /**
996      * {@link CharSequence} extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION}
997      * which contains a human-readable message which can be displayed to the user for the
998      * supplementary service notification.
999      * <p>
1000      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1001      * @hide
1002      */
1003     public static final String EXTRA_NOTIFICATION_MESSAGE =
1004             "android.telephony.extra.NOTIFICATION_MESSAGE";
1005 
1006     /* Visual voicemail protocols */
1007 
1008     /**
1009      * The OMTP protocol.
1010      */
1011     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
1012 
1013     /**
1014      * A flavor of OMTP protocol with a different mobile originated (MO) format
1015      */
1016     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
1017 
1018     /**
1019      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
1020      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
1021      * setting, this key will not exist.
1022      *
1023      * @see #getVisualVoicemailSettings()
1024      * @hide
1025      */
1026     @SystemApi
1027     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
1028             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
1029 
1030     /**
1031      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
1032      * access PIN scrambled during the auto provisioning process. The user is expected to reset
1033      * their PIN if this value is not {@code null}.
1034      *
1035      * @see #getVisualVoicemailSettings()
1036      * @hide
1037      */
1038     @SystemApi
1039     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
1040             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
1041 
1042     /**
1043      * Broadcast action to be received by Broadcast receivers.
1044      *
1045      * Indicates multi-SIM configuration is changed. For example, it changed
1046      * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
1047      *
1048      * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
1049      * or that all steps during multi-SIM change are done. To know those information you still need
1050      * to listen to SIM_STATE changes or active subscription changes.
1051      *
1052      * See extra of {@link #EXTRA_ACTIVE_SIM_SUPPORTED_COUNT} for updated value.
1053      */
1054     public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
1055             "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
1056 
1057 
1058     /**
1059      * The number of active SIM supported by current multi-SIM config. It's not related to how many
1060      * SIM/subscriptions are currently active.
1061      *
1062      * Same value will be returned by {@link #getActiveModemCount()}.
1063      *
1064      * For single SIM mode, it's 1.
1065      * For DSDS or DSDA mode, it's 2.
1066      * For triple-SIM mode, it's 3.
1067      *
1068      * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
1069      *
1070      * type: integer
1071      */
1072     public static final String EXTRA_ACTIVE_SIM_SUPPORTED_COUNT =
1073             "android.telephony.extra.ACTIVE_SIM_SUPPORTED_COUNT";
1074 
1075     /**
1076      * @hide
1077      */
1078     public static final String USSD_RESPONSE = "USSD_RESPONSE";
1079 
1080     /**
1081      * USSD return code success.
1082      * @hide
1083      */
1084     public static final int USSD_RETURN_SUCCESS = 100;
1085 
1086     /**
1087      * Failed code returned when the mobile network has failed to complete a USSD request.
1088      * <p>
1089      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1090      * TelephonyManager, String, int)}.
1091      */
1092     public static final int USSD_RETURN_FAILURE = -1;
1093 
1094     /**
1095      * Failure code returned when a USSD request has failed to execute because the Telephony
1096      * service is unavailable.
1097      * <p>
1098      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1099      * TelephonyManager, String, int)}.
1100      */
1101     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
1102 
1103     /**
1104      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which leaves the roaming
1105      * mode set to the radio default or to the user's preference if they've indicated one.
1106      */
1107     public static final int CDMA_ROAMING_MODE_RADIO_DEFAULT = -1;
1108     /**
1109      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which only permits
1110      * connections on home networks.
1111      */
1112     public static final int CDMA_ROAMING_MODE_HOME = 0;
1113     /**
1114      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1115      * affiliated networks.
1116      */
1117     public static final int CDMA_ROAMING_MODE_AFFILIATED = 1;
1118     /**
1119      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1120      * any network.
1121      */
1122     public static final int CDMA_ROAMING_MODE_ANY = 2;
1123 
1124     /** @hide */
1125     @IntDef(prefix = { "CDMA_ROAMING_MODE_" }, value = {
1126             CDMA_ROAMING_MODE_RADIO_DEFAULT,
1127             CDMA_ROAMING_MODE_HOME,
1128             CDMA_ROAMING_MODE_AFFILIATED,
1129             CDMA_ROAMING_MODE_ANY
1130     })
1131     @Retention(RetentionPolicy.SOURCE)
1132     public @interface CdmaRoamingMode{}
1133 
1134     /**
1135      * An unknown carrier id. It could either be subscription unavailable or the subscription
1136      * carrier cannot be recognized. Unrecognized carriers here means
1137      * {@link #getSimOperator() MCC+MNC} cannot be identified.
1138      */
1139     public static final int UNKNOWN_CARRIER_ID = -1;
1140 
1141     /**
1142      * An unknown carrier id list version.
1143      * @hide
1144      */
1145     @TestApi
1146     public static final int UNKNOWN_CARRIER_ID_LIST_VERSION = -1;
1147 
1148     /**
1149      * Broadcast Action: The subscription carrier identity has changed.
1150      * This intent could be sent on the following events:
1151      * <ul>
1152      *   <li>Subscription absent. Carrier identity could change from a valid id to
1153      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID}.</li>
1154      *   <li>Subscription loaded. Carrier identity could change from
1155      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID} to a valid id.</li>
1156      *   <li>The subscription carrier is recognized after a remote update.</li>
1157      * </ul>
1158      * The intent will have the following extra values:
1159      * <ul>
1160      *   <li>{@link #EXTRA_CARRIER_ID} The up-to-date carrier id of the current subscription id.
1161      *   </li>
1162      *   <li>{@link #EXTRA_CARRIER_NAME} The up-to-date carrier name of the current subscription.
1163      *   </li>
1164      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1165      *   identity.
1166      *   </li>
1167      * </ul>
1168      * <p class="note">This is a protected intent that can only be sent by the system.
1169      */
1170     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1171     public static final String ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED =
1172             "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED";
1173 
1174     /**
1175      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which indicates
1176      * the updated carrier id returned by {@link TelephonyManager#getSimCarrierId()}.
1177      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1178      * the carrier cannot be identified.
1179      */
1180     public static final String EXTRA_CARRIER_ID = "android.telephony.extra.CARRIER_ID";
1181 
1182     /**
1183      * An string extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which
1184      * indicates the updated carrier name of the current subscription.
1185      * @see TelephonyManager#getSimCarrierIdName()
1186      * <p>Carrier name is a user-facing name of the carrier id {@link #EXTRA_CARRIER_ID},
1187      * usually the brand name of the subsidiary (e.g. T-Mobile).
1188      */
1189     public static final String EXTRA_CARRIER_NAME = "android.telephony.extra.CARRIER_NAME";
1190 
1191     /**
1192      * Broadcast Action: The subscription specific carrier identity has changed.
1193      *
1194      * A specific carrier ID returns the fine-grained carrier ID of the current subscription.
1195      * It can represent the fact that a carrier may be in effect an aggregation of other carriers
1196      * (ie in an MVNO type scenario) where each of these specific carriers which are used to make
1197      * up the actual carrier service may have different carrier configurations.
1198      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
1199      * different carrier configuration for different service offering such as a prepaid plan.
1200      *
1201      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
1202      * about the carrier itself should use the regular carrier ID returned by
1203      * {@link #getSimCarrierId()}.
1204      *
1205      * <p>Similar like {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED}, this intent will be
1206      * sent on the event of {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} while its also
1207      * possible to be sent without {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} when
1208      * specific carrier ID changes while carrier ID remains the same.
1209      * e.g, the same subscription switches to different IMSI could potentially change its
1210      * specific carrier ID while carrier id remains the same.
1211      * @see #getSimSpecificCarrierId()
1212      * @see #getSimCarrierId()
1213      *
1214      * The intent will have the following extra values:
1215      * <ul>
1216      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_ID} The up-to-date specific carrier id of the
1217      *   current subscription.
1218      *   </li>
1219      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_NAME} The up-to-date name of the specific carrier id.
1220      *   </li>
1221      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1222      *   identity.
1223      *   </li>
1224      * </ul>
1225      * <p class="note">This is a protected intent that can only be sent by the system.
1226      */
1227     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1228     public static final String ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED =
1229             "android.telephony.action.SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED";
1230 
1231     /**
1232      * An int extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED} which
1233      * indicates the updated specific carrier id returned by
1234      * {@link TelephonyManager#getSimSpecificCarrierId()}. Note, its possible specific carrier id
1235      * changes while {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} remains the same
1236      * e.g, when subscription switch to different IMSIs.
1237      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1238      * the carrier cannot be identified.
1239      */
1240     public static final String EXTRA_SPECIFIC_CARRIER_ID =
1241             "android.telephony.extra.SPECIFIC_CARRIER_ID";
1242 
1243     /**
1244      * An string extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED}
1245      * which indicates the updated specific carrier name returned by
1246      * {@link TelephonyManager#getSimSpecificCarrierIdName()}.
1247      * <p>it's a user-facing name of the specific carrier id {@link #EXTRA_SPECIFIC_CARRIER_ID}
1248      * e.g, Tracfone-AT&T
1249      */
1250     public static final String EXTRA_SPECIFIC_CARRIER_NAME =
1251             "android.telephony.extra.SPECIFIC_CARRIER_NAME";
1252 
1253     /**
1254      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} to indicate the
1255      * subscription which has changed; or in general whenever a subscription ID needs specified.
1256      */
1257     public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
1258 
1259     /**
1260      * Broadcast Action: The Service Provider string(s) have been updated. Activities or
1261      * services that use these strings should update their display.
1262      *
1263      * <p>The intent will have the following extra values:
1264      * <dl>
1265      *   <dt>{@link #EXTRA_SHOW_PLMN}</dt>
1266      *   <dd>Boolean that indicates whether the PLMN should be shown.</dd>
1267      *   <dt>{@link #EXTRA_PLMN}</dt>
1268      *   <dd>The operator name of the registered network, as a string.</dd>
1269      *   <dt>{@link #EXTRA_SHOW_SPN}</dt>
1270      *   <dd>Boolean that indicates whether the SPN should be shown.</dd>
1271      *   <dt>{@link #EXTRA_SPN}</dt>
1272      *   <dd>The service provider name, as a string.</dd>
1273      *   <dt>{@link #EXTRA_DATA_SPN}</dt>
1274      *   <dd>The service provider name for data service, as a string.</dd>
1275      * </dl>
1276      *
1277      * Note that {@link #EXTRA_SHOW_PLMN} may indicate that {@link #EXTRA_PLMN} should be displayed,
1278      * even though the value for {@link #EXTRA_PLMN} is null. This can happen, for example, if the
1279      * phone has not registered to a network yet. In this case the receiver may substitute an
1280      * appropriate placeholder string (eg, "No service").
1281      *
1282      * It is recommended to display {@link #EXTRA_PLMN} before / above {@link #EXTRA_SPN} if
1283      * both are displayed.
1284      *
1285      * <p>Note: this is a protected intent that can only be sent by the system.
1286      * @hide
1287      */
1288     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1289     public static final String ACTION_SERVICE_PROVIDERS_UPDATED =
1290             "android.telephony.action.SERVICE_PROVIDERS_UPDATED";
1291 
1292     /**
1293      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1294      * whether the PLMN should be shown.
1295      * @hide
1296      */
1297     public static final String EXTRA_SHOW_PLMN = "android.telephony.extra.SHOW_PLMN";
1298 
1299     /**
1300      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1301      * the operator name of the registered network.
1302      * @hide
1303      */
1304     public static final String EXTRA_PLMN = "android.telephony.extra.PLMN";
1305 
1306     /**
1307      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1308      * whether the PLMN should be shown.
1309      * @hide
1310      */
1311     public static final String EXTRA_SHOW_SPN = "android.telephony.extra.SHOW_SPN";
1312 
1313     /**
1314      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1315      * the service provider name.
1316      * @hide
1317      */
1318     public static final String EXTRA_SPN = "android.telephony.extra.SPN";
1319 
1320     /**
1321      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1322      * the service provider name for data service.
1323      * @hide
1324      */
1325     public static final String EXTRA_DATA_SPN = "android.telephony.extra.DATA_SPN";
1326 
1327     /**
1328      * Broadcast intent action indicating that when data stall recovery is attempted by Telephony,
1329      * intended for report every data stall recovery step attempted.
1330      *
1331      * <p>
1332      * The {@link #EXTRA_RECOVERY_ACTION} extra indicates the action associated with the data
1333      * stall recovery.
1334      * The phone id where the data stall recovery is attempted.
1335      *
1336      * <p class="note">
1337      * Requires the READ_PHONE_STATE permission.
1338      *
1339      * <p class="note">
1340      * This is a protected intent that can only be sent by the system.
1341      *
1342      * @see #EXTRA_RECOVERY_ACTION
1343      *
1344      * @hide
1345      */
1346     // TODO(b/78370030) : Restrict this to system applications only
1347     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1348     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1349     public static final String ACTION_DATA_STALL_DETECTED =
1350             "android.intent.action.DATA_STALL_DETECTED";
1351 
1352     /**
1353      * A service action that identifies
1354      * a {@link android.service.carrier.CarrierMessagingClientService} subclass in the
1355      * AndroidManifest.xml.
1356      *
1357      * <p>See {@link android.service.carrier.CarrierMessagingClientService} for the details.
1358      */
1359     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1360     public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE =
1361             "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
1362 
1363     /**
1364      * An int extra used with {@link #ACTION_DATA_STALL_DETECTED} to indicate the
1365      * action associated with the data stall recovery.
1366      *
1367      * @see #ACTION_DATA_STALL_DETECTED
1368      *
1369      * @hide
1370      */
1371     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
1372 
1373     private static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000;
1374 
1375     /**
1376      * Intent sent when an error occurs that debug tools should log and possibly take further
1377      * action such as capturing vendor-specific logs.
1378      *
1379      * A privileged application that reads these events should take appropriate vendor-specific
1380      * action to record the event and collect further information to assist in analysis, debugging,
1381      * and resolution of any associated issue.
1382      *
1383      * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
1384      * should generally be sent at a low rate. Instead, this mechanism should be used for the
1385      * framework to notify a debugging application that an event (such as a bug) has occured
1386      * within the framework if that event should trigger the collection and preservation of other
1387      * more detailed device state for debugging.
1388      *
1389      * <p>At most one application can receive these events and should register a receiver in
1390      * in the application manifest. For performance reasons, if no application to receive these
1391      * events is detected at boot, then these events will not be sent.
1392      *
1393      * <p>Each event will include an {@link EXTRA_ANOMALY_ID} that will uniquely identify the
1394      * event that has occurred. Each event will be sent to the diagnostic monitor only once per
1395      * boot cycle (as another optimization).
1396      *
1397      * @see #EXTRA_ANOMALY_ID
1398      * @see #EXTRA_ANOMALY_DESCRIPTION
1399      * @hide
1400      */
1401     @SystemApi
1402     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1403     public static final String ACTION_ANOMALY_REPORTED =
1404             "android.telephony.action.ANOMALY_REPORTED";
1405 
1406     /**
1407      * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
1408      *
1409      * This field must be included in all {@link ACTION_ANOMALY_REPORTED} events.
1410      *
1411      * @see #ACTION_ANOMALY_REPORTED
1412      * @hide
1413      */
1414     @SystemApi
1415     public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
1416 
1417     /**
1418      * A freeform string description of the Anomaly.
1419      *
1420      * This field is optional for all {@link ACTION_ANOMALY_REPORTED}s, as a guideline should not
1421      * exceed 80 characters, and should be as short as possible to convey the essence of the event.
1422      *
1423      * @see #ACTION_ANOMALY_REPORTED
1424      * @hide
1425      */
1426     @SystemApi
1427     public static final String EXTRA_ANOMALY_DESCRIPTION =
1428             "android.telephony.extra.ANOMALY_DESCRIPTION";
1429 
1430     /**
1431      * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
1432      *
1433      * @hide
1434      */
1435     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1436     public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
1437             "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
1438 
1439     /**
1440      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1441      * to indicate what type of SIM selection is needed.
1442      *
1443      * @hide
1444      */
1445     public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
1446             "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
1447 
1448     /** @hide */
1449     @IntDef({
1450             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE,
1451             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
1452             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE,
1453             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS,
1454             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL
1455     })
1456     @Retention(RetentionPolicy.SOURCE)
1457     public @interface DefaultSubscriptionSelectType{}
1458 
1459     /**
1460      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1461      * to indicate there's no need to re-select any default subscription.
1462      * @hide
1463      */
1464     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
1465 
1466     /**
1467      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1468      * to indicate there's a need to select default data subscription.
1469      * @hide
1470      */
1471     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
1472 
1473     /**
1474      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1475      * to indicate there's a need to select default voice call subscription.
1476      * @hide
1477      */
1478     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
1479 
1480     /**
1481      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1482      * to indicate there's a need to select default sms subscription.
1483      * @hide
1484      */
1485     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
1486 
1487     /**
1488      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1489      * to indicate user to decide whether current SIM should be preferred for all
1490      * data / voice / sms. {@link #EXTRA_SUBSCRIPTION_ID} will specified to indicate
1491      * which subscription should be the default subscription.
1492      * @hide
1493      */
1494     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL = 4;
1495 
1496     /**
1497      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1498      * to indicate that default subscription for data/sms/voice is now determined, that
1499      * it should dismiss any dialog or pop-ups that is asking user to select default sub.
1500      * This is used when, for example, opportunistic subscription is configured. At that
1501      * time the primary becomes default sub there's no need to ask user to select anymore.
1502      * @hide
1503      */
1504     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS = 5;
1505 
1506     /**
1507      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1508      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1509      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1510      *
1511      * @hide
1512      */
1513     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1514             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1515 
1516     /** @hide */
1517     @IntDef({
1518             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1519             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1520     })
1521     @Retention(RetentionPolicy.SOURCE)
1522     public @interface SimCombinationWarningType{}
1523 
1524     /**
1525      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1526      * to indicate there's no SIM combination warning.
1527      * @hide
1528      */
1529     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1530 
1531     /**
1532      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1533      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1534      * @hide
1535      */
1536     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1537 
1538     /**
1539      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1540      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1541      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1542      * name will be "operator1 & operator2".
1543      *
1544      * @hide
1545      */
1546     public static final String EXTRA_SIM_COMBINATION_NAMES =
1547             "android.telephony.extra.SIM_COMBINATION_NAMES";
1548 
1549     /**
1550      * <p>Broadcast Action: The emergency callback mode is changed.
1551      * <ul>
1552      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1553      *   false=ECM off</li>
1554      * </ul>
1555      * <p class="note">
1556      * You can <em>not</em> receive this through components declared
1557      * in manifests, only by explicitly registering for it with
1558      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1559      * android.content.IntentFilter) Context.registerReceiver()}.
1560      *
1561      * <p class="note">This is a protected intent that can only be sent by the system.
1562      *
1563      * @see #EXTRA_PHONE_IN_ECM_STATE
1564      *
1565      * @hide
1566      */
1567     @SystemApi
1568     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1569     @SuppressLint("ActionValue")
1570     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1571             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1572 
1573 
1574     /**
1575      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1576      * Indicates whether the phone is in an emergency phone state.
1577      *
1578      * @hide
1579      */
1580     @SystemApi
1581     public static final String EXTRA_PHONE_IN_ECM_STATE =
1582             "android.telephony.extra.PHONE_IN_ECM_STATE";
1583 
1584     /**
1585      * <p>Broadcast Action: when data connections get redirected with validation failure.
1586      * intended for sim/account status checks and only sent to the specified carrier app
1587      * The intent will have the following extra values:</p>
1588      * <ul>
1589      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1590      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1591      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>redirection url string</dd>
1592      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1593      * </ul>
1594      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1595      * @hide
1596      */
1597     @SuppressLint("ActionValue")
1598     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1599             "com.android.internal.telephony.CARRIER_SIGNAL_REDIRECTED";
1600 
1601     /**
1602      * <p>Broadcast Action: when data connections setup fails.
1603      * intended for sim/account status checks and only sent to the specified carrier app
1604      * The intent will have the following extra values:</p>
1605      * <ul>
1606      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1607      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1608      *   <li>{@link #EXTRA_ERROR_CODE}</li><dd>A integer with dataFailCause.</dd>
1609      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1610      * </ul>
1611      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1612      * @hide
1613      */
1614     @SuppressLint("ActionValue")
1615     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1616             "com.android.internal.telephony.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1617 
1618     /**
1619      * <p>Broadcast Action: when pco value is available.
1620      * intended for sim/account status checks and only sent to the specified carrier app
1621      * The intent will have the following extra values:</p>
1622      * <ul>
1623      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1624      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1625      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>A string with the protocol of the apn connection
1626      *      (IP,IPV6, IPV4V6)</dd>
1627      *   <li>{@link #EXTRA_APN_PROTOCOL_INT}</li><dd>A integer with the protocol of the apn
1628      *      connection (IP,IPV6, IPV4V6)</dd>
1629      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the pco id for the data.</dd>
1630      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of pco data read from modem.</dd>
1631      *   <li>subId</li><dd>Sub Id which associated the data connection.</dd>
1632      * </ul>
1633      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1634      * @hide
1635      */
1636     @SuppressLint("ActionValue")
1637     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1638             "com.android.internal.telephony.CARRIER_SIGNAL_PCO_VALUE";
1639 
1640     /**
1641      * <p>Broadcast Action: when system default network available/unavailable with
1642      * carrier-disabled mobile data. Intended for carrier apps to set/reset carrier actions when
1643      * other network becomes system default network, Wi-Fi for example.
1644      * The intent will have the following extra values:</p>
1645      * <ul>
1646      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1647      *   <dd>A boolean indicates default network available.</dd>
1648      *   <li>subId</li><dd>Sub Id which associated the default data.</dd>
1649      * </ul>
1650      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1651      * @hide
1652      */
1653     @SuppressLint("ActionValue")
1654     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1655             "com.android.internal.telephony.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1656 
1657     /**
1658      * <p>Broadcast Action: when framework reset all carrier actions on sim load or absent.
1659      * intended for carrier apps clean up (clear UI e.g.) and only sent to the specified carrier app
1660      * The intent will have the following extra values:</p>
1661      * <ul>
1662      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1663      * </ul>
1664      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1665      * @hide
1666      */
1667     @SuppressLint("ActionValue")
1668     public static final String ACTION_CARRIER_SIGNAL_RESET =
1669             "com.android.internal.telephony.CARRIER_SIGNAL_RESET";
1670 
1671     // CARRIER_SIGNAL_ACTION extra keys
1672     /**
1673      *  An string extra of redirected url upon {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
1674      *  @hide
1675      */
1676     @SuppressLint("ActionValue")
1677     public static final String EXTRA_REDIRECTION_URL = "redirectionUrl";
1678 
1679     /**
1680      *  An integer extra of error code upon {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}.
1681      *  Check {@link DataFailCause} for all possible values.
1682      *  @hide
1683      */
1684     @SuppressLint("ActionValue")
1685     public static final String EXTRA_ERROR_CODE = "errorCode";
1686 
1687     /**
1688      *  An string extra of corresponding apn type upon
1689      *  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1690      *  {@link #ACTION_CARRIER_SIGNAL_REDIRECTED} and
1691      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1692      *  @deprecated This is kept for backward compatibility reason. Use {@link #EXTRA_APN_TYPE_INT}
1693      *  instead.
1694      *
1695      *  @hide
1696      */
1697     @Deprecated
1698     @SuppressLint("ActionValue")
1699     public static final String EXTRA_APN_TYPE = "apnType";
1700 
1701     /**
1702      *  An string integer of corresponding apn type upon
1703      *  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1704      *  {@link #ACTION_CARRIER_SIGNAL_REDIRECTED} and
1705      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1706      *  Check {@link ApnSetting} TYPE_* for its values.
1707      *  @hide
1708      */
1709     @SuppressLint("ActionValue")
1710     public static final String EXTRA_APN_TYPE_INT = "apnTypeInt";
1711 
1712     /**
1713      *  An string extra with the protocol of the apn connection (IP,IPV6, IPV4V6) upon
1714      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1715      *  @deprecated This is kept for backward compatibility reason.
1716      *  Use {@link #EXTRA_APN_PROTOCOL_INT} instead.
1717      *
1718      *  @hide
1719      */
1720     @Deprecated
1721     @SuppressLint("ActionValue")
1722     public static final String EXTRA_APN_PROTOCOL = "apnProto";
1723 
1724     /**
1725      *  An integer extra with the protocol of the apn connection (IP,IPV6, IPV4V6) upon
1726      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1727      *  Check {@link ApnSetting} PROTOCOL_* for its values.
1728      *  @hide
1729      */
1730     @SuppressLint("ActionValue")
1731     public static final String EXTRA_APN_PROTOCOL_INT = "apnProtoInt";
1732 
1733     /**
1734      *  An integer extra indicating the pco id for the data upon
1735      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1736      *  @hide
1737      */
1738     @SuppressLint("ActionValue")
1739     public static final String EXTRA_PCO_ID = "pcoId";
1740 
1741     /**
1742      *  An extra of byte array of pco data read from modem upon
1743      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1744      *  @hide
1745      */
1746     @SuppressLint("ActionValue")
1747     public static final String EXTRA_PCO_VALUE = "pcoValue";
1748 
1749     /**
1750      *  An boolean extra indicating default network available upon
1751      *  {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcasts.
1752      *  @hide
1753      */
1754     @SuppressLint("ActionValue")
1755     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE = "defaultNetworkAvailable";
1756 
1757     /**
1758      * <p>Broadcast Action: The emergency call state is changed.
1759      * <ul>
1760      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
1761      *   call, false otherwise</li>
1762      * </ul>
1763      * <p class="note">
1764      * You can <em>not</em> receive this through components declared
1765      * in manifests, only by explicitly registering for it with
1766      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1767      * android.content.IntentFilter) Context.registerReceiver()}.
1768      *
1769      * <p class="note">This is a protected intent that can only be sent by the system.
1770      *
1771      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
1772      *
1773      * @hide
1774      */
1775     @SystemApi
1776     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1777     @SuppressLint("ActionValue")
1778     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
1779             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
1780 
1781 
1782     /**
1783      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
1784      * It indicates whether the phone is making an emergency call.
1785      *
1786      * @hide
1787      */
1788     @SystemApi
1789     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
1790             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
1791 
1792     /**
1793      * <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
1794      * <p class="note">.
1795      * This is to pop up a notice to show user that the phone is in emergency callback mode
1796      * and data calls and outgoing sms are blocked.
1797      *
1798      * <p class="note">This is a protected intent that can only be sent by the system.
1799      *
1800      * @hide
1801      */
1802     @SystemApi
1803     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS =
1804             "android.telephony.action.SHOW_NOTICE_ECM_BLOCK_OTHERS";
1805 
1806     /**
1807      * Broadcast Action: The default data subscription has changed in a multi-SIM device.
1808      * This has the following extra values:</p>
1809      * <ul>
1810      *   <li><em>subscription</em> - A int, the current data default subscription.</li>
1811      * </ul>
1812      *
1813      * @hide
1814      */
1815     @SystemApi
1816     @SuppressLint("ActionValue")
1817     public static final String ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED =
1818             "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED";
1819 
1820     /**
1821      * Broadcast Action: The default voice subscription has changed in a mult-SIm device.
1822      * This has the following extra values:</p>
1823      * <ul>
1824      *   <li><em>subscription</em> - A int, the current voice default subscription.</li>
1825      * </ul>
1826      *
1827      * @hide
1828      */
1829     @SystemApi
1830     @SuppressLint("ActionValue")
1831     public static final String ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED =
1832             "android.intent.action.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED";
1833 
1834     /**
1835      * Broadcast Action: This triggers a client initiated OMA-DM session to the OMA server.
1836      * <p class="note">
1837      * Open Mobile Alliance (OMA) Device Management (DM).
1838      *
1839      * This intent is used by the system components to trigger OMA-DM
1840      *
1841      * @hide
1842      */
1843     @SystemApi
1844     @SuppressLint("ActionValue")
1845     public static final String ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE =
1846             "com.android.omadm.service.CONFIGURATION_UPDATE";
1847 
1848     //
1849     //
1850     // Device Info
1851     //
1852     //
1853 
1854     /**
1855      * Returns the software version number for the device, for example,
1856      * the IMEI/SV for GSM phones. Return null if the software version is
1857      * not available.
1858      * <p>
1859      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}.
1860      */
1861     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1862     @Nullable
getDeviceSoftwareVersion()1863     public String getDeviceSoftwareVersion() {
1864         return getDeviceSoftwareVersion(getSlotIndex());
1865     }
1866 
1867     /**
1868      * Returns the software version number for the device, for example,
1869      * the IMEI/SV for GSM phones. Return null if the software version is
1870      * not available.
1871      * <p>
1872      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
1873      *
1874      * @param slotIndex of which deviceID is returned
1875      *
1876      * @hide
1877      */
1878     @SystemApi
1879     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1880     @Nullable
getDeviceSoftwareVersion(int slotIndex)1881     public String getDeviceSoftwareVersion(int slotIndex) {
1882         ITelephony telephony = getITelephony();
1883         if (telephony == null) return null;
1884 
1885         try {
1886             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
1887                     getAttributionTag());
1888         } catch (RemoteException ex) {
1889             return null;
1890         } catch (NullPointerException ex) {
1891             return null;
1892         }
1893     }
1894 
1895     /**
1896      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
1897      * or ESN for CDMA phones. Return null if device ID is not available.
1898      *
1899      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
1900      * restrictions, and apps are recommended to use resettable identifiers (see <a
1901      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
1902      * method can be invoked if one of the following requirements is met:
1903      * <ul>
1904      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
1905      *     is a privileged permission that can only be granted to apps preloaded on the device.
1906      *     <li>If the calling app is the device or profile owner and has been granted the
1907      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
1908      *     owns a managed profile on the device; for more details see <a
1909      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
1910      *     Profile owner access is deprecated and will be removed in a future release.
1911      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
1912      *     active subscription.
1913      *     <li>If the calling app is the default SMS role holder (see {@link
1914      *     RoleManager#isRoleHeld(String)}).
1915      * </ul>
1916      *
1917      * <p>If the calling app does not meet one of these requirements then this method will behave
1918      * as follows:
1919      *
1920      * <ul>
1921      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1922      *     READ_PHONE_STATE permission then null is returned.</li>
1923      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1924      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1925      *     higher, then a SecurityException is thrown.</li>
1926      * </ul>
1927      *
1928      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1929      * MEID for CDMA.
1930      */
1931     @Deprecated
1932     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1933     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()1934     public String getDeviceId() {
1935         try {
1936             ITelephony telephony = getITelephony();
1937             if (telephony == null)
1938                 return null;
1939             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
1940                     mContext.getAttributionTag());
1941         } catch (RemoteException ex) {
1942             return null;
1943         } catch (NullPointerException ex) {
1944             return null;
1945         }
1946     }
1947 
1948     /**
1949      * Returns the unique device ID of a subscription, for example, the IMEI for
1950      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
1951      *
1952      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
1953      * restrictions, and apps are recommended to use resettable identifiers (see <a
1954      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
1955      * method can be invoked if one of the following requirements is met:
1956      * <ul>
1957      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
1958      *     is a privileged permission that can only be granted to apps preloaded on the device.
1959      *     <li>If the calling app is the device or profile owner and has been granted the
1960      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
1961      *     owns a managed profile on the device; for more details see <a
1962      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
1963      *     Profile owner access is deprecated and will be removed in a future release.
1964      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
1965      *     active subscription.
1966      *     <li>If the calling app is the default SMS role holder (see {@link
1967      *     RoleManager#isRoleHeld(String)}).
1968      * </ul>
1969      *
1970      * <p>If the calling app does not meet one of these requirements then this method will behave
1971      * as follows:
1972      *
1973      * <ul>
1974      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1975      *     READ_PHONE_STATE permission then null is returned.</li>
1976      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1977      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1978      *     higher, then a SecurityException is thrown.</li>
1979      * </ul>
1980      *
1981      * @param slotIndex of which deviceID is returned
1982      *
1983      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1984      * MEID for CDMA.
1985      */
1986     @Deprecated
1987     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1988     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)1989     public String getDeviceId(int slotIndex) {
1990         // FIXME this assumes phoneId == slotIndex
1991         try {
1992             IPhoneSubInfo info = getSubscriberInfoService();
1993             if (info == null)
1994                 return null;
1995             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
1996                     mContext.getAttributionTag());
1997         } catch (RemoteException ex) {
1998             return null;
1999         } catch (NullPointerException ex) {
2000             return null;
2001         }
2002     }
2003 
2004     /**
2005      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2006      * available.
2007      *
2008      * See {@link #getImei(int)} for details on the required permissions and behavior
2009      * when the caller does not hold sufficient permissions.
2010      */
2011     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2012     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei()2013     public String getImei() {
2014         return getImei(getSlotIndex());
2015     }
2016 
2017     /**
2018      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2019      * available.
2020      *
2021      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2022      * restrictions, and apps are recommended to use resettable identifiers (see <a
2023      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2024      * method can be invoked if one of the following requirements is met:
2025      * <ul>
2026      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2027      *     is a privileged permission that can only be granted to apps preloaded on the device.
2028      *     <li>If the calling app is the device or profile owner and has been granted the
2029      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2030      *     owns a managed profile on the device; for more details see <a
2031      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2032      *     Profile owner access is deprecated and will be removed in a future release.
2033      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2034      *     active subscription.
2035      *     <li>If the calling app is the default SMS role holder (see {@link
2036      *     RoleManager#isRoleHeld(String)}).
2037      * </ul>
2038      *
2039      * <p>If the calling app does not meet one of these requirements then this method will behave
2040      * as follows:
2041      *
2042      * <ul>
2043      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2044      *     READ_PHONE_STATE permission then null is returned.</li>
2045      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2046      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2047      *     higher, then a SecurityException is thrown.</li>
2048      * </ul>
2049      *
2050      * @param slotIndex of which IMEI is returned
2051      */
2052     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2053     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei(int slotIndex)2054     public String getImei(int slotIndex) {
2055         ITelephony telephony = getITelephony();
2056         if (telephony == null) return null;
2057 
2058         try {
2059             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
2060         } catch (RemoteException ex) {
2061             return null;
2062         } catch (NullPointerException ex) {
2063             return null;
2064         }
2065     }
2066 
2067     /**
2068      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2069      * available.
2070      */
2071     @Nullable
getTypeAllocationCode()2072     public String getTypeAllocationCode() {
2073         return getTypeAllocationCode(getSlotIndex());
2074     }
2075 
2076     /**
2077      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2078      * available.
2079      *
2080      * @param slotIndex of which Type Allocation Code is returned
2081      */
2082     @Nullable
getTypeAllocationCode(int slotIndex)2083     public String getTypeAllocationCode(int slotIndex) {
2084         ITelephony telephony = getITelephony();
2085         if (telephony == null) return null;
2086 
2087         try {
2088             return telephony.getTypeAllocationCodeForSlot(slotIndex);
2089         } catch (RemoteException ex) {
2090             return null;
2091         } catch (NullPointerException ex) {
2092             return null;
2093         }
2094     }
2095 
2096     /**
2097      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2098      *
2099      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2100      * restrictions, and apps are recommended to use resettable identifiers (see <a
2101      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2102      * method can be invoked if one of the following requirements is met:
2103      * <ul>
2104      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2105      *     is a privileged permission that can only be granted to apps preloaded on the device.
2106      *     <li>If the calling app is the device or profile owner and has been granted the
2107      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2108      *     owns a managed profile on the device; for more details see <a
2109      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2110      *     Profile owner access is deprecated and will be removed in a future release.
2111      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2112      *     active subscription.
2113      *     <li>If the calling app is the default SMS role holder (see {@link
2114      *     RoleManager#isRoleHeld(String)}).
2115      * </ul>
2116      *
2117      * <p>If the calling app does not meet one of these requirements then this method will behave
2118      * as follows:
2119      *
2120      * <ul>
2121      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2122      *     READ_PHONE_STATE permission then null is returned.</li>
2123      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2124      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2125      *     higher, then a SecurityException is thrown.</li>
2126      * </ul>
2127      */
2128     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2129     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid()2130     public String getMeid() {
2131         return getMeid(getSlotIndex());
2132     }
2133 
2134     /**
2135      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2136      *
2137      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2138      * restrictions, and apps are recommended to use resettable identifiers (see <a
2139      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2140      * method can be invoked if one of the following requirements is met:
2141      * <ul>
2142      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2143      *     is a privileged permission that can only be granted to apps preloaded on the device.
2144      *     <li>If the calling app is the device or profile owner and has been granted the
2145      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2146      *     owns a managed profile on the device; for more details see <a
2147      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2148      *     Profile owner access is deprecated and will be removed in a future release.
2149      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2150      *     active subscription.
2151      *     <li>If the calling app is the default SMS role holder (see {@link
2152      *     RoleManager#isRoleHeld(String)}).
2153      * </ul>
2154      *
2155      * <p>If the calling app does not meet one of these requirements then this method will behave
2156      * as follows:
2157      *
2158      * <ul>
2159      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2160      *     READ_PHONE_STATE permission then null is returned.</li>
2161      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2162      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2163      *     higher, then a SecurityException is thrown.</li>
2164      * </ul>
2165      *
2166      * @param slotIndex of which MEID is returned
2167      */
2168     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2169     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid(int slotIndex)2170     public String getMeid(int slotIndex) {
2171         ITelephony telephony = getITelephony();
2172         if (telephony == null) return null;
2173 
2174         try {
2175             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
2176                     getAttributionTag());
2177             if (TextUtils.isEmpty(meid)) {
2178                 Log.d(TAG, "getMeid: return null because MEID is not available");
2179                 return null;
2180             }
2181             return meid;
2182         } catch (RemoteException ex) {
2183             return null;
2184         } catch (NullPointerException ex) {
2185             return null;
2186         }
2187     }
2188 
2189     /**
2190      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2191      * available.
2192      */
2193     @Nullable
getManufacturerCode()2194     public String getManufacturerCode() {
2195         return getManufacturerCode(getSlotIndex());
2196     }
2197 
2198     /**
2199      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2200      * available.
2201      *
2202      * @param slotIndex of which Type Allocation Code is returned
2203      */
2204     @Nullable
getManufacturerCode(int slotIndex)2205     public String getManufacturerCode(int slotIndex) {
2206         ITelephony telephony = getITelephony();
2207         if (telephony == null) return null;
2208 
2209         try {
2210             return telephony.getManufacturerCodeForSlot(slotIndex);
2211         } catch (RemoteException ex) {
2212             return null;
2213         } catch (NullPointerException ex) {
2214             return null;
2215         }
2216     }
2217 
2218     /**
2219      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2220      *
2221      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2222      * restrictions, and apps are recommended to use resettable identifiers (see <a
2223      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2224      * method can be invoked if one of the following requirements is met:
2225      * <ul>
2226      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2227      *     is a privileged permission that can only be granted to apps preloaded on the device.
2228      *     <li>If the calling app is the device or profile owner and has been granted the
2229      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2230      *     owns a managed profile on the device; for more details see <a
2231      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2232      *     Profile owner access is deprecated and will be removed in a future release.
2233      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2234      *     <li>If the calling app is the default SMS role holder (see {@link
2235      *     RoleManager#isRoleHeld(String)}).
2236      * </ul>
2237      *
2238      * <p>If the calling app does not meet one of these requirements then this method will behave
2239      * as follows:
2240      *
2241      * <ul>
2242      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2243      *     READ_PHONE_STATE permission then null is returned.</li>
2244      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2245      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2246      *     higher, then a SecurityException is thrown.</li>
2247      * </ul>
2248      */
2249     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2250     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNai()2251     public String getNai() {
2252         return getNaiBySubscriberId(getSubId());
2253     }
2254 
2255     /**
2256      * Returns the NAI. Return null if NAI is not available.
2257      *
2258      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2259      * restrictions, and apps are recommended to use resettable identifiers (see <a
2260      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2261      * method can be invoked if one of the following requirements is met:
2262      * <ul>
2263      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2264      *     is a privileged permission that can only be granted to apps preloaded on the device.
2265      *     <li>If the calling app is the device or profile owner and has been granted the
2266      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2267      *     owns a managed profile on the device; for more details see <a
2268      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2269      *     Profile owner access is deprecated and will be removed in a future release.
2270      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2271      *     <li>If the calling app is the default SMS role holder (see {@link
2272      *     RoleManager#isRoleHeld(String)}).
2273      * </ul>
2274      *
2275      * <p>If the calling app does not meet one of these requirements then this method will behave
2276      * as follows:
2277      *
2278      * <ul>
2279      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2280      *     READ_PHONE_STATE permission then null is returned.</li>
2281      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2282      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2283      *     higher, then a SecurityException is thrown.</li>
2284      * </ul>
2285      *
2286      *  @param slotIndex of which Nai is returned
2287      */
2288     /** {@hide}*/
2289     @UnsupportedAppUsage
getNai(int slotIndex)2290     public String getNai(int slotIndex) {
2291         int[] subId = SubscriptionManager.getSubId(slotIndex);
2292         if (subId == null) {
2293             return null;
2294         }
2295         return getNaiBySubscriberId(subId[0]);
2296     }
2297 
getNaiBySubscriberId(int subId)2298     private String getNaiBySubscriberId(int subId) {
2299         try {
2300             IPhoneSubInfo info = getSubscriberInfoService();
2301             if (info == null)
2302                 return null;
2303             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2304                     mContext.getAttributionTag());
2305             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2306                 Rlog.v(TAG, "Nai = " + nai);
2307             }
2308             return nai;
2309         } catch (RemoteException ex) {
2310             return null;
2311         } catch (NullPointerException ex) {
2312             return null;
2313         }
2314     }
2315 
2316     /**
2317      * Returns the current location of the device.
2318      *<p>
2319      * If there is only one radio in the device and that radio has an LTE connection,
2320      * this method will return null. The implementation must not to try add LTE
2321      * identifiers into the existing cdma/gsm classes.
2322      *<p>
2323      * @return Current location of the device or null if not available.
2324      *
2325      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2326      */
2327     @Deprecated
2328     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getCellLocation()2329     public CellLocation getCellLocation() {
2330         try {
2331             ITelephony telephony = getITelephony();
2332             if (telephony == null) {
2333                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2334                 return null;
2335             }
2336 
2337             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2338                     mContext.getAttributionTag());
2339             CellLocation cl = cellIdentity.asCellLocation();
2340             if (cl == null || cl.isEmpty()) {
2341                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2342                         + " phone type doesn't match CellLocation type");
2343                 return null;
2344             }
2345 
2346             return cl;
2347         } catch (RemoteException ex) {
2348             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2349             return null;
2350         }
2351     }
2352 
2353     /**
2354      * Enables location update notifications.  {@link PhoneStateListener#onCellLocationChanged
2355      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
2356      *
2357      * @hide
2358      */
2359     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
enableLocationUpdates()2360     public void enableLocationUpdates() {
2361         enableLocationUpdates(getSubId());
2362     }
2363 
2364     /**
2365      * Enables location update notifications for a subscription.
2366      * {@link PhoneStateListener#onCellLocationChanged
2367      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
2368      *
2369      * @param subId for which the location updates are enabled
2370      * @hide
2371      */
2372     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
enableLocationUpdates(int subId)2373     public void enableLocationUpdates(int subId) {
2374         try {
2375             ITelephony telephony = getITelephony();
2376             if (telephony != null)
2377                 telephony.enableLocationUpdatesForSubscriber(subId);
2378         } catch (RemoteException ex) {
2379         } catch (NullPointerException ex) {
2380         }
2381     }
2382 
2383     /**
2384      * Disables location update notifications.  {@link PhoneStateListener#onCellLocationChanged
2385      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
2386      *
2387      * @hide
2388      */
2389     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
disableLocationUpdates()2390     public void disableLocationUpdates() {
2391         disableLocationUpdates(getSubId());
2392     }
2393 
2394     /** @hide */
disableLocationUpdates(int subId)2395     public void disableLocationUpdates(int subId) {
2396         try {
2397             ITelephony telephony = getITelephony();
2398             if (telephony != null)
2399                 telephony.disableLocationUpdatesForSubscriber(subId);
2400         } catch (RemoteException ex) {
2401         } catch (NullPointerException ex) {
2402         }
2403     }
2404 
2405     /**
2406      * Returns the neighboring cell information of the device.
2407      *
2408      * @return List of NeighboringCellInfo or null if info unavailable.
2409      *
2410      * @removed
2411      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2412      *             from NeighboringCellInfo, including LTE cell information.
2413      */
2414     @Deprecated
2415     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
getNeighboringCellInfo()2416     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2417         try {
2418             ITelephony telephony = getITelephony();
2419             if (telephony == null)
2420                 return null;
2421             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2422                     mContext.getAttributionTag());
2423         } catch (RemoteException ex) {
2424             return null;
2425         } catch (NullPointerException ex) {
2426             return null;
2427         }
2428     }
2429 
2430     /** No phone radio. */
2431     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2432     /** Phone radio is GSM. */
2433     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2434     /** Phone radio is CDMA. */
2435     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2436     /** Phone is via SIP. */
2437     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2438 
2439     /**
2440      * Phone is via IMS.
2441      *
2442      * @hide
2443      */
2444     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2445 
2446     /**
2447      * Phone is via Third Party.
2448      *
2449      * @hide
2450      */
2451     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2452 
2453     /**
2454      * Returns the current phone type.
2455      * TODO: This is a last minute change and hence hidden.
2456      *
2457      * @see #PHONE_TYPE_NONE
2458      * @see #PHONE_TYPE_GSM
2459      * @see #PHONE_TYPE_CDMA
2460      * @see #PHONE_TYPE_SIP
2461      *
2462      * {@hide}
2463      */
2464     @SystemApi
getCurrentPhoneType()2465     public int getCurrentPhoneType() {
2466         return getCurrentPhoneType(getSubId());
2467     }
2468 
2469     /**
2470      * Returns a constant indicating the device phone type for a subscription.
2471      *
2472      * @see #PHONE_TYPE_NONE
2473      * @see #PHONE_TYPE_GSM
2474      * @see #PHONE_TYPE_CDMA
2475      *
2476      * @param subId for which phone type is returned
2477      * @hide
2478      */
2479     @SystemApi
getCurrentPhoneType(int subId)2480     public int getCurrentPhoneType(int subId) {
2481         int phoneId;
2482         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2483             // if we don't have any sims, we don't have subscriptions, but we
2484             // still may want to know what type of phone we've got.
2485             phoneId = 0;
2486         } else {
2487             phoneId = SubscriptionManager.getPhoneId(subId);
2488         }
2489 
2490         return getCurrentPhoneTypeForSlot(phoneId);
2491     }
2492 
2493     /**
2494      * See getCurrentPhoneType.
2495      *
2496      * @hide
2497      */
getCurrentPhoneTypeForSlot(int slotIndex)2498     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2499         try{
2500             ITelephony telephony = getITelephony();
2501             if (telephony != null) {
2502                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2503             } else {
2504                 // This can happen when the ITelephony interface is not up yet.
2505                 return getPhoneTypeFromProperty(slotIndex);
2506             }
2507         } catch (RemoteException ex) {
2508             // This shouldn't happen in the normal case, as a backup we
2509             // read from the system property.
2510             return getPhoneTypeFromProperty(slotIndex);
2511         } catch (NullPointerException ex) {
2512             // This shouldn't happen in the normal case, as a backup we
2513             // read from the system property.
2514             return getPhoneTypeFromProperty(slotIndex);
2515         }
2516     }
2517 
2518     /**
2519      * Returns a constant indicating the device phone type.  This
2520      * indicates the type of radio used to transmit voice calls.
2521      *
2522      * @see #PHONE_TYPE_NONE
2523      * @see #PHONE_TYPE_GSM
2524      * @see #PHONE_TYPE_CDMA
2525      * @see #PHONE_TYPE_SIP
2526      */
getPhoneType()2527     public int getPhoneType() {
2528         if (!isVoiceCapable()) {
2529             return PHONE_TYPE_NONE;
2530         }
2531         return getCurrentPhoneType();
2532     }
2533 
getPhoneTypeFromProperty()2534     private int getPhoneTypeFromProperty() {
2535         return getPhoneTypeFromProperty(getPhoneId());
2536     }
2537 
2538     /** {@hide} */
2539     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2540     private int getPhoneTypeFromProperty(int phoneId) {
2541         Integer type = getTelephonyProperty(
2542                 phoneId, TelephonyProperties.current_active_phone(), null);
2543         if (type != null) return type;
2544         return getPhoneTypeFromNetworkType(phoneId);
2545     }
2546 
getPhoneTypeFromNetworkType()2547     private int getPhoneTypeFromNetworkType() {
2548         return getPhoneTypeFromNetworkType(getPhoneId());
2549     }
2550 
2551     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2552     private int getPhoneTypeFromNetworkType(int phoneId) {
2553         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2554         // use the system property for default network type.
2555         // This is a fail safe, and can only happen at first boot.
2556         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2557         if (mode != null) {
2558             return TelephonyManager.getPhoneType(mode);
2559         }
2560         return TelephonyManager.PHONE_TYPE_NONE;
2561     }
2562 
2563     /**
2564      * This function returns the type of the phone, depending
2565      * on the network mode.
2566      *
2567      * @param networkMode
2568      * @return Phone Type
2569      *
2570      * @hide
2571      */
2572     @UnsupportedAppUsage
getPhoneType(int networkMode)2573     public static int getPhoneType(int networkMode) {
2574         switch(networkMode) {
2575         case RILConstants.NETWORK_MODE_CDMA:
2576         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2577         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2578             return PhoneConstants.PHONE_TYPE_CDMA;
2579 
2580         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2581         case RILConstants.NETWORK_MODE_GSM_ONLY:
2582         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2583         case RILConstants.NETWORK_MODE_GSM_UMTS:
2584         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2585         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2586         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2587         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2588         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2589         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2590         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2591         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2592         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2593         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2594         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2595         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2596             return PhoneConstants.PHONE_TYPE_GSM;
2597 
2598         // Use CDMA Phone for the global mode including CDMA
2599         case RILConstants.NETWORK_MODE_GLOBAL:
2600         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2601         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2602             return PhoneConstants.PHONE_TYPE_CDMA;
2603 
2604         case RILConstants.NETWORK_MODE_LTE_ONLY:
2605             if (getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
2606                 return PhoneConstants.PHONE_TYPE_CDMA;
2607             } else {
2608                 return PhoneConstants.PHONE_TYPE_GSM;
2609             }
2610         default:
2611             return PhoneConstants.PHONE_TYPE_GSM;
2612         }
2613     }
2614 
2615     /**
2616      * The contents of the /proc/cmdline file
2617      */
2618     @UnsupportedAppUsage
getProcCmdLine()2619     private static String getProcCmdLine()
2620     {
2621         String cmdline = "";
2622         FileInputStream is = null;
2623         try {
2624             is = new FileInputStream("/proc/cmdline");
2625             byte [] buffer = new byte[2048];
2626             int count = is.read(buffer);
2627             if (count > 0) {
2628                 cmdline = new String(buffer, 0, count);
2629             }
2630         } catch (IOException e) {
2631             Rlog.d(TAG, "No /proc/cmdline exception=" + e);
2632         } finally {
2633             if (is != null) {
2634                 try {
2635                     is.close();
2636                 } catch (IOException e) {
2637                 }
2638             }
2639         }
2640         Rlog.d(TAG, "/proc/cmdline=" + cmdline);
2641         return cmdline;
2642     }
2643 
2644     /**
2645      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2646      * @hide
2647      */
2648     @SystemApi
getMaxNumberVerificationTimeoutMillis()2649     public static long getMaxNumberVerificationTimeoutMillis() {
2650         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2651     }
2652 
2653     /** Kernel command line */
2654     private static final String sKernelCmdLine = getProcCmdLine();
2655 
2656     /** Pattern for selecting the product type from the kernel command line */
2657     private static final Pattern sProductTypePattern =
2658         Pattern.compile("\\sproduct_type\\s*=\\s*(\\w+)");
2659 
2660     /** The ProductType used for LTE on CDMA devices */
2661     private static final String sLteOnCdmaProductType =
2662             TelephonyProperties.lte_on_cdma_product_type().orElse("");
2663 
2664     /**
2665      * Return if the current radio is LTE on CDMA. This
2666      * is a tri-state return value as for a period of time
2667      * the mode may be unknown.
2668      *
2669      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
2670      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
2671      *
2672      * @hide
2673      */
2674     @UnsupportedAppUsage
getLteOnCdmaModeStatic()2675     public static int getLteOnCdmaModeStatic() {
2676         int retVal;
2677         int curVal;
2678         String productType = "";
2679 
2680         curVal = TelephonyProperties.lte_on_cdma_device().orElse(
2681             PhoneConstants.LTE_ON_CDMA_UNKNOWN);
2682         retVal = curVal;
2683         if (retVal == PhoneConstants.LTE_ON_CDMA_UNKNOWN) {
2684             Matcher matcher = sProductTypePattern.matcher(sKernelCmdLine);
2685             if (matcher.find()) {
2686                 productType = matcher.group(1);
2687                 if (sLteOnCdmaProductType.equals(productType)) {
2688                     retVal = PhoneConstants.LTE_ON_CDMA_TRUE;
2689                 } else {
2690                     retVal = PhoneConstants.LTE_ON_CDMA_FALSE;
2691                 }
2692             } else {
2693                 retVal = PhoneConstants.LTE_ON_CDMA_FALSE;
2694             }
2695         }
2696 
2697         Rlog.d(TAG, "getLteOnCdmaMode=" + retVal + " curVal=" + curVal +
2698                 " product_type='" + productType +
2699                 "' lteOnCdmaProductType='" + sLteOnCdmaProductType + "'");
2700         return retVal;
2701     }
2702 
2703     //
2704     //
2705     // Current Network
2706     //
2707     //
2708 
2709     /**
2710      * Returns the alphabetic name of current registered operator.
2711      * <p>
2712      * Availability: Only when user is registered to a network. Result may be
2713      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2714      * on a CDMA network).
2715      */
getNetworkOperatorName()2716     public String getNetworkOperatorName() {
2717         return getNetworkOperatorName(getSubId());
2718     }
2719 
2720     /**
2721      * Returns the alphabetic name of current registered operator
2722      * for a particular subscription.
2723      * <p>
2724      * Availability: Only when user is registered to a network. Result may be
2725      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2726      * on a CDMA network).
2727      * @param subId
2728      * @hide
2729      */
2730     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2731     public String getNetworkOperatorName(int subId) {
2732         int phoneId = SubscriptionManager.getPhoneId(subId);
2733         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2734     }
2735 
2736     /**
2737      * Returns the numeric name (MCC+MNC) of current registered operator.
2738      * <p>
2739      * Availability: Only when user is registered to a network. Result may be
2740      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2741      * on a CDMA network).
2742      */
getNetworkOperator()2743     public String getNetworkOperator() {
2744         return getNetworkOperatorForPhone(getPhoneId());
2745     }
2746 
2747     /**
2748      * Returns the numeric name (MCC+MNC) of current registered operator
2749      * for a particular subscription.
2750      * <p>
2751      * Availability: Only when user is registered to a network. Result may be
2752      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2753      * on a CDMA network).
2754      *
2755      * @param subId
2756      * @hide
2757      */
2758     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2759     public String getNetworkOperator(int subId) {
2760         int phoneId = SubscriptionManager.getPhoneId(subId);
2761         return getNetworkOperatorForPhone(phoneId);
2762      }
2763 
2764     /**
2765      * Returns the numeric name (MCC+MNC) of current registered operator
2766      * for a particular subscription.
2767      * <p>
2768      * Availability: Only when user is registered to a network. Result may be
2769      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2770      * on a CDMA network).
2771      *
2772      * @param phoneId
2773      * @hide
2774      **/
2775     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2776     public String getNetworkOperatorForPhone(int phoneId) {
2777         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2778     }
2779 
2780 
2781     /**
2782      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2783      * network specifier is used by {@link
2784      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2785      * android.net.NetworkRequest} that connects through the subscription.
2786      *
2787      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2788      * @see #createForSubscriptionId(int)
2789      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2790      */
getNetworkSpecifier()2791     public String getNetworkSpecifier() {
2792         return String.valueOf(getSubId());
2793     }
2794 
2795     /**
2796      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
2797      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
2798      * default values.
2799      *
2800      * <p>This method may take several seconds to complete, so it should only be called from a
2801      * worker thread.
2802      *
2803      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2804      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2805      *
2806      * @see CarrierConfigManager#getConfigForSubId(int)
2807      * @see #createForSubscriptionId(int)
2808      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2809      */
2810     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2811     @WorkerThread
2812     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCarrierConfig()2813     public PersistableBundle getCarrierConfig() {
2814         CarrierConfigManager carrierConfigManager = mContext
2815                 .getSystemService(CarrierConfigManager.class);
2816         return carrierConfigManager.getConfigForSubId(getSubId());
2817     }
2818 
2819     /**
2820      * Returns true if the device is considered roaming on the current
2821      * network, for GSM purposes.
2822      * <p>
2823      * Availability: Only when user registered to a network.
2824      */
isNetworkRoaming()2825     public boolean isNetworkRoaming() {
2826         return isNetworkRoaming(getSubId());
2827     }
2828 
2829     /**
2830      * Returns true if the device is considered roaming on the current
2831      * network for a subscription.
2832      * <p>
2833      * Availability: Only when user registered to a network.
2834      *
2835      * @param subId
2836      * @hide
2837      */
2838     @UnsupportedAppUsage
isNetworkRoaming(int subId)2839     public boolean isNetworkRoaming(int subId) {
2840         int phoneId = SubscriptionManager.getPhoneId(subId);
2841         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
2842     }
2843 
2844     /**
2845      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2846      * the current registered operator or the cell nearby, if available.
2847      *
2848      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2849      * if on a CDMA network).
2850      * <p>
2851      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2852      * available.
2853      */
getNetworkCountryIso()2854     public String getNetworkCountryIso() {
2855         return getNetworkCountryIso(getSlotIndex());
2856     }
2857 
2858     /**
2859      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2860      * the current registered operator or the cell nearby, if available. This is same as
2861      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
2862      * accessing network country info from the SIM slot that does not have SIM inserted.
2863      *
2864      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2865      * if on a CDMA network).
2866      * <p>
2867      *
2868      * @param slotIndex the SIM slot index to get network country ISO.
2869      *
2870      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2871      * available.
2872      *
2873      * @throws IllegalArgumentException when the slotIndex is invalid.
2874      *
2875      */
2876     @NonNull
getNetworkCountryIso(int slotIndex)2877     public String getNetworkCountryIso(int slotIndex) {
2878         try {
2879             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
2880                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
2881                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
2882             }
2883 
2884             ITelephony telephony = getITelephony();
2885             if (telephony == null) return "";
2886             return telephony.getNetworkCountryIsoForPhone(slotIndex);
2887         } catch (RemoteException ex) {
2888             return "";
2889         }
2890     }
2891 
2892     /**
2893      * @hide
2894      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
2895      */
2896     @Deprecated
2897     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
2898             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)2899     public String getNetworkCountryIsoForPhone(int phoneId) {
2900         return getNetworkCountryIso(phoneId);
2901     }
2902 
2903     /*
2904      * When adding a network type to the list below, make sure to add the correct icon to
2905      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
2906      * Do not add negative types.
2907      */
2908     /** Network type is unknown */
2909     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
2910     /** Current network is GPRS */
2911     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
2912     /** Current network is EDGE */
2913     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
2914     /** Current network is UMTS */
2915     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
2916     /** Current network is CDMA: Either IS95A or IS95B*/
2917     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
2918     /** Current network is EVDO revision 0*/
2919     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
2920     /** Current network is EVDO revision A*/
2921     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
2922     /** Current network is 1xRTT*/
2923     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
2924     /** Current network is HSDPA */
2925     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
2926     /** Current network is HSUPA */
2927     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
2928     /** Current network is HSPA */
2929     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
2930     /** Current network is iDen */
2931     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
2932     /** Current network is EVDO revision B*/
2933     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
2934     /** Current network is LTE */
2935     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
2936     /** Current network is eHRPD */
2937     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
2938     /** Current network is HSPA+ */
2939     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
2940     /** Current network is GSM */
2941     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
2942     /** Current network is TD_SCDMA */
2943     public static final int NETWORK_TYPE_TD_SCDMA =
2944             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
2945     /** Current network is IWLAN */
2946     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
2947     /** Current network is LTE_CA {@hide} */
2948     @UnsupportedAppUsage
2949     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
2950     /** Current network is NR(New Radio) 5G. */
2951     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
2952 
2953     private static final @NetworkType int[] NETWORK_TYPES = {
2954             NETWORK_TYPE_GPRS,
2955             NETWORK_TYPE_EDGE,
2956             NETWORK_TYPE_UMTS,
2957             NETWORK_TYPE_CDMA,
2958             NETWORK_TYPE_EVDO_0,
2959             NETWORK_TYPE_EVDO_A,
2960             NETWORK_TYPE_1xRTT,
2961             NETWORK_TYPE_HSDPA,
2962             NETWORK_TYPE_HSUPA,
2963             NETWORK_TYPE_HSPA,
2964             NETWORK_TYPE_IDEN,
2965             NETWORK_TYPE_EVDO_B,
2966             NETWORK_TYPE_LTE,
2967             NETWORK_TYPE_EHRPD,
2968             NETWORK_TYPE_HSPAP,
2969             NETWORK_TYPE_GSM,
2970             NETWORK_TYPE_TD_SCDMA,
2971             NETWORK_TYPE_IWLAN,
2972             NETWORK_TYPE_LTE_CA,
2973             NETWORK_TYPE_NR
2974     };
2975 
2976     /**
2977      * Return a collection of all network types
2978      * @return network types
2979      *
2980      * @hide
2981      */
getAllNetworkTypes()2982     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
2983         return NETWORK_TYPES;
2984     }
2985 
2986     /**
2987      * Return the current data network type.
2988      *
2989      * @deprecated use {@link #getDataNetworkType()}
2990      * @return the NETWORK_TYPE_xxxx for current data connection.
2991      */
2992     @Deprecated
2993     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNetworkType()2994     public @NetworkType int getNetworkType() {
2995         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
2996     }
2997 
2998     /**
2999      * Returns a constant indicating the radio technology (network type)
3000      * currently in use on the device for a subscription.
3001      * @return the network type
3002      *
3003      * @param subId for which network type is returned
3004      *
3005      * @see #NETWORK_TYPE_UNKNOWN
3006      * @see #NETWORK_TYPE_GPRS
3007      * @see #NETWORK_TYPE_EDGE
3008      * @see #NETWORK_TYPE_UMTS
3009      * @see #NETWORK_TYPE_HSDPA
3010      * @see #NETWORK_TYPE_HSUPA
3011      * @see #NETWORK_TYPE_HSPA
3012      * @see #NETWORK_TYPE_CDMA
3013      * @see #NETWORK_TYPE_EVDO_0
3014      * @see #NETWORK_TYPE_EVDO_A
3015      * @see #NETWORK_TYPE_EVDO_B
3016      * @see #NETWORK_TYPE_1xRTT
3017      * @see #NETWORK_TYPE_IDEN
3018      * @see #NETWORK_TYPE_LTE
3019      * @see #NETWORK_TYPE_EHRPD
3020      * @see #NETWORK_TYPE_HSPAP
3021      * @see #NETWORK_TYPE_NR
3022      *
3023      * @hide
3024      */
3025     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3026     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)3027     public int getNetworkType(int subId) {
3028         try {
3029             ITelephony telephony = getITelephony();
3030             if (telephony != null) {
3031                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
3032                         getAttributionTag());
3033             } else {
3034                 // This can happen when the ITelephony interface is not up yet.
3035                 return NETWORK_TYPE_UNKNOWN;
3036             }
3037         } catch (RemoteException ex) {
3038             // This shouldn't happen in the normal case
3039             return NETWORK_TYPE_UNKNOWN;
3040         } catch (NullPointerException ex) {
3041             // This could happen before phone restarts due to crashing
3042             return NETWORK_TYPE_UNKNOWN;
3043         }
3044     }
3045 
3046     /**
3047      * Returns a constant indicating the radio technology (network type)
3048      * currently in use on the device for data transmission.
3049      *
3050      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
3051      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
3052      *
3053      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3054      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3055      *
3056      * @return the network type
3057      *
3058      * @see #NETWORK_TYPE_UNKNOWN
3059      * @see #NETWORK_TYPE_GPRS
3060      * @see #NETWORK_TYPE_EDGE
3061      * @see #NETWORK_TYPE_UMTS
3062      * @see #NETWORK_TYPE_HSDPA
3063      * @see #NETWORK_TYPE_HSUPA
3064      * @see #NETWORK_TYPE_HSPA
3065      * @see #NETWORK_TYPE_CDMA
3066      * @see #NETWORK_TYPE_EVDO_0
3067      * @see #NETWORK_TYPE_EVDO_A
3068      * @see #NETWORK_TYPE_EVDO_B
3069      * @see #NETWORK_TYPE_1xRTT
3070      * @see #NETWORK_TYPE_IDEN
3071      * @see #NETWORK_TYPE_LTE
3072      * @see #NETWORK_TYPE_EHRPD
3073      * @see #NETWORK_TYPE_HSPAP
3074      * @see #NETWORK_TYPE_NR
3075      */
3076     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3077     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getDataNetworkType()3078     public @NetworkType int getDataNetworkType() {
3079         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3080     }
3081 
3082     /**
3083      * Returns a constant indicating the radio technology (network type)
3084      * currently in use on the device for data transmission for a subscription
3085      * @return the network type
3086      *
3087      * @param subId for which network type is returned
3088      * @hide
3089      */
3090     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3091     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)3092     public int getDataNetworkType(int subId) {
3093         try{
3094             ITelephony telephony = getITelephony();
3095             if (telephony != null) {
3096                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
3097                         getAttributionTag());
3098             } else {
3099                 // This can happen when the ITelephony interface is not up yet.
3100                 return NETWORK_TYPE_UNKNOWN;
3101             }
3102         } catch(RemoteException ex) {
3103             // This shouldn't happen in the normal case
3104             return NETWORK_TYPE_UNKNOWN;
3105         } catch (NullPointerException ex) {
3106             // This could happen before phone restarts due to crashing
3107             return NETWORK_TYPE_UNKNOWN;
3108         }
3109     }
3110 
3111     /**
3112      * Returns the NETWORK_TYPE_xxxx for voice
3113      *
3114      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3115      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3116      */
3117     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3118     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceNetworkType()3119     public @NetworkType int getVoiceNetworkType() {
3120         return getVoiceNetworkType(getSubId());
3121     }
3122 
3123     /**
3124      * Returns the NETWORK_TYPE_xxxx for voice for a subId
3125      * @hide
3126      */
3127     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3128     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)3129     public int getVoiceNetworkType(int subId) {
3130         try{
3131             ITelephony telephony = getITelephony();
3132             if (telephony != null) {
3133                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
3134                         getAttributionTag());
3135             } else {
3136                 // This can happen when the ITelephony interface is not up yet.
3137                 return NETWORK_TYPE_UNKNOWN;
3138             }
3139         } catch(RemoteException ex) {
3140             // This shouldn't happen in the normal case
3141             return NETWORK_TYPE_UNKNOWN;
3142         } catch (NullPointerException ex) {
3143             // This could happen before phone restarts due to crashing
3144             return NETWORK_TYPE_UNKNOWN;
3145         }
3146     }
3147 
3148     /**
3149      * Returns a string representation of the radio technology (network type)
3150      * currently in use on the device.
3151      * @return the name of the radio technology
3152      *
3153      * @hide pending API council review
3154      */
3155     @UnsupportedAppUsage
getNetworkTypeName()3156     public String getNetworkTypeName() {
3157         return getNetworkTypeName(getNetworkType());
3158     }
3159 
3160     /**
3161      * Returns a string representation of the radio technology (network type)
3162      * currently in use on the device.
3163      * @param subId for which network type is returned
3164      * @return the name of the radio technology
3165      *
3166      */
3167     /** {@hide} */
3168     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)3169     public static String getNetworkTypeName(@NetworkType int type) {
3170         switch (type) {
3171             case NETWORK_TYPE_GPRS:
3172                 return "GPRS";
3173             case NETWORK_TYPE_EDGE:
3174                 return "EDGE";
3175             case NETWORK_TYPE_UMTS:
3176                 return "UMTS";
3177             case NETWORK_TYPE_HSDPA:
3178                 return "HSDPA";
3179             case NETWORK_TYPE_HSUPA:
3180                 return "HSUPA";
3181             case NETWORK_TYPE_HSPA:
3182                 return "HSPA";
3183             case NETWORK_TYPE_CDMA:
3184                 return "CDMA";
3185             case NETWORK_TYPE_EVDO_0:
3186                 return "CDMA - EvDo rev. 0";
3187             case NETWORK_TYPE_EVDO_A:
3188                 return "CDMA - EvDo rev. A";
3189             case NETWORK_TYPE_EVDO_B:
3190                 return "CDMA - EvDo rev. B";
3191             case NETWORK_TYPE_1xRTT:
3192                 return "CDMA - 1xRTT";
3193             case NETWORK_TYPE_LTE:
3194                 return "LTE";
3195             case NETWORK_TYPE_EHRPD:
3196                 return "CDMA - eHRPD";
3197             case NETWORK_TYPE_IDEN:
3198                 return "iDEN";
3199             case NETWORK_TYPE_HSPAP:
3200                 return "HSPA+";
3201             case NETWORK_TYPE_GSM:
3202                 return "GSM";
3203             case NETWORK_TYPE_TD_SCDMA:
3204                 return "TD_SCDMA";
3205             case NETWORK_TYPE_IWLAN:
3206                 return "IWLAN";
3207             case NETWORK_TYPE_LTE_CA:
3208                 return "LTE_CA";
3209             case NETWORK_TYPE_NR:
3210                 return "NR";
3211             default:
3212                 return "UNKNOWN";
3213         }
3214     }
3215 
3216     /**
3217      * Returns the bitmask for a given technology (network type)
3218      * @param networkType for which bitmask is returned
3219      * @return the network type bitmask
3220      * {@hide}
3221      */
getBitMaskForNetworkType(@etworkType int networkType)3222     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
3223         switch(networkType) {
3224             case NETWORK_TYPE_GSM:
3225                 return NETWORK_TYPE_BITMASK_GSM;
3226             case NETWORK_TYPE_GPRS:
3227                 return NETWORK_TYPE_BITMASK_GPRS;
3228             case NETWORK_TYPE_EDGE:
3229                 return NETWORK_TYPE_BITMASK_EDGE;
3230             case NETWORK_TYPE_CDMA:
3231                 return NETWORK_TYPE_BITMASK_CDMA;
3232             case NETWORK_TYPE_1xRTT:
3233                 return NETWORK_TYPE_BITMASK_1xRTT;
3234             case NETWORK_TYPE_EVDO_0:
3235                 return NETWORK_TYPE_BITMASK_EVDO_0;
3236             case NETWORK_TYPE_EVDO_A:
3237                 return NETWORK_TYPE_BITMASK_EVDO_A;
3238             case NETWORK_TYPE_EVDO_B:
3239                 return NETWORK_TYPE_BITMASK_EVDO_B;
3240             case NETWORK_TYPE_EHRPD:
3241                 return NETWORK_TYPE_BITMASK_EHRPD;
3242             case NETWORK_TYPE_HSUPA:
3243                 return NETWORK_TYPE_BITMASK_HSUPA;
3244             case NETWORK_TYPE_HSDPA:
3245                 return NETWORK_TYPE_BITMASK_HSDPA;
3246             case NETWORK_TYPE_HSPA:
3247                 return NETWORK_TYPE_BITMASK_HSPA;
3248             case NETWORK_TYPE_HSPAP:
3249                 return NETWORK_TYPE_BITMASK_HSPAP;
3250             case NETWORK_TYPE_UMTS:
3251                 return NETWORK_TYPE_BITMASK_UMTS;
3252             case NETWORK_TYPE_TD_SCDMA:
3253                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
3254             case NETWORK_TYPE_LTE:
3255                 return NETWORK_TYPE_BITMASK_LTE;
3256             case NETWORK_TYPE_LTE_CA:
3257                 return NETWORK_TYPE_BITMASK_LTE_CA;
3258             case NETWORK_TYPE_NR:
3259                 return NETWORK_TYPE_BITMASK_NR;
3260             default:
3261                 return NETWORK_TYPE_BITMASK_UNKNOWN;
3262         }
3263     }
3264 
3265     //
3266     //
3267     // SIM Card
3268     //
3269     //
3270 
3271     /** @hide */
3272     @IntDef(prefix = {"SIM_STATE_"},
3273             value = {
3274                     SIM_STATE_UNKNOWN,
3275                     SIM_STATE_ABSENT,
3276                     SIM_STATE_PIN_REQUIRED,
3277                     SIM_STATE_PUK_REQUIRED,
3278                     SIM_STATE_NETWORK_LOCKED,
3279                     SIM_STATE_READY,
3280                     SIM_STATE_NOT_READY,
3281                     SIM_STATE_PERM_DISABLED,
3282                     SIM_STATE_CARD_IO_ERROR,
3283                     SIM_STATE_CARD_RESTRICTED,
3284                     SIM_STATE_LOADED,
3285                     SIM_STATE_PRESENT,
3286             })
3287     public @interface SimState {}
3288 
3289     /**
3290      * SIM card state: Unknown. Signifies that the SIM is in transition
3291      * between states. For example, when the user inputs the SIM pin
3292      * under PIN_REQUIRED state, a query for sim status returns
3293      * this state before turning to SIM_STATE_READY.
3294      *
3295      * These are the ordinal value of IccCardConstants.State.
3296      */
3297 
3298     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
3299     /** SIM card state: no SIM card is available in the device */
3300     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3301     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3302     public static final int SIM_STATE_PIN_REQUIRED =
3303             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3304     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3305     public static final int SIM_STATE_PUK_REQUIRED =
3306             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3307     /** SIM card state: Locked: requires a network PIN to unlock */
3308     public static final int SIM_STATE_NETWORK_LOCKED =
3309             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3310     /** SIM card state: Ready */
3311     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3312     /** SIM card state: SIM Card is NOT READY */
3313     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3314     /** SIM card state: SIM Card Error, permanently disabled */
3315     public static final int SIM_STATE_PERM_DISABLED =
3316             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3317     /** SIM card state: SIM Card Error, present but faulty */
3318     public static final int SIM_STATE_CARD_IO_ERROR =
3319             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3320     /** SIM card state: SIM Card restricted, present but not usable due to
3321      * carrier restrictions.
3322      */
3323     public static final int SIM_STATE_CARD_RESTRICTED =
3324             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3325     /**
3326      * SIM card state: Loaded: SIM card applications have been loaded
3327      * @hide
3328      */
3329     @SystemApi
3330     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3331     /**
3332      * SIM card state: SIM Card is present
3333      * @hide
3334      */
3335     @SystemApi
3336     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3337 
3338     /**
3339      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3340      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3341      *
3342      * @hide
3343      */
3344     @SystemApi
3345     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3346 
3347     /**
3348      * Broadcast Action: The sim card state has changed.
3349      * The intent will have the following extra values:</p>
3350      * <dl>
3351      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3352      *   <dd>The sim card state. One of:
3353      *     <dl>
3354      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3355      *       <dd>SIM card not found</dd>
3356      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3357      *       <dd>SIM card IO error</dd>
3358      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3359      *       <dd>SIM card is restricted</dd>
3360      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3361      *       <dd>SIM card is present</dd>
3362      *     </dl>
3363      *   </dd>
3364      * </dl>
3365      *
3366      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3367      *
3368      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3369      *
3370      * <p class="note">This is a protected intent that can only be sent by the system.
3371      * @hide
3372      */
3373     @SystemApi
3374     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3375     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3376             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3377 
3378     /**
3379      * Broadcast Action: The sim application state has changed.
3380      * The intent will have the following extra values:</p>
3381      * <dl>
3382      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3383      *   <dd>The sim application state. One of:
3384      *     <dl>
3385      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3386      *       <dd>SIM card applications not ready</dd>
3387      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3388      *       <dd>SIM card PIN locked</dd>
3389      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3390      *       <dd>SIM card PUK locked</dd>
3391      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3392      *       <dd>SIM card network locked</dd>
3393      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3394      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3395      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3396      *       <dd>SIM card data loaded</dd>
3397      *     </dl>
3398      *   </dd>
3399      * </dl>
3400      *
3401      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3402      *
3403      * <p class="note">The current state can also be queried using
3404      * {@link #getSimApplicationState()}.
3405      *
3406      * <p class="note">This is a protected intent that can only be sent by the system.
3407      * @hide
3408      */
3409     @SystemApi
3410     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3411     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3412             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3413 
3414     /**
3415      * Broadcast Action: Status of the SIM slots on the device has changed.
3416      *
3417      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3418      *
3419      * <p class="note">The status can be queried using
3420      * {@link #getUiccSlotsInfo()}
3421      *
3422      * <p class="note">This is a protected intent that can only be sent by the system.
3423      * @hide
3424      */
3425     @SystemApi
3426     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3427     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3428             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3429 
3430     /**
3431      * Broadcast Action: A debug code has been entered in the dialer.
3432      * <p>
3433      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3434      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3435      * (see {@link #hasCarrierPrivileges}).
3436      * <p>
3437      * These "secret codes" are used to activate developer menus by dialing certain codes.
3438      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3439      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3440      * receiver would be woken up even if it is not currently running.
3441      * <p>
3442      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3443      * in the next Android version.
3444      * Before that both of these two actions will be broadcast.
3445      */
3446     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3447     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3448 
3449     /**
3450      * @return true if a ICC card is present
3451      */
hasIccCard()3452     public boolean hasIccCard() {
3453         return hasIccCard(getSlotIndex());
3454     }
3455 
3456     /**
3457      * @return true if a ICC card is present for a subscription
3458      *
3459      * @param slotIndex for which icc card presence is checked
3460      */
3461     /** {@hide} */
3462     // FIXME Input argument slotIndex should be of type int
3463     @UnsupportedAppUsage
hasIccCard(int slotIndex)3464     public boolean hasIccCard(int slotIndex) {
3465 
3466         try {
3467             ITelephony telephony = getITelephony();
3468             if (telephony == null)
3469                 return false;
3470             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3471         } catch (RemoteException ex) {
3472             // Assume no ICC card if remote exception which shouldn't happen
3473             return false;
3474         } catch (NullPointerException ex) {
3475             // This could happen before phone restarts due to crashing
3476             return false;
3477         }
3478     }
3479 
3480     /**
3481      * Returns a constant indicating the state of the default SIM card.
3482      *
3483      * @see #SIM_STATE_UNKNOWN
3484      * @see #SIM_STATE_ABSENT
3485      * @see #SIM_STATE_PIN_REQUIRED
3486      * @see #SIM_STATE_PUK_REQUIRED
3487      * @see #SIM_STATE_NETWORK_LOCKED
3488      * @see #SIM_STATE_READY
3489      * @see #SIM_STATE_NOT_READY
3490      * @see #SIM_STATE_PERM_DISABLED
3491      * @see #SIM_STATE_CARD_IO_ERROR
3492      * @see #SIM_STATE_CARD_RESTRICTED
3493      */
getSimState()3494     public @SimState int getSimState() {
3495         int simState = getSimStateIncludingLoaded();
3496         if (simState == SIM_STATE_LOADED) {
3497             simState = SIM_STATE_READY;
3498         }
3499         return simState;
3500     }
3501 
getSimStateIncludingLoaded()3502     private @SimState int getSimStateIncludingLoaded() {
3503         int slotIndex = getSlotIndex();
3504         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3505         // sim state
3506         if (slotIndex < 0) {
3507             // query for all slots and return absent if all sim states are absent, otherwise
3508             // return unknown
3509             for (int i = 0; i < getPhoneCount(); i++) {
3510                 int simState = getSimState(i);
3511                 if (simState != SIM_STATE_ABSENT) {
3512                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3513                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3514                     return SIM_STATE_UNKNOWN;
3515                 }
3516             }
3517             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3518                     "state as absent");
3519             return SIM_STATE_ABSENT;
3520         }
3521         return SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3522     }
3523 
3524     /**
3525      * Returns a constant indicating the state of the default SIM card.
3526      *
3527      * @see #SIM_STATE_UNKNOWN
3528      * @see #SIM_STATE_ABSENT
3529      * @see #SIM_STATE_CARD_IO_ERROR
3530      * @see #SIM_STATE_CARD_RESTRICTED
3531      * @see #SIM_STATE_PRESENT
3532      *
3533      * @hide
3534      */
3535     @SystemApi
getSimCardState()3536     public @SimState int getSimCardState() {
3537         int simState = getSimState();
3538         return getSimCardStateFromSimState(simState);
3539     }
3540 
3541     /**
3542      * Returns a constant indicating the state of the device SIM card in a physical slot.
3543      *
3544      * @param physicalSlotIndex physical slot index
3545      *
3546      * @see #SIM_STATE_UNKNOWN
3547      * @see #SIM_STATE_ABSENT
3548      * @see #SIM_STATE_CARD_IO_ERROR
3549      * @see #SIM_STATE_CARD_RESTRICTED
3550      * @see #SIM_STATE_PRESENT
3551      *
3552      * @hide
3553      */
3554     @SystemApi
3555     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimCardState(int physicalSlotIndex)3556     public @SimState int getSimCardState(int physicalSlotIndex) {
3557         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex));
3558         return getSimCardStateFromSimState(simState);
3559     }
3560 
3561     /**
3562      * Converts SIM state to SIM card state.
3563      * @param simState
3564      * @return SIM card state
3565      */
getSimCardStateFromSimState(int simState)3566     private @SimState int getSimCardStateFromSimState(int simState) {
3567         switch (simState) {
3568             case SIM_STATE_UNKNOWN:
3569             case SIM_STATE_ABSENT:
3570             case SIM_STATE_CARD_IO_ERROR:
3571             case SIM_STATE_CARD_RESTRICTED:
3572                 return simState;
3573             default:
3574                 return SIM_STATE_PRESENT;
3575         }
3576     }
3577 
3578     /**
3579      * Converts a physical slot index to logical slot index.
3580      * @param physicalSlotIndex physical slot index
3581      * @return logical slot index
3582      */
getLogicalSlotIndex(int physicalSlotIndex)3583     private int getLogicalSlotIndex(int physicalSlotIndex) {
3584         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3585         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length) {
3586             return slotInfos[physicalSlotIndex].getLogicalSlotIdx();
3587         }
3588 
3589         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3590     }
3591 
3592     /**
3593      * Returns a constant indicating the state of the card applications on the default SIM card.
3594      *
3595      * @see #SIM_STATE_UNKNOWN
3596      * @see #SIM_STATE_PIN_REQUIRED
3597      * @see #SIM_STATE_PUK_REQUIRED
3598      * @see #SIM_STATE_NETWORK_LOCKED
3599      * @see #SIM_STATE_NOT_READY
3600      * @see #SIM_STATE_PERM_DISABLED
3601      * @see #SIM_STATE_LOADED
3602      *
3603      * @hide
3604      */
3605     @SystemApi
getSimApplicationState()3606     public @SimState int getSimApplicationState() {
3607         int simState = getSimStateIncludingLoaded();
3608         return getSimApplicationStateFromSimState(simState);
3609     }
3610 
3611     /**
3612      * Returns a constant indicating the state of the card applications on the device SIM card in
3613      * a physical slot.
3614      *
3615      * @param physicalSlotIndex physical slot index
3616      *
3617      * @see #SIM_STATE_UNKNOWN
3618      * @see #SIM_STATE_PIN_REQUIRED
3619      * @see #SIM_STATE_PUK_REQUIRED
3620      * @see #SIM_STATE_NETWORK_LOCKED
3621      * @see #SIM_STATE_NOT_READY
3622      * @see #SIM_STATE_PERM_DISABLED
3623      * @see #SIM_STATE_LOADED
3624      *
3625      * @hide
3626      */
3627     @SystemApi
3628     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimApplicationState(int physicalSlotIndex)3629     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3630         int simState =
3631                 SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex));
3632         return getSimApplicationStateFromSimState(simState);
3633     }
3634 
3635     /**
3636      * Converts SIM state to SIM application state.
3637      * @param simState
3638      * @return SIM application state
3639      */
getSimApplicationStateFromSimState(int simState)3640     private @SimState int getSimApplicationStateFromSimState(int simState) {
3641         switch (simState) {
3642             case SIM_STATE_UNKNOWN:
3643             case SIM_STATE_ABSENT:
3644             case SIM_STATE_CARD_IO_ERROR:
3645             case SIM_STATE_CARD_RESTRICTED:
3646                 return SIM_STATE_UNKNOWN;
3647             case SIM_STATE_READY:
3648                 // Ready is not a valid state anymore. The state that is broadcast goes from
3649                 // NOT_READY to either LOCKED or LOADED.
3650                 return SIM_STATE_NOT_READY;
3651             default:
3652                 return simState;
3653         }
3654     }
3655 
3656 
3657     /**
3658      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
3659      * on the UICC card.
3660      *
3661      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
3662      *
3663      * @param appType the uicc app type like {@link APPTYPE_CSIM}
3664      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
3665      * @hide
3666      */
3667     @SystemApi
3668     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApplicationOnUicc(@iccAppType int appType)3669     public boolean isApplicationOnUicc(@UiccAppType int appType) {
3670         try {
3671             ITelephony service = getITelephony();
3672             if (service != null) {
3673                 return service.isApplicationOnUicc(getSubId(), appType);
3674             }
3675         } catch (RemoteException e) {
3676             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
3677         }
3678         return false;
3679     }
3680 
3681     /**
3682      * Returns a constant indicating the state of the device SIM card in a logical slot.
3683      *
3684      * @param slotIndex logical slot index
3685      *
3686      * @see #SIM_STATE_UNKNOWN
3687      * @see #SIM_STATE_ABSENT
3688      * @see #SIM_STATE_PIN_REQUIRED
3689      * @see #SIM_STATE_PUK_REQUIRED
3690      * @see #SIM_STATE_NETWORK_LOCKED
3691      * @see #SIM_STATE_READY
3692      * @see #SIM_STATE_NOT_READY
3693      * @see #SIM_STATE_PERM_DISABLED
3694      * @see #SIM_STATE_CARD_IO_ERROR
3695      * @see #SIM_STATE_CARD_RESTRICTED
3696      */
getSimState(int slotIndex)3697     public @SimState int getSimState(int slotIndex) {
3698         int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3699         if (simState == SIM_STATE_LOADED) {
3700             simState = SIM_STATE_READY;
3701         }
3702         return simState;
3703     }
3704 
3705     /**
3706      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3707      * provider of the SIM. 5 or 6 decimal digits.
3708      * <p>
3709      * Availability: SIM state must be {@link #SIM_STATE_READY}
3710      *
3711      * @see #getSimState
3712      */
getSimOperator()3713     public String getSimOperator() {
3714         return getSimOperatorNumeric();
3715     }
3716 
3717     /**
3718      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3719      * provider of the SIM. 5 or 6 decimal digits.
3720      * <p>
3721      * Availability: SIM state must be {@link #SIM_STATE_READY}
3722      *
3723      * @see #getSimState
3724      *
3725      * @param subId for which SimOperator is returned
3726      * @hide
3727      */
3728     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)3729     public String getSimOperator(int subId) {
3730         return getSimOperatorNumeric(subId);
3731     }
3732 
3733     /**
3734      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3735      * provider of the SIM. 5 or 6 decimal digits.
3736      * <p>
3737      * Availability: SIM state must be {@link #SIM_STATE_READY}
3738      *
3739      * @see #getSimState
3740      * @hide
3741      */
3742     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()3743     public String getSimOperatorNumeric() {
3744         int subId = mSubId;
3745         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3746             subId = SubscriptionManager.getDefaultDataSubscriptionId();
3747             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3748                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
3749                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3750                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
3751                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3752                         subId = SubscriptionManager.getDefaultSubscriptionId();
3753                     }
3754                 }
3755             }
3756         }
3757         return getSimOperatorNumeric(subId);
3758     }
3759 
3760     /**
3761      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3762      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3763      * <p>
3764      * Availability: SIM state must be {@link #SIM_STATE_READY}
3765      *
3766      * @see #getSimState
3767      *
3768      * @param subId for which SimOperator is returned
3769      * @hide
3770      */
3771     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)3772     public String getSimOperatorNumeric(int subId) {
3773         int phoneId = SubscriptionManager.getPhoneId(subId);
3774         return getSimOperatorNumericForPhone(phoneId);
3775     }
3776 
3777     /**
3778      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3779      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3780      * <p>
3781      *
3782      * @param phoneId for which SimOperator is returned
3783      * @hide
3784      */
3785     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)3786     public String getSimOperatorNumericForPhone(int phoneId) {
3787         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
3788     }
3789 
3790     /**
3791      * Returns the Service Provider Name (SPN).
3792      * <p>
3793      * Availability: SIM state must be {@link #SIM_STATE_READY}
3794      *
3795      * @see #getSimState
3796      */
getSimOperatorName()3797     public String getSimOperatorName() {
3798         return getSimOperatorNameForPhone(getPhoneId());
3799     }
3800 
3801     /**
3802      * Returns the Service Provider Name (SPN).
3803      * <p>
3804      * Availability: SIM state must be {@link #SIM_STATE_READY}
3805      *
3806      * @see #getSimState
3807      *
3808      * @param subId for which SimOperatorName is returned
3809      * @hide
3810      */
3811     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)3812     public String getSimOperatorName(int subId) {
3813         int phoneId = SubscriptionManager.getPhoneId(subId);
3814         return getSimOperatorNameForPhone(phoneId);
3815     }
3816 
3817     /**
3818      * Returns the Service Provider Name (SPN).
3819      *
3820      * @hide
3821      */
3822     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)3823     public String getSimOperatorNameForPhone(int phoneId) {
3824         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
3825     }
3826 
3827     /**
3828      * Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
3829      * <p>
3830      * The ISO-3166-1 alpha-2 country code is provided in lowercase 2 character format.
3831      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string is not
3832      * available.
3833      */
getSimCountryIso()3834     public String getSimCountryIso() {
3835         return getSimCountryIsoForPhone(getPhoneId());
3836     }
3837 
3838     /**
3839      * Returns the ISO country code equivalent for the SIM provider's country code.
3840      *
3841      * @param subId for which SimCountryIso is returned
3842      * @hide
3843      */
3844     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)3845     public static String getSimCountryIso(int subId) {
3846         int phoneId = SubscriptionManager.getPhoneId(subId);
3847         return getSimCountryIsoForPhone(phoneId);
3848     }
3849 
3850     /**
3851      * Returns the ISO country code equivalent for the SIM provider's country code.
3852      *
3853      * @hide
3854      */
3855     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)3856     public static String getSimCountryIsoForPhone(int phoneId) {
3857         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
3858     }
3859 
3860     /**
3861      * Returns the serial number of the SIM, if applicable. Return null if it is
3862      * unavailable.
3863      *
3864      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
3865      * restrictions, and apps are recommended to use resettable identifiers (see <a
3866      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
3867      * method can be invoked if one of the following requirements is met:
3868      * <ul>
3869      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
3870      *     is a privileged permission that can only be granted to apps preloaded on the device.
3871      *     <li>If the calling app is the device or profile owner and has been granted the
3872      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
3873      *     owns a managed profile on the device; for more details see <a
3874      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
3875      *     Profile owner access is deprecated and will be removed in a future release.
3876      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3877      *     <li>If the calling app is the default SMS role holder (see {@link
3878      *     RoleManager#isRoleHeld(String)}).
3879      * </ul>
3880      *
3881      * <p>If the calling app does not meet one of these requirements then this method will behave
3882      * as follows:
3883      *
3884      * <ul>
3885      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3886      *     READ_PHONE_STATE permission then null is returned.</li>
3887      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3888      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3889      *     higher, then a SecurityException is thrown.</li>
3890      * </ul>
3891      */
3892     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
3893     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimSerialNumber()3894     public String getSimSerialNumber() {
3895          return getSimSerialNumber(getSubId());
3896     }
3897 
3898     /**
3899      * Returns the serial number for the given subscription, if applicable. Return null if it is
3900      * unavailable.
3901      *
3902      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
3903      * restrictions, and apps are recommended to use resettable identifiers (see <a
3904      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
3905      * method can be invoked if one of the following requirements is met:
3906      * <ul>
3907      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
3908      *     is a privileged permission that can only be granted to apps preloaded on the device.
3909      *     <li>If the calling app is the device or profile owner and has been granted the
3910      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
3911      *     owns a managed profile on the device; for more details see <a
3912      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
3913      *     Profile owner access is deprecated and will be removed in a future release.
3914      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3915      *     <li>If the calling app is the default SMS role holder (see {@link
3916      *     RoleManager#isRoleHeld(String)}).
3917      * </ul>
3918      *
3919      * <p>If the calling app does not meet one of these requirements then this method will behave
3920      * as follows:
3921      *
3922      * <ul>
3923      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3924      *     READ_PHONE_STATE permission then null is returned.</li>
3925      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3926      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3927      *     higher, then a SecurityException is thrown.</li>
3928      * </ul>
3929      *
3930      * @param subId for which Sim Serial number is returned
3931      * @hide
3932      */
3933     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3934     @UnsupportedAppUsage
getSimSerialNumber(int subId)3935     public String getSimSerialNumber(int subId) {
3936         try {
3937             IPhoneSubInfo info = getSubscriberInfoService();
3938             if (info == null)
3939                 return null;
3940             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
3941                     mContext.getAttributionTag());
3942         } catch (RemoteException ex) {
3943             return null;
3944         } catch (NullPointerException ex) {
3945             // This could happen before phone restarts due to crashing
3946             return null;
3947         }
3948     }
3949 
3950     /**
3951      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
3952      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
3953      *
3954      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
3955      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
3956      *
3957      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
3958      *         {@code false} if not supported or unknown
3959      * @hide
3960      */
3961     @SystemApi
3962     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isLteCdmaEvdoGsmWcdmaEnabled()3963     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
3964         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
3965     }
3966 
3967     /**
3968      * Return if the current radio is LTE on CDMA for Subscription. This
3969      * is a tri-state return value as for a period of time
3970      * the mode may be unknown.
3971      *
3972      * @param subId for which radio is LTE on CDMA is returned
3973      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
3974      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
3975      * @hide
3976      */
3977     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3978     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)3979     public int getLteOnCdmaMode(int subId) {
3980         try {
3981             ITelephony telephony = getITelephony();
3982             if (telephony == null)
3983                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3984             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
3985                     getAttributionTag());
3986         } catch (RemoteException ex) {
3987             // Assume no ICC card if remote exception which shouldn't happen
3988             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3989         } catch (NullPointerException ex) {
3990             // This could happen before phone restarts due to crashing
3991             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3992         }
3993     }
3994 
3995     /**
3996      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
3997      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
3998      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
3999      *
4000      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
4001      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
4002      * through a factory reset.
4003      *
4004      * @return card ID of the default eUICC card, if loaded.
4005      */
getCardIdForDefaultEuicc()4006     public int getCardIdForDefaultEuicc() {
4007         try {
4008             ITelephony telephony = getITelephony();
4009             if (telephony == null) {
4010                 return UNINITIALIZED_CARD_ID;
4011             }
4012             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
4013         } catch (RemoteException e) {
4014             return UNINITIALIZED_CARD_ID;
4015         }
4016     }
4017 
4018     /**
4019      * Gets information about currently inserted UICCs and eUICCs.
4020      * <p>
4021      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4022      * <p>
4023      * If the caller has carrier priviliges on any active subscription, then they have permission to
4024      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
4025      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the slot index where the card is inserted
4026      * ({@link UiccCardInfo#getSlotIndex()}).
4027      * <p>
4028      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
4029      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
4030      * UICC or eUICC card.
4031      * <p>
4032      * See {@link UiccCardInfo} for more details on the kind of information available.
4033      *
4034      * @return a list of UiccCardInfo objects, representing information on the currently inserted
4035      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
4036      * the caller does not have adequate permissions for that card.
4037      */
4038     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4039     @NonNull
getUiccCardsInfo()4040     public List<UiccCardInfo> getUiccCardsInfo() {
4041         try {
4042             ITelephony telephony = getITelephony();
4043             if (telephony == null) {
4044                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
4045                 return new ArrayList<UiccCardInfo>();
4046             }
4047             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
4048         } catch (RemoteException e) {
4049             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
4050             return new ArrayList<UiccCardInfo>();
4051         }
4052     }
4053 
4054     /**
4055      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
4056      * available, which is possible between phone process starting and getting slot info from modem.
4057      *
4058      * @return UiccSlotInfo array.
4059      *
4060      * @hide
4061      */
4062     @SystemApi
4063     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getUiccSlotsInfo()4064     public UiccSlotInfo[] getUiccSlotsInfo() {
4065         try {
4066             ITelephony telephony = getITelephony();
4067             if (telephony == null) {
4068                 return null;
4069             }
4070             return telephony.getUiccSlotsInfo();
4071         } catch (RemoteException e) {
4072             return null;
4073         }
4074     }
4075 
4076     /**
4077      * Test method to reload the UICC profile.
4078      *
4079      * @hide
4080      */
4081     @TestApi
4082     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()4083     public void refreshUiccProfile() {
4084         try {
4085             ITelephony telephony = getITelephony();
4086             telephony.refreshUiccProfile(mSubId);
4087         } catch (RemoteException ex) {
4088             Rlog.w(TAG, "RemoteException", ex);
4089         }
4090     }
4091 
4092     /**
4093      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
4094      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
4095      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
4096      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
4097      * logical slots.
4098      *
4099      * @param physicalSlots The content of the array represents the physical slot index. The array
4100      *        size should be same as {@link #getUiccSlotsInfo()}.
4101      * @return boolean Return true if the switch succeeds, false if the switch fails.
4102      * @hide
4103      */
4104     @SystemApi
4105     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchSlots(int[] physicalSlots)4106     public boolean switchSlots(int[] physicalSlots) {
4107         try {
4108             ITelephony telephony = getITelephony();
4109             if (telephony == null) {
4110                 return false;
4111             }
4112             return telephony.switchSlots(physicalSlots);
4113         } catch (RemoteException e) {
4114             return false;
4115         }
4116     }
4117 
4118     /**
4119      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
4120      * id and the value is the physical slots id mapped to this logical slot id.
4121      *
4122      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
4123      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
4124      *
4125      * @hide
4126      */
4127     @SystemApi
4128     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4129     @NonNull
getLogicalToPhysicalSlotMapping()4130     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
4131         Map<Integer, Integer> slotMapping = new HashMap<>();
4132         try {
4133             ITelephony telephony = getITelephony();
4134             if (telephony != null) {
4135                 int[] slotMappingArray = telephony.getSlotsMapping();
4136                 for (int i = 0; i < slotMappingArray.length; i++) {
4137                     slotMapping.put(i, slotMappingArray[i]);
4138                 }
4139             }
4140         } catch (RemoteException e) {
4141             Log.e(TAG, "getSlotsMapping RemoteException", e);
4142         }
4143         return slotMapping;
4144     }
4145 
4146     //
4147     //
4148     // Subscriber Info
4149     //
4150     //
4151 
4152     /**
4153      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
4154      * Return null if it is unavailable.
4155      *
4156      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4157      * restrictions, and apps are recommended to use resettable identifiers (see <a
4158      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4159      * method can be invoked if one of the following requirements is met:
4160      * <ul>
4161      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4162      *     is a privileged permission that can only be granted to apps preloaded on the device.
4163      *     <li>If the calling app is the device or profile owner and has been granted the
4164      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
4165      *     owns a managed profile on the device; for more details see <a
4166      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
4167      *     Profile owner access is deprecated and will be removed in a future release.
4168      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4169      *     <li>If the calling app is the default SMS role holder (see {@link
4170      *     RoleManager#isRoleHeld(String)}).
4171      * </ul>
4172      *
4173      * <p>If the calling app does not meet one of these requirements then this method will behave
4174      * as follows:
4175      *
4176      * <ul>
4177      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4178      *     READ_PHONE_STATE permission then null is returned.</li>
4179      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4180      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4181      *     higher, then a SecurityException is thrown.</li>
4182      * </ul>
4183      */
4184     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4185     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSubscriberId()4186     public String getSubscriberId() {
4187         return getSubscriberId(getSubId());
4188     }
4189 
4190     /**
4191      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
4192      * for a subscription.
4193      * Return null if it is unavailable.
4194      *
4195      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4196      * restrictions, and apps are recommended to use resettable identifiers (see <a
4197      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4198      * method can be invoked if one of the following requirements is met:
4199      * <ul>
4200      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4201      *     is a privileged permission that can only be granted to apps preloaded on the device.
4202      *     <li>If the calling app is the device or profile owner and has been granted the
4203      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
4204      *     owns a managed profile on the device; for more details see <a
4205      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
4206      *     Profile owner access is deprecated and will be removed in a future release.
4207      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4208      *     <li>If the calling app is the default SMS role holder (see {@link
4209      *     RoleManager#isRoleHeld(String)}).
4210      * </ul>
4211      *
4212      * <p>If the calling app does not meet one of these requirements then this method will behave
4213      * as follows:
4214      *
4215      * <ul>
4216      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4217      *     READ_PHONE_STATE permission then null is returned.</li>
4218      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4219      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4220      *     higher, then a SecurityException is thrown.</li>
4221      * </ul>
4222      *
4223      * @param subId whose subscriber id is returned
4224      * @hide
4225      */
4226     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4227     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)4228     public String getSubscriberId(int subId) {
4229         try {
4230             IPhoneSubInfo info = getSubscriberInfoService();
4231             if (info == null)
4232                 return null;
4233             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
4234                     mContext.getAttributionTag());
4235         } catch (RemoteException ex) {
4236             return null;
4237         } catch (NullPointerException ex) {
4238             // This could happen before phone restarts due to crashing
4239             return null;
4240         }
4241     }
4242 
4243     /**
4244      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
4245      * including the public key and the key identifier; or {@code null} if not available.
4246      * <p>
4247      * For a multi-sim device, the dafault data sim is used if not specified.
4248      * <p>
4249      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
4250      *
4251      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
4252      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
4253      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
4254      *         IMSI and IMPI. This includes the public key and the key identifier. This information
4255      *         will be stored in the device keystore. {@code null} will be returned when no key is
4256      *         found, and the carrier does not require a key.
4257      * @throws IllegalArgumentException when an invalid key is found or when key is required but
4258      *         not found.
4259      * @hide
4260      */
4261     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4262     @SystemApi
4263     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)4264     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
4265         try {
4266             IPhoneSubInfo info = getSubscriberInfoService();
4267             if (info == null) {
4268                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
4269                 return null;
4270             }
4271             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4272             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
4273                 throw new IllegalArgumentException("IMSI error: Invalid key type");
4274             }
4275             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
4276                     subId, keyType, mContext.getOpPackageName());
4277             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
4278                 Rlog.e(TAG, "IMSI error: key is required but not found");
4279                 throw new IllegalArgumentException("IMSI error: key is required but not found");
4280             }
4281             return imsiEncryptionInfo;
4282         } catch (RemoteException ex) {
4283             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4284         } catch (NullPointerException ex) {
4285             // This could happen before phone restarts due to crashing
4286             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
4287         }
4288         return null;
4289     }
4290 
4291     /**
4292      * Resets the carrier keys used to encrypt the IMSI and IMPI.
4293      * <p>
4294      * This involves 2 steps:
4295      *  1. Delete the keys from the database.
4296      *  2. Send an intent to download new Certificates.
4297      * <p>
4298      * For a multi-sim device, the dafault data sim is used if not specified.
4299      * <p>
4300      * Requires Permission: MODIFY_PHONE_STATE.
4301      *
4302      * @see #getCarrierInfoForImsiEncryption
4303      * @hide
4304      */
4305     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4306     @SystemApi
resetCarrierKeysForImsiEncryption()4307     public void resetCarrierKeysForImsiEncryption() {
4308         try {
4309             IPhoneSubInfo info = getSubscriberInfoService();
4310             if (info == null) {
4311                 Rlog.e(TAG, "IMSI error: Subscriber Info is null");
4312                 if (!isSystemProcess()) {
4313                     throw new RuntimeException("IMSI error: Subscriber Info is null");
4314                 }
4315                 return;
4316             }
4317             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4318             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
4319         } catch (RemoteException ex) {
4320             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4321             if (!isSystemProcess()) {
4322                 ex.rethrowAsRuntimeException();
4323             }
4324         }
4325     }
4326 
4327    /**
4328      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
4329      * @param keyType the key type which is being checked. (WLAN, EPDG)
4330      * @return true if the digit at position keyType is 1, else false.
4331      * @hide
4332      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)4333     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
4334         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
4335         return (returnValue == 1) ? true : false;
4336     }
4337 
4338     /**
4339      * If Carrier requires Imsi to be encrypted.
4340      * @hide
4341      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4342     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4343         CarrierConfigManager configManager =
4344                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4345         if (configManager == null) {
4346             return false;
4347         }
4348         PersistableBundle pb = configManager.getConfigForSubId(subId);
4349         if (pb == null) {
4350             return false;
4351         }
4352         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4353         return isKeyEnabled(keyAvailability, keyType);
4354     }
4355 
4356     /**
4357      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4358      * This includes the public key and the key identifier. This information will be stored in the
4359      * device keystore.
4360      * <p>
4361      * Requires Permission:
4362      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4363      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4364      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4365      *        The keyIdentifier Attribute value pair that helps a server locate
4366      *        the private key to decrypt the permanent identity. This field is
4367      *        optional and if it is present then it’s always separated from encrypted
4368      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4369      *        with “name=value” format.
4370      * @hide
4371      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4372     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4373         try {
4374             IPhoneSubInfo info = getSubscriberInfoService();
4375             if (info == null) return;
4376             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4377                     imsiEncryptionInfo);
4378         } catch (NullPointerException ex) {
4379             // This could happen before phone restarts due to crashing
4380             return;
4381         } catch (RemoteException ex) {
4382             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4383             return;
4384         }
4385     }
4386 
4387     /**
4388      * Returns the Group Identifier Level1 for a GSM phone.
4389      * Return null if it is unavailable.
4390      *
4391      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4392      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4393      */
4394     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4395     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getGroupIdLevel1()4396     public String getGroupIdLevel1() {
4397         try {
4398             IPhoneSubInfo info = getSubscriberInfoService();
4399             if (info == null)
4400                 return null;
4401             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
4402                     mContext.getAttributionTag());
4403         } catch (RemoteException ex) {
4404             return null;
4405         } catch (NullPointerException ex) {
4406             // This could happen before phone restarts due to crashing
4407             return null;
4408         }
4409     }
4410 
4411     /**
4412      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
4413      * Return null if it is unavailable.
4414      *
4415      * @param subId whose subscriber id is returned
4416      * @hide
4417      */
4418     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4419     @UnsupportedAppUsage
getGroupIdLevel1(int subId)4420     public String getGroupIdLevel1(int subId) {
4421         try {
4422             IPhoneSubInfo info = getSubscriberInfoService();
4423             if (info == null)
4424                 return null;
4425             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
4426                     mContext.getAttributionTag());
4427         } catch (RemoteException ex) {
4428             return null;
4429         } catch (NullPointerException ex) {
4430             // This could happen before phone restarts due to crashing
4431             return null;
4432         }
4433     }
4434 
4435     /**
4436      * Returns the phone number string for line 1, for example, the MSISDN
4437      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4438      * <p>
4439      * The default SMS app can also use this.
4440      *
4441      * <p>Requires Permission:
4442      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4443      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4444      *     that the caller is the default SMS app,
4445      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4446      *     for any API level.
4447      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4448      *     for apps targeting SDK API level 29 and below.
4449      */
4450     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
4451     @RequiresPermission(anyOf = {
4452             android.Manifest.permission.READ_PHONE_STATE,
4453             android.Manifest.permission.READ_SMS,
4454             android.Manifest.permission.READ_PHONE_NUMBERS
4455     })
getLine1Number()4456     public String getLine1Number() {
4457         return getLine1Number(getSubId());
4458     }
4459 
4460     /**
4461      * Returns the phone number string for line 1, for example, the MSISDN
4462      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4463      * <p>
4464      * The default SMS app can also use this.
4465      *
4466      * <p>Requires Permission:
4467      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4468      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4469      *     that the caller is the default SMS app,
4470      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4471      *     for any API level.
4472      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4473      *     for apps targeting SDK API level 29 and below.
4474      *
4475      * @param subId whose phone number for line 1 is returned
4476      * @hide
4477      */
4478     @RequiresPermission(anyOf = {
4479             android.Manifest.permission.READ_PHONE_STATE,
4480             android.Manifest.permission.READ_SMS,
4481             android.Manifest.permission.READ_PHONE_NUMBERS
4482     })
4483     @UnsupportedAppUsage
getLine1Number(int subId)4484     public String getLine1Number(int subId) {
4485         String number = null;
4486         try {
4487             ITelephony telephony = getITelephony();
4488             if (telephony != null)
4489                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
4490                          mContext.getAttributionTag());
4491         } catch (RemoteException ex) {
4492         } catch (NullPointerException ex) {
4493         }
4494         if (number != null) {
4495             return number;
4496         }
4497         try {
4498             IPhoneSubInfo info = getSubscriberInfoService();
4499             if (info == null)
4500                 return null;
4501             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
4502                     mContext.getAttributionTag());
4503         } catch (RemoteException ex) {
4504             return null;
4505         } catch (NullPointerException ex) {
4506             // This could happen before phone restarts due to crashing
4507             return null;
4508         }
4509     }
4510 
4511     /**
4512      * Set the line 1 phone number string and its alphatag for the current ICCID
4513      * for display purpose only, for example, displayed in Phone Status. It won't
4514      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4515      * value.
4516      *
4517      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4518      *
4519      * @param alphaTag alpha-tagging of the dailing nubmer
4520      * @param number The dialing number
4521      * @return true if the operation was executed correctly.
4522      */
setLine1NumberForDisplay(String alphaTag, String number)4523     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
4524         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
4525     }
4526 
4527     /**
4528      * Set the line 1 phone number string and its alphatag for the current ICCID
4529      * for display purpose only, for example, displayed in Phone Status. It won't
4530      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4531      * value.
4532      *
4533      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4534      *
4535      * @param subId the subscriber that the alphatag and dialing number belongs to.
4536      * @param alphaTag alpha-tagging of the dailing nubmer
4537      * @param number The dialing number
4538      * @return true if the operation was executed correctly.
4539      * @hide
4540      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)4541     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
4542         try {
4543             ITelephony telephony = getITelephony();
4544             if (telephony != null)
4545                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
4546         } catch (RemoteException ex) {
4547         } catch (NullPointerException ex) {
4548         }
4549         return false;
4550     }
4551 
4552     /**
4553      * Returns the alphabetic identifier associated with the line 1 number.
4554      * Return null if it is unavailable.
4555      * @hide
4556      * nobody seems to call this.
4557      */
4558     @UnsupportedAppUsage
4559     @TestApi
4560     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()4561     public String getLine1AlphaTag() {
4562         return getLine1AlphaTag(getSubId());
4563     }
4564 
4565     /**
4566      * Returns the alphabetic identifier associated with the line 1 number
4567      * for a subscription.
4568      * Return null if it is unavailable.
4569      * @param subId whose alphabetic identifier associated with line 1 is returned
4570      * nobody seems to call this.
4571      * @hide
4572      */
4573     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4574     @UnsupportedAppUsage
getLine1AlphaTag(int subId)4575     public String getLine1AlphaTag(int subId) {
4576         String alphaTag = null;
4577         try {
4578             ITelephony telephony = getITelephony();
4579             if (telephony != null)
4580                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
4581                         getOpPackageName(), getAttributionTag());
4582         } catch (RemoteException ex) {
4583         } catch (NullPointerException ex) {
4584         }
4585         if (alphaTag != null) {
4586             return alphaTag;
4587         }
4588         try {
4589             IPhoneSubInfo info = getSubscriberInfoService();
4590             if (info == null)
4591                 return null;
4592             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
4593                     getAttributionTag());
4594         } catch (RemoteException ex) {
4595             return null;
4596         } catch (NullPointerException ex) {
4597             // This could happen before phone restarts due to crashing
4598             return null;
4599         }
4600     }
4601 
4602     /**
4603      * Return the set of subscriber IDs that should be considered "merged together" for data usage
4604      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
4605      * subscribers are sorted in a deterministic order.
4606      * <p>
4607      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
4608      * TelephonyManager's subId.
4609      *
4610      * This is deprecated and {@link #getMergedImsisFromGroup()} should be used for data
4611      * usage merging purpose.
4612      * TODO: remove this API.
4613      *
4614      * @hide
4615      */
4616     @UnsupportedAppUsage
4617     @Deprecated
getMergedSubscriberIds()4618     public @Nullable String[] getMergedSubscriberIds() {
4619         try {
4620             ITelephony telephony = getITelephony();
4621             if (telephony != null)
4622                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
4623                         getAttributionTag());
4624         } catch (RemoteException ex) {
4625         } catch (NullPointerException ex) {
4626         }
4627         return null;
4628     }
4629 
4630     /**
4631      * Return the set of IMSIs that should be considered "merged together" for data usage
4632      * purposes. Unlike {@link #getMergedSubscriberIds()} this API merge IMSIs based on
4633      * subscription grouping: IMSI of those in the same group will all be returned.
4634      * Return the current IMSI if there is no subscription group.
4635      *
4636      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
4637      *
4638      * @hide
4639      */
4640     @SystemApi
4641     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMergedImsisFromGroup()4642     public @NonNull String[] getMergedImsisFromGroup() {
4643         try {
4644             ITelephony telephony = getITelephony();
4645             if (telephony != null) {
4646                 return telephony.getMergedImsisFromGroup(getSubId(), getOpPackageName());
4647             }
4648         } catch (RemoteException ex) {
4649         } catch (NullPointerException ex) {
4650         }
4651         return new String[0];
4652     }
4653 
4654     /**
4655      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4656      *
4657      * <p>Requires Permission:
4658      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4659      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4660      *     that the caller is the default SMS app,
4661      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4662      *     for any API level.
4663      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4664      *     for apps targeting SDK API level 29 and below.
4665      *
4666      * @hide
4667      */
4668     @RequiresPermission(anyOf = {
4669             android.Manifest.permission.READ_PHONE_STATE,
4670             android.Manifest.permission.READ_SMS,
4671             android.Manifest.permission.READ_PHONE_NUMBERS
4672     })
4673     @UnsupportedAppUsage
getMsisdn()4674     public String getMsisdn() {
4675         return getMsisdn(getSubId());
4676     }
4677 
4678     /**
4679      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4680      *
4681      * @param subId for which msisdn is returned
4682      *
4683      * <p>Requires Permission:
4684      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4685      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4686      *     that the caller is the default SMS app,
4687      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4688      *     for any API level.
4689      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4690      *     for apps targeting SDK API level 29 and below.
4691      *
4692      * @hide
4693      */
4694     @RequiresPermission(anyOf = {
4695             android.Manifest.permission.READ_PHONE_STATE,
4696             android.Manifest.permission.READ_SMS,
4697             android.Manifest.permission.READ_PHONE_NUMBERS
4698     })
4699     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)4700     public String getMsisdn(int subId) {
4701         try {
4702             IPhoneSubInfo info = getSubscriberInfoService();
4703             if (info == null)
4704                 return null;
4705             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
4706         } catch (RemoteException ex) {
4707             return null;
4708         } catch (NullPointerException ex) {
4709             // This could happen before phone restarts due to crashing
4710             return null;
4711         }
4712     }
4713 
4714     /**
4715      * Returns the voice mail number. Return null if it is unavailable.
4716      *
4717      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4718      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4719      */
4720     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4721     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailNumber()4722     public String getVoiceMailNumber() {
4723         return getVoiceMailNumber(getSubId());
4724     }
4725 
4726     /**
4727      * Returns the voice mail number for a subscription.
4728      * Return null if it is unavailable.
4729      * @param subId whose voice mail number is returned
4730      * @hide
4731      */
4732     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4733     @UnsupportedAppUsage
getVoiceMailNumber(int subId)4734     public String getVoiceMailNumber(int subId) {
4735         try {
4736             IPhoneSubInfo info = getSubscriberInfoService();
4737             if (info == null)
4738                 return null;
4739             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
4740                     getAttributionTag());
4741         } catch (RemoteException ex) {
4742             return null;
4743         } catch (NullPointerException ex) {
4744             // This could happen before phone restarts due to crashing
4745             return null;
4746         }
4747     }
4748 
4749     /**
4750      * Sets the voice mail number.
4751      *
4752      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4753      *
4754      * @param alphaTag The alpha tag to display.
4755      * @param number The voicemail number.
4756      */
setVoiceMailNumber(String alphaTag, String number)4757     public boolean setVoiceMailNumber(String alphaTag, String number) {
4758         return setVoiceMailNumber(getSubId(), alphaTag, number);
4759     }
4760 
4761     /**
4762      * Sets the voicemail number for the given subscriber.
4763      *
4764      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4765      *
4766      * @param subId The subscription id.
4767      * @param alphaTag The alpha tag to display.
4768      * @param number The voicemail number.
4769      * @hide
4770      */
setVoiceMailNumber(int subId, String alphaTag, String number)4771     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
4772         try {
4773             ITelephony telephony = getITelephony();
4774             if (telephony != null)
4775                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
4776         } catch (RemoteException ex) {
4777         } catch (NullPointerException ex) {
4778         }
4779         return false;
4780     }
4781 
4782     /**
4783      * Enables or disables the visual voicemail client for a phone account.
4784      *
4785      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
4786      * {@link #hasCarrierPrivileges}), or has permission
4787      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
4788      *
4789      * @param phoneAccountHandle the phone account to change the client state
4790      * @param enabled the new state of the client
4791      * @hide
4792      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
4793      * be implemented instead.
4794      */
4795     @SystemApi
4796     @SuppressLint("Doclava125")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)4797     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
4798     }
4799 
4800     /**
4801      * Returns whether the visual voicemail client is enabled.
4802      *
4803      * @param phoneAccountHandle the phone account to check for.
4804      * @return {@code true} when the visual voicemail client is enabled for this client
4805      * @hide
4806      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
4807      * be implemented instead.
4808      */
4809     @SystemApi
4810     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4811     @SuppressLint("Doclava125")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)4812     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
4813         return false;
4814     }
4815 
4816     /**
4817      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
4818      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
4819      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
4820      * voicemail client in telephony.
4821      *
4822      * <p>Requires the caller to be the system dialer.
4823      *
4824      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
4825      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
4826      *
4827      * @hide
4828      */
4829     @SystemApi
4830     @SuppressLint("Doclava125")
4831     @Nullable
getVisualVoicemailSettings()4832     public Bundle getVisualVoicemailSettings(){
4833         try {
4834             ITelephony telephony = getITelephony();
4835             if (telephony != null) {
4836                 return telephony
4837                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
4838             }
4839         } catch (RemoteException ex) {
4840         } catch (NullPointerException ex) {
4841         }
4842         return null;
4843     }
4844 
4845     /**
4846      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
4847      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
4848      * processing visual voicemail for the subscription.
4849      *
4850      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4851      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4852      *
4853      * @see #createForSubscriptionId(int)
4854      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
4855      * @see VisualVoicemailService
4856      */
4857     @Nullable
4858     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4859     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVisualVoicemailPackageName()4860     public String getVisualVoicemailPackageName() {
4861         try {
4862             ITelephony telephony = getITelephony();
4863             if (telephony != null) {
4864                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
4865                         getAttributionTag(), getSubId());
4866             }
4867         } catch (RemoteException ex) {
4868         } catch (NullPointerException ex) {
4869         }
4870         return null;
4871     }
4872 
4873     /**
4874      * Set the visual voicemail SMS filter settings for the subscription ID pinned
4875      * to the TelephonyManager.
4876      * When the filter is enabled, {@link
4877      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
4878      * called when a SMS matching the settings is received. Caller must be the default dialer,
4879      * system dialer, or carrier visual voicemail app.
4880      *
4881      * @param settings The settings for the filter, or {@code null} to disable the filter.
4882      *
4883      * @see TelecomManager#getDefaultDialerPackage()
4884      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
4885      */
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)4886     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
4887         if (settings == null) {
4888             disableVisualVoicemailSmsFilter(mSubId);
4889         } else {
4890             enableVisualVoicemailSmsFilter(mSubId, settings);
4891         }
4892     }
4893 
4894     /**
4895      * Send a visual voicemail SMS. The caller must be the current default dialer.
4896      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
4897      * visual voicemail server.  Some examples for carriers using the OMTP standard include
4898      * activating and deactivating visual voicemail, or requesting the current visual voicemail
4899      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
4900      * format of these SMS messages.
4901      *
4902      * <p>Requires Permission:
4903      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
4904      *
4905      * @param number The destination number.
4906      * @param port The destination port for data SMS, or 0 for text SMS.
4907      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
4908      * @param sentIntent The sent intent passed to the {@link SmsManager}
4909      *
4910      * @throws SecurityException if the caller is not the current default dialer
4911      *
4912      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
4913      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
4914      */
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)4915     public void sendVisualVoicemailSms(String number, int port, String text,
4916             PendingIntent sentIntent) {
4917         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
4918     }
4919 
4920     /**
4921      * Enables the visual voicemail SMS filter for a phone account. When the filter is
4922      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
4923      * visual voicemail client with
4924      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
4925      *
4926      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4927      * settings persist through default dialer changes, but the filter will only honor the setting
4928      * set by the current default dialer.
4929      *
4930      *
4931      * @param subId The subscription id of the phone account.
4932      * @param settings The settings for the filter.
4933      */
4934     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)4935     public void enableVisualVoicemailSmsFilter(int subId,
4936             VisualVoicemailSmsFilterSettings settings) {
4937         if(settings == null){
4938             throw new IllegalArgumentException("Settings cannot be null");
4939         }
4940         try {
4941             ITelephony telephony = getITelephony();
4942             if (telephony != null) {
4943                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
4944                         settings);
4945             }
4946         } catch (RemoteException ex) {
4947         } catch (NullPointerException ex) {
4948         }
4949     }
4950 
4951     /**
4952      * Disables the visual voicemail SMS filter for a phone account.
4953      *
4954      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4955      * settings persist through default dialer changes, but the filter will only honor the setting
4956      * set by the current default dialer.
4957      */
4958     /** @hide */
disableVisualVoicemailSmsFilter(int subId)4959     public void disableVisualVoicemailSmsFilter(int subId) {
4960         try {
4961             ITelephony telephony = getITelephony();
4962             if (telephony != null) {
4963                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
4964             }
4965         } catch (RemoteException ex) {
4966         } catch (NullPointerException ex) {
4967         }
4968     }
4969 
4970     /**
4971      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
4972      * if the filter is disabled.
4973      *
4974      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4975      * settings persist through default dialer changes, but the filter will only honor the setting
4976      * set by the current default dialer.
4977      */
4978     /** @hide */
4979     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)4980     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
4981         try {
4982             ITelephony telephony = getITelephony();
4983             if (telephony != null) {
4984                 return telephony
4985                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
4986             }
4987         } catch (RemoteException ex) {
4988         } catch (NullPointerException ex) {
4989         }
4990 
4991         return null;
4992     }
4993 
4994     /**
4995      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
4996      * current active visual voicemail client, or {@code null} if the filter is disabled.
4997      *
4998      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
4999      */
5000     /** @hide */
5001     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)5002     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
5003         try {
5004             ITelephony telephony = getITelephony();
5005             if (telephony != null) {
5006                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
5007             }
5008         } catch (RemoteException ex) {
5009         } catch (NullPointerException ex) {
5010         }
5011 
5012         return null;
5013     }
5014 
5015     /**
5016      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
5017      *
5018      * @param phoneAccountHandle The account to send the SMS with.
5019      * @param number The destination number.
5020      * @param port The destination port for data SMS, or 0 for text SMS.
5021      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5022      * @param sentIntent The sent intent passed to the {@link SmsManager}
5023      *
5024      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5025      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5026      *
5027      * @hide
5028      */
5029     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)5030     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
5031             String text, PendingIntent sentIntent) {
5032         try {
5033             ITelephony telephony = getITelephony();
5034             if (telephony != null) {
5035                 telephony.sendVisualVoicemailSmsForSubscriber(
5036                         mContext.getOpPackageName(), mContext.getAttributionTag(), subId, number,
5037                         port, text, sentIntent);
5038             }
5039         } catch (RemoteException ex) {
5040         }
5041     }
5042 
5043     /**
5044      * Initial SIM activation state, unknown. Not set by any carrier apps.
5045      * @hide
5046      */
5047     @SystemApi
5048     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
5049 
5050     /**
5051      * indicate SIM is under activation procedure now.
5052      * intermediate state followed by another state update with activation procedure result:
5053      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5054      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5055      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5056      * @hide
5057      */
5058     @SystemApi
5059     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
5060 
5061     /**
5062      * Indicate SIM has been successfully activated with full service
5063      * @hide
5064      */
5065     @SystemApi
5066     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
5067 
5068     /**
5069      * Indicate SIM has been deactivated by the carrier so that service is not available
5070      * and requires activation service to enable services.
5071      * Carrier apps could be signalled to set activation state to deactivated if detected
5072      * deactivated sim state and set it back to activated after successfully run activation service.
5073      * @hide
5074      */
5075     @SystemApi
5076     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
5077 
5078     /**
5079      * Restricted state indicate SIM has been activated but service are restricted.
5080      * note this is currently available for data activation state. For example out of byte sim.
5081      * @hide
5082      */
5083     @SystemApi
5084     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
5085 
5086      /**
5087       * Sets the voice activation state
5088       *
5089       * <p>Requires Permission:
5090       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5091       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5092       *
5093       * @param activationState The voice activation state
5094       * @see #SIM_ACTIVATION_STATE_UNKNOWN
5095       * @see #SIM_ACTIVATION_STATE_ACTIVATING
5096       * @see #SIM_ACTIVATION_STATE_ACTIVATED
5097       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5098       * @hide
5099       */
5100     @SystemApi
5101     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(@imActivationState int activationState)5102     public void setVoiceActivationState(@SimActivationState int activationState) {
5103         setVoiceActivationState(getSubId(), activationState);
5104     }
5105 
5106     /**
5107      * Sets the voice activation state for the given subscriber.
5108      *
5109      * <p>Requires Permission:
5110      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5111      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5112      *
5113      * @param subId The subscription id.
5114      * @param activationState The voice activation state of the given subscriber.
5115      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5116      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5117      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5118      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5119      * @hide
5120      */
5121     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)5122     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
5123         try {
5124            ITelephony telephony = getITelephony();
5125            if (telephony != null)
5126                telephony.setVoiceActivationState(subId, activationState);
5127        } catch (RemoteException ex) {
5128        } catch (NullPointerException ex) {
5129        }
5130     }
5131 
5132     /**
5133      * Sets the data activation state
5134      *
5135      * <p>Requires Permission:
5136      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5137      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5138      *
5139      * @param activationState The data activation state
5140      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5141      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5142      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5143      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5144      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5145      * @hide
5146      */
5147     @SystemApi
5148     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(@imActivationState int activationState)5149     public void setDataActivationState(@SimActivationState int activationState) {
5150         setDataActivationState(getSubId(), activationState);
5151     }
5152 
5153     /**
5154      * Sets the data activation state for the given subscriber.
5155      *
5156      * <p>Requires Permission:
5157      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5158      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5159      *
5160      * @param subId The subscription id.
5161      * @param activationState The data activation state of the given subscriber.
5162      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5163      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5164      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5165      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5166      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5167      * @hide
5168      */
5169     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)5170     public void setDataActivationState(int subId, @SimActivationState int activationState) {
5171         try {
5172             ITelephony telephony = getITelephony();
5173             if (telephony != null)
5174                 telephony.setDataActivationState(subId, activationState);
5175         } catch (RemoteException ex) {
5176         } catch (NullPointerException ex) {
5177         }
5178     }
5179 
5180     /**
5181      * Returns the voice activation state
5182      *
5183      * <p>Requires Permission:
5184      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5185      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5186      *
5187      * @return voiceActivationState
5188      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5189      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5190      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5191      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5192      * @hide
5193      */
5194     @SystemApi
5195     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState()5196     public @SimActivationState int getVoiceActivationState() {
5197         return getVoiceActivationState(getSubId());
5198     }
5199 
5200     /**
5201      * Returns the voice activation state for the given subscriber.
5202      *
5203      * <p>Requires Permission:
5204      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5205      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5206      *
5207      * @param subId The subscription id.
5208      *
5209      * @return voiceActivationState for the given subscriber
5210      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5211      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5212      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5213      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5214      * @hide
5215      */
5216     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)5217     public @SimActivationState int getVoiceActivationState(int subId) {
5218         try {
5219             ITelephony telephony = getITelephony();
5220             if (telephony != null)
5221                 return telephony.getVoiceActivationState(subId, getOpPackageName());
5222         } catch (RemoteException ex) {
5223         } catch (NullPointerException ex) {
5224         }
5225         return SIM_ACTIVATION_STATE_UNKNOWN;
5226     }
5227 
5228     /**
5229      * Returns the data activation state
5230      *
5231      * <p>Requires Permission:
5232      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5233      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5234      *
5235      * @return dataActivationState for the given subscriber
5236      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5237      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5238      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5239      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5240      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5241      * @hide
5242      */
5243     @SystemApi
5244     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState()5245     public @SimActivationState int getDataActivationState() {
5246         return getDataActivationState(getSubId());
5247     }
5248 
5249     /**
5250      * Returns the data activation state for the given subscriber.
5251      *
5252      * <p>Requires Permission:
5253      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5254      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5255      *
5256      * @param subId The subscription id.
5257      *
5258      * @return dataActivationState for the given subscriber
5259      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5260      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5261      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5262      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5263      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5264      * @hide
5265      */
5266     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)5267     public @SimActivationState int getDataActivationState(int subId) {
5268         try {
5269             ITelephony telephony = getITelephony();
5270             if (telephony != null)
5271                 return telephony.getDataActivationState(subId, getOpPackageName());
5272         } catch (RemoteException ex) {
5273         } catch (NullPointerException ex) {
5274         }
5275         return SIM_ACTIVATION_STATE_UNKNOWN;
5276     }
5277 
5278     /**
5279      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
5280      * but the count is unknown.
5281      * @hide
5282      */
5283     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5284     @UnsupportedAppUsage
getVoiceMessageCount()5285     public int getVoiceMessageCount() {
5286         return getVoiceMessageCount(getSubId());
5287     }
5288 
5289     /**
5290      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
5291      * not have the READ_PHONE_STATE permission.
5292      * @param subId whose voice message count is returned
5293      * @hide
5294      */
5295     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5296     @UnsupportedAppUsage
getVoiceMessageCount(int subId)5297     public int getVoiceMessageCount(int subId) {
5298         try {
5299             ITelephony telephony = getITelephony();
5300             if (telephony == null)
5301                 return 0;
5302             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
5303                     getAttributionTag());
5304         } catch (RemoteException ex) {
5305             return 0;
5306         } catch (NullPointerException ex) {
5307             // This could happen before phone restarts due to crashing
5308             return 0;
5309         }
5310     }
5311 
5312     /**
5313      * Retrieves the alphabetic identifier associated with the voice
5314      * mail number.
5315      *
5316      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5317      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5318      */
5319     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5320     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailAlphaTag()5321     public String getVoiceMailAlphaTag() {
5322         return getVoiceMailAlphaTag(getSubId());
5323     }
5324 
5325     /**
5326      * Retrieves the alphabetic identifier associated with the voice
5327      * mail number for a subscription.
5328      * @param subId whose alphabetic identifier associated with the
5329      * voice mail number is returned
5330      * @hide
5331      */
5332     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5333     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)5334     public String getVoiceMailAlphaTag(int subId) {
5335         try {
5336             IPhoneSubInfo info = getSubscriberInfoService();
5337             if (info == null)
5338                 return null;
5339             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
5340                     getAttributionTag());
5341         } catch (RemoteException ex) {
5342             return null;
5343         } catch (NullPointerException ex) {
5344             // This could happen before phone restarts due to crashing
5345             return null;
5346         }
5347     }
5348 
5349     /**
5350      * Send the special dialer code. The IPC caller must be the current default dialer or have
5351      * carrier privileges (see {@link #hasCarrierPrivileges}).
5352      *
5353      * @param inputCode The special dialer code to send
5354      *
5355      * @throws SecurityException if the caller does not have carrier privileges or is not the
5356      *         current default dialer
5357      */
sendDialerSpecialCode(String inputCode)5358     public void sendDialerSpecialCode(String inputCode) {
5359         try {
5360             final ITelephony telephony = getITelephony();
5361             if (telephony == null) {
5362                 if (!isSystemProcess()) {
5363                     throw new RuntimeException("Telephony service unavailable");
5364                 }
5365                 return;
5366             }
5367             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
5368         } catch (RemoteException ex) {
5369             // This could happen if binder process crashes.
5370             if (!isSystemProcess()) {
5371                 ex.rethrowAsRuntimeException();
5372             }
5373         }
5374     }
5375 
5376     /**
5377      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
5378      * @return the IMPI, or null if not present or not loaded
5379      * @hide
5380      */
5381     @UnsupportedAppUsage
getIsimImpi()5382     public String getIsimImpi() {
5383         try {
5384             IPhoneSubInfo info = getSubscriberInfoService();
5385             if (info == null)
5386                 return null;
5387             //get the Isim Impi based on subId
5388             return info.getIsimImpi(getSubId());
5389         } catch (RemoteException ex) {
5390             return null;
5391         } catch (NullPointerException ex) {
5392             // This could happen before phone restarts due to crashing
5393             return null;
5394         }
5395     }
5396 
5397     /**
5398      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
5399      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
5400      * hasn't been loaded or isn't present on the ISIM.
5401      *
5402      * <p>Requires Permission:
5403      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5404      * @hide
5405      */
5406     @Nullable
5407     @SystemApi
5408     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimDomain()5409     public String getIsimDomain() {
5410         try {
5411             IPhoneSubInfo info = getSubscriberInfoService();
5412             if (info == null)
5413                 return null;
5414             //get the Isim Domain based on subId
5415             return info.getIsimDomain(getSubId());
5416         } catch (RemoteException ex) {
5417             return null;
5418         } catch (NullPointerException ex) {
5419             // This could happen before phone restarts due to crashing
5420             return null;
5421         }
5422     }
5423 
5424     /**
5425      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
5426      * @return an array of IMPU strings, with one IMPU per string, or null if
5427      *      not present or not loaded
5428      * @hide
5429      */
5430     @UnsupportedAppUsage
5431     @Nullable
5432     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()5433     public String[] getIsimImpu() {
5434         try {
5435             IPhoneSubInfo info = getSubscriberInfoService();
5436             if (info == null)
5437                 return null;
5438             //get the Isim Impu based on subId
5439             return info.getIsimImpu(getSubId());
5440         } catch (RemoteException ex) {
5441             return null;
5442         } catch (NullPointerException ex) {
5443             // This could happen before phone restarts due to crashing
5444             return null;
5445         }
5446     }
5447 
5448     /**
5449      * Device call state: No activity.
5450      */
5451     public static final int CALL_STATE_IDLE = 0;
5452     /**
5453      * Device call state: Ringing. A new call arrived and is
5454      *  ringing or waiting. In the latter case, another call is
5455      *  already active.
5456      */
5457     public static final int CALL_STATE_RINGING = 1;
5458     /**
5459      * Device call state: Off-hook. At least one call exists
5460      * that is dialing, active, or on hold, and no calls are ringing
5461      * or waiting.
5462      */
5463     public static final int CALL_STATE_OFFHOOK = 2;
5464 
5465     /**
5466      * Returns the state of all calls on the device.
5467      * <p>
5468      * This method considers not only calls in the Telephony stack, but also calls via other
5469      * {@link android.telecom.ConnectionService} implementations.
5470      * <p>
5471      * Note: The call state returned via this method may differ from what is reported by
5472      * {@link PhoneStateListener#onCallStateChanged(int, String)}, as that callback only considers
5473      * Telephony (mobile) calls.
5474      *
5475      * @return the current call state.
5476      */
getCallState()5477     public @CallState int getCallState() {
5478         if (mContext != null) {
5479             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
5480             if (telecomManager != null) {
5481                 return telecomManager.getCallState();
5482             }
5483         }
5484         return CALL_STATE_IDLE;
5485     }
5486 
5487     /**
5488      * Returns the Telephony call state for calls on a specific subscription.
5489      * <p>
5490      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5491      * considers the state of calls from other {@link android.telecom.ConnectionService}
5492      * implementations.
5493      *
5494      * @param subId the subscription to check call state for.
5495      * @hide
5496      */
5497     @UnsupportedAppUsage
getCallState(int subId)5498     public @CallState int getCallState(int subId) {
5499         int phoneId = SubscriptionManager.getPhoneId(subId);
5500         return getCallStateForSlot(phoneId);
5501     }
5502 
5503     /**
5504     * @hide
5505     */
5506     @UnsupportedAppUsage
getSubscriberInfo()5507     private IPhoneSubInfo getSubscriberInfo() {
5508         return getSubscriberInfoService();
5509     }
5510 
5511     /**
5512      * Returns the Telephony call state for calls on a specific SIM slot.
5513      * <p>
5514      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5515      * considers the state of calls from other {@link android.telecom.ConnectionService}
5516      * implementations.
5517      *
5518      * @param slotIndex the SIM slot index to check call state for.
5519      * @hide
5520      */
getCallStateForSlot(int slotIndex)5521     public @CallState int getCallStateForSlot(int slotIndex) {
5522         try {
5523             ITelephony telephony = getITelephony();
5524             if (telephony == null)
5525                 return CALL_STATE_IDLE;
5526             return telephony.getCallStateForSlot(slotIndex);
5527         } catch (RemoteException ex) {
5528             // the phone process is restarting.
5529             return CALL_STATE_IDLE;
5530         } catch (NullPointerException ex) {
5531           // the phone process is restarting.
5532           return CALL_STATE_IDLE;
5533         }
5534     }
5535 
5536 
5537     /** Data connection activity: No traffic. */
5538     public static final int DATA_ACTIVITY_NONE = 0x00000000;
5539     /** Data connection activity: Currently receiving IP PPP traffic. */
5540     public static final int DATA_ACTIVITY_IN = 0x00000001;
5541     /** Data connection activity: Currently sending IP PPP traffic. */
5542     public static final int DATA_ACTIVITY_OUT = 0x00000002;
5543     /** Data connection activity: Currently both sending and receiving
5544      *  IP PPP traffic. */
5545     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
5546     /**
5547      * Data connection is active, but physical link is down
5548      */
5549     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
5550 
5551     /**
5552      * Returns a constant indicating the type of activity on a data connection
5553      * (cellular).
5554      *
5555      * @see #DATA_ACTIVITY_NONE
5556      * @see #DATA_ACTIVITY_IN
5557      * @see #DATA_ACTIVITY_OUT
5558      * @see #DATA_ACTIVITY_INOUT
5559      * @see #DATA_ACTIVITY_DORMANT
5560      */
getDataActivity()5561     public int getDataActivity() {
5562         try {
5563             ITelephony telephony = getITelephony();
5564             if (telephony == null)
5565                 return DATA_ACTIVITY_NONE;
5566             return telephony.getDataActivityForSubId(
5567                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5568         } catch (RemoteException ex) {
5569             // the phone process is restarting.
5570             return DATA_ACTIVITY_NONE;
5571         } catch (NullPointerException ex) {
5572           // the phone process is restarting.
5573           return DATA_ACTIVITY_NONE;
5574       }
5575     }
5576 
5577     /** @hide */
5578     @IntDef(prefix = {"DATA_"}, value = {
5579             DATA_UNKNOWN,
5580             DATA_DISCONNECTED,
5581             DATA_CONNECTING,
5582             DATA_CONNECTED,
5583             DATA_SUSPENDED,
5584             DATA_DISCONNECTING,
5585     })
5586     @Retention(RetentionPolicy.SOURCE)
5587     public @interface DataState{}
5588 
5589     /** Data connection state: Unknown.  Used before we know the state. */
5590     public static final int DATA_UNKNOWN        = -1;
5591     /** Data connection state: Disconnected. IP traffic not available. */
5592     public static final int DATA_DISCONNECTED   = 0;
5593     /** Data connection state: Currently setting up a data connection. */
5594     public static final int DATA_CONNECTING     = 1;
5595     /** Data connection state: Connected. IP traffic should be available. */
5596     public static final int DATA_CONNECTED      = 2;
5597     /** Data connection state: Suspended. The connection is up, but IP
5598      * traffic is temporarily unavailable. For example, in a 2G network,
5599      * data activity may be suspended when a voice call arrives. */
5600     public static final int DATA_SUSPENDED      = 3;
5601     /**
5602      * Data connection state: Disconnecting.
5603      *
5604      * IP traffic may be available but will cease working imminently.
5605      */
5606     public static final int DATA_DISCONNECTING = 4;
5607 
5608     /**
5609      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
5610      */
5611     @ChangeId
5612     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
5613     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
5614 
5615     /**
5616      * Returns a constant indicating the current data connection state
5617      * (cellular).
5618      *
5619      * @see #DATA_DISCONNECTED
5620      * @see #DATA_CONNECTING
5621      * @see #DATA_CONNECTED
5622      * @see #DATA_SUSPENDED
5623      * @see #DATA_DISCONNECTING
5624      */
getDataState()5625     public int getDataState() {
5626         try {
5627             ITelephony telephony = getITelephony();
5628             if (telephony == null)
5629                 return DATA_DISCONNECTED;
5630             int state = telephony.getDataStateForSubId(
5631                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5632             if (state == TelephonyManager.DATA_DISCONNECTING
5633                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
5634                 return TelephonyManager.DATA_CONNECTED;
5635             }
5636 
5637             return state;
5638         } catch (RemoteException ex) {
5639             // the phone process is restarting.
5640             return DATA_DISCONNECTED;
5641         } catch (NullPointerException ex) {
5642             return DATA_DISCONNECTED;
5643         }
5644     }
5645 
5646     /**
5647      * Convert data state to string
5648      *
5649      * @return The data state in string format.
5650      * @hide
5651      */
dataStateToString(@ataState int state)5652     public static String dataStateToString(@DataState int state) {
5653         switch (state) {
5654             case DATA_DISCONNECTED: return "DISCONNECTED";
5655             case DATA_CONNECTING: return "CONNECTING";
5656             case DATA_CONNECTED: return "CONNECTED";
5657             case DATA_SUSPENDED: return "SUSPENDED";
5658             case DATA_DISCONNECTING: return "DISCONNECTING";
5659         }
5660         return "UNKNOWN(" + state + ")";
5661     }
5662 
5663    /**
5664     * @hide
5665     */
5666     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getITelephony()5667     private ITelephony getITelephony() {
5668         return ITelephony.Stub.asInterface(TelephonyFrameworkInitializer
5669                 .getTelephonyServiceManager().getTelephonyServiceRegisterer().get());
5670     }
5671 
getIOns()5672     private IOns getIOns() {
5673         return IOns.Stub.asInterface(
5674                 TelephonyFrameworkInitializer
5675                         .getTelephonyServiceManager()
5676                         .getOpportunisticNetworkServiceRegisterer()
5677                         .get());
5678     }
5679 
5680     //
5681     //
5682     // PhoneStateListener
5683     //
5684     //
5685 
5686     /**
5687      * Registers a listener object to receive notification of changes
5688      * in specified telephony states.
5689      * <p>
5690      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
5691      * state of interest in the events argument.
5692      *
5693      * At registration, and when a specified telephony state changes, the telephony manager invokes
5694      * the appropriate callback method on the listener object and passes the current (updated)
5695      * values.
5696      * <p>
5697      * To un-register a listener, pass the listener object and set the events argument to
5698      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
5699      *
5700      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
5701      * applies to the given subId. Otherwise, applies to
5702      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
5703      * pass a separate listener object to each TelephonyManager object created with
5704      * {@link #createForSubscriptionId}.
5705      *
5706      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
5707      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
5708      * {@link SecurityException} will be thrown otherwise.
5709      *
5710      * This API should be used sparingly -- large numbers of listeners will cause system
5711      * instability. If a process has registered too many listeners without unregistering them, it
5712      * may encounter an {@link IllegalStateException} when trying to register more listeners.
5713      *
5714      * @param listener The {@link PhoneStateListener} object to register
5715      *                 (or unregister)
5716      * @param events The telephony state(s) of interest to the listener,
5717      *               as a bitwise-OR combination of {@link PhoneStateListener}
5718      *               LISTEN_ flags.
5719      */
listen(PhoneStateListener listener, int events)5720     public void listen(PhoneStateListener listener, int events) {
5721         if (mContext == null) return;
5722         boolean notifyNow = (getITelephony() != null);
5723         TelephonyRegistryManager telephonyRegistry =
5724                 (TelephonyRegistryManager)
5725                         mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
5726         if (telephonyRegistry != null) {
5727             telephonyRegistry.listenForSubscriber(mSubId, getOpPackageName(), getAttributionTag(),
5728                     listener, events, notifyNow);
5729         } else {
5730             Rlog.w(TAG, "telephony registry not ready.");
5731         }
5732     }
5733 
5734     /**
5735      * Get the CDMA ERI (Enhanced Roaming Indicator) information
5736      *
5737      * Returns {@link android.telephony#CdmaEriInformation}
5738      *
5739      * @hide
5740      */
5741     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5742     @NonNull
getCdmaEriInformation()5743     public CdmaEriInformation getCdmaEriInformation() {
5744         return new CdmaEriInformation(
5745                getCdmaEriIconIndex(getSubId()), getCdmaEriIconMode(getSubId()));
5746     }
5747 
5748     /**
5749      * Returns the CDMA ERI icon index to display for a subscription
5750      * @hide
5751      */
5752     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5753     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)5754     public int getCdmaEriIconIndex(int subId) {
5755         try {
5756             ITelephony telephony = getITelephony();
5757             if (telephony == null)
5758                 return -1;
5759             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
5760                     getAttributionTag());
5761         } catch (RemoteException ex) {
5762             // the phone process is restarting.
5763             return -1;
5764         } catch (NullPointerException ex) {
5765             return -1;
5766         }
5767     }
5768 
5769     /**
5770      * Returns the CDMA ERI icon mode for a subscription.
5771      * 0 - ON
5772      * 1 - FLASHING
5773      *
5774      * @hide
5775      */
5776     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5777     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)5778     public int getCdmaEriIconMode(int subId) {
5779         try {
5780             ITelephony telephony = getITelephony();
5781             if (telephony == null)
5782                 return -1;
5783             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
5784                     getAttributionTag());
5785         } catch (RemoteException ex) {
5786             // the phone process is restarting.
5787             return -1;
5788         } catch (NullPointerException ex) {
5789             return -1;
5790         }
5791     }
5792 
5793     /**
5794      * Returns the CDMA ERI text,
5795      *
5796      * @hide
5797      */
5798     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()5799     public String getCdmaEriText() {
5800         return getCdmaEriText(getSubId());
5801     }
5802 
5803     /**
5804      * Returns the CDMA ERI text, of a subscription
5805      *
5806      * @hide
5807      */
5808     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5809     @UnsupportedAppUsage
getCdmaEriText(int subId)5810     public String getCdmaEriText(int subId) {
5811         try {
5812             ITelephony telephony = getITelephony();
5813             if (telephony == null)
5814                 return null;
5815             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
5816                     getAttributionTag());
5817         } catch (RemoteException ex) {
5818             // the phone process is restarting.
5819             return null;
5820         } catch (NullPointerException ex) {
5821             return null;
5822         }
5823     }
5824 
5825     /**
5826      * @return true if the current device is "voice capable".
5827      * <p>
5828      * "Voice capable" means that this device supports circuit-switched
5829      * (i.e. voice) phone calls over the telephony network, and is allowed
5830      * to display the in-call UI while a cellular voice call is active.
5831      * This will be false on "data only" devices which can't make voice
5832      * calls and don't support any in-call UI.
5833      * <p>
5834      * Note: the meaning of this flag is subtly different from the
5835      * PackageManager.FEATURE_TELEPHONY system feature, which is available
5836      * on any device with a telephony radio, even if the device is
5837      * data-only.
5838      */
isVoiceCapable()5839     public boolean isVoiceCapable() {
5840         if (mContext == null) return true;
5841         return mContext.getResources().getBoolean(
5842                 com.android.internal.R.bool.config_voice_capable);
5843     }
5844 
5845     /**
5846      * @return true if the current device supports sms service.
5847      * <p>
5848      * If true, this means that the device supports both sending and
5849      * receiving sms via the telephony network.
5850      * <p>
5851      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
5852      *       disabled when device doesn't support sms.
5853      */
isSmsCapable()5854     public boolean isSmsCapable() {
5855         if (mContext == null) return true;
5856         return mContext.getResources().getBoolean(
5857                 com.android.internal.R.bool.config_sms_capable);
5858     }
5859 
5860     /**
5861      * Requests all available cell information from all radios on the device including the
5862      * camped/registered, serving, and neighboring cells.
5863      *
5864      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
5865      * {@link android.telephony.CellInfoCdma CellInfoCdma},
5866      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
5867      * {@link android.telephony.CellInfoLte CellInfoLte}, and
5868      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
5869      * It is typical to see instances of one or more of any these in the list. In addition, zero
5870      * or more of the returned objects may be considered registered; that is, their
5871      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
5872      * methods may return true, indicating that the cell is being used or would be used for
5873      * signaling communication if necessary.
5874      *
5875      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
5876      * if this API results in a change of the cached CellInfo, that change will be reported via
5877      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}.
5878      *
5879      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
5880      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
5881      * will receive the latest cached results, which may not be current. Apps targeting
5882      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
5883      * CellInfo should call
5884      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
5885      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
5886      * recency of CellInfo data, callers should check
5887      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
5888      *
5889      * <p>This method returns valid data for devices with
5890      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
5891      * where only partial information is available for a particular CellInfo entry, unavailable
5892      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
5893      * cells will include at least a valid set of technology-specific identification info and a
5894      * power level measurement.
5895      *
5896      * <p>This method is preferred over using {@link
5897      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
5898      *
5899      * @return List of {@link android.telephony.CellInfo}; null if cell
5900      * information is unavailable.
5901      */
5902     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getAllCellInfo()5903     public List<CellInfo> getAllCellInfo() {
5904         try {
5905             ITelephony telephony = getITelephony();
5906             if (telephony == null)
5907                 return null;
5908             return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
5909         } catch (RemoteException ex) {
5910         } catch (NullPointerException ex) {
5911         }
5912         return null;
5913     }
5914 
5915     /** Callback for providing asynchronous {@link CellInfo} on request */
5916     public abstract static class CellInfoCallback {
5917         /**
5918          * Success response to
5919          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
5920          *
5921          * Invoked when there is a response to
5922          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
5923          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
5924          * list will be provided. If an error occurs, null will be provided unless the onError
5925          * callback is overridden.
5926          *
5927          * @param cellInfo a list of {@link CellInfo}, an empty list, or null.
5928          *
5929          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
5930          */
onCellInfo(@onNull List<CellInfo> cellInfo)5931         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
5932 
5933         /** @hide */
5934         @Retention(RetentionPolicy.SOURCE)
5935         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
5936         public @interface CellInfoCallbackError {}
5937 
5938         /**
5939          * The system timed out waiting for a response from the Radio.
5940          */
5941         public static final int ERROR_TIMEOUT = 1;
5942 
5943         /**
5944          * The modem returned a failure.
5945          */
5946         public static final int ERROR_MODEM_ERROR = 2;
5947 
5948         /**
5949          * Error response to
5950          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
5951          *
5952          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
5953          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
5954          * function to receive detailed status information in the event of an error. By default,
5955          * this function will invoke onCellInfo() with null.
5956          *
5957          * @param errorCode an error code indicating the type of failure.
5958          * @param detail a Throwable object with additional detail regarding the failure if
5959          *     available, otherwise null.
5960          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)5961         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
5962             // By default, simply invoke the success callback with an empty list.
5963             onCellInfo(new ArrayList<CellInfo>());
5964         }
5965     };
5966 
5967     /**
5968      * Requests all available cell information from the current subscription for observed
5969      * camped/registered, serving, and neighboring cells.
5970      *
5971      * <p>Any available results from this request will be provided by calls to
5972      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
5973      * for each active subscription.
5974      *
5975      * <p>This method returns valid data for devices with
5976      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
5977      * that do not implement this feature, the behavior is not reliable.
5978      *
5979      * @param executor the executor on which callback will be invoked.
5980      * @param callback a callback to receive CellInfo.
5981      */
5982     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)5983     public void requestCellInfoUpdate(
5984             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
5985         try {
5986             ITelephony telephony = getITelephony();
5987             if (telephony == null) return;
5988             telephony.requestCellInfoUpdate(
5989                     getSubId(),
5990                     new ICellInfoCallback.Stub() {
5991                         @Override
5992                         public void onCellInfo(List<CellInfo> cellInfo) {
5993                             final long identity = Binder.clearCallingIdentity();
5994                             try {
5995                                 executor.execute(() -> callback.onCellInfo(cellInfo));
5996                             } finally {
5997                                 Binder.restoreCallingIdentity(identity);
5998                             }
5999                         }
6000 
6001                         @Override
6002                         public void onError(int errorCode, String exceptionName, String message) {
6003                             final long identity = Binder.clearCallingIdentity();
6004                             try {
6005                                 executor.execute(() -> callback.onError(
6006                                         errorCode,
6007                                         createThrowableByClassName(exceptionName, message)));
6008                             } finally {
6009                                 Binder.restoreCallingIdentity(identity);
6010                             }
6011                         }
6012                     }, getOpPackageName(), getAttributionTag());
6013         } catch (RemoteException ex) {
6014         }
6015     }
6016 
6017     /**
6018      * Requests all available cell information from the current subscription for observed
6019      * camped/registered, serving, and neighboring cells.
6020      *
6021      * <p>Any available results from this request will be provided by calls to
6022      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
6023      * for each active subscription.
6024      *
6025      * <p>This method returns valid data for devices with
6026      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
6027      * that do not implement this feature, the behavior is not reliable.
6028      *
6029      * @param workSource the requestor to whom the power consumption for this should be attributed.
6030      * @param executor the executor on which callback will be invoked.
6031      * @param callback a callback to receive CellInfo.
6032      * @hide
6033      */
6034     @SystemApi
6035     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
6036             android.Manifest.permission.MODIFY_PHONE_STATE})
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)6037     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
6038             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
6039         try {
6040             ITelephony telephony = getITelephony();
6041             if (telephony == null) return;
6042             telephony.requestCellInfoUpdateWithWorkSource(
6043                     getSubId(),
6044                     new ICellInfoCallback.Stub() {
6045                         @Override
6046                         public void onCellInfo(List<CellInfo> cellInfo) {
6047                             final long identity = Binder.clearCallingIdentity();
6048                             try {
6049                                 executor.execute(() -> callback.onCellInfo(cellInfo));
6050                             } finally {
6051                                 Binder.restoreCallingIdentity(identity);
6052                             }
6053 
6054                         }
6055 
6056                         @Override
6057                         public void onError(int errorCode, String exceptionName, String message) {
6058                             final long identity = Binder.clearCallingIdentity();
6059                             try {
6060                                 executor.execute(() -> callback.onError(
6061                                         errorCode,
6062                                         createThrowableByClassName(exceptionName, message)));
6063                             } finally {
6064                                 Binder.restoreCallingIdentity(identity);
6065                             }
6066                         }
6067                     }, getOpPackageName(), getAttributionTag(), workSource);
6068         } catch (RemoteException ex) {
6069         }
6070     }
6071 
createThrowableByClassName(String className, String message)6072     private static Throwable createThrowableByClassName(String className, String message) {
6073         if (className == null) {
6074             return null;
6075         }
6076         try {
6077             Class<?> c = Class.forName(className);
6078             return (Throwable) c.getConstructor(String.class).newInstance(message);
6079         } catch (ReflectiveOperationException | ClassCastException e) {
6080         }
6081         return new RuntimeException(className + ": " + message);
6082     }
6083 
6084     /**
6085      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
6086      * PhoneStateListener.onCellInfoChanged} will be invoked.
6087      *<p>
6088      * The default, 0, means invoke onCellInfoChanged when any of the reported
6089      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
6090      * A onCellInfoChanged.
6091      *<p>
6092      * @param rateInMillis the rate
6093      *
6094      * @hide
6095      */
setCellInfoListRate(int rateInMillis)6096     public void setCellInfoListRate(int rateInMillis) {
6097         try {
6098             ITelephony telephony = getITelephony();
6099             if (telephony != null)
6100                 telephony.setCellInfoListRate(rateInMillis);
6101         } catch (RemoteException ex) {
6102         } catch (NullPointerException ex) {
6103         }
6104     }
6105 
6106     /**
6107      * Returns the MMS user agent.
6108      */
getMmsUserAgent()6109     public String getMmsUserAgent() {
6110         try {
6111             ITelephony telephony = getITelephony();
6112             if (telephony != null) {
6113                 return telephony.getMmsUserAgent(getSubId());
6114             }
6115         } catch (RemoteException ex) {
6116         } catch (NullPointerException ex) {
6117         }
6118         return null;
6119     }
6120 
6121     /**
6122      * Returns the MMS user agent profile URL.
6123      */
getMmsUAProfUrl()6124     public String getMmsUAProfUrl() {
6125         try {
6126             ITelephony telephony = getITelephony();
6127             if (telephony != null) {
6128                 return telephony.getMmsUAProfUrl(getSubId());
6129             }
6130         } catch (RemoteException ex) {
6131         } catch (NullPointerException ex) {
6132         }
6133         return null;
6134     }
6135 
6136     /**
6137      * Opens a logical channel to the ICC card.
6138      *
6139      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6140      *
6141      * <p>Requires Permission:
6142      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6143      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6144      *
6145      * @param AID Application id. See ETSI 102.221 and 101.220.
6146      * @return an IccOpenLogicalChannelResponse object.
6147      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
6148      */
6149     @Deprecated
iccOpenLogicalChannel(String AID)6150     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
6151         return iccOpenLogicalChannel(getSubId(), AID, -1);
6152     }
6153 
6154     /**
6155      * Opens a logical channel to the ICC card using the physical slot index.
6156      *
6157      * Use this method when no subscriptions are available on the SIM and the operation must be
6158      * performed using the physical slot index.
6159      *
6160      * This operation wraps two APDU instructions:
6161      * <ul>
6162      *     <li>MANAGE CHANNEL to open a logical channel</li>
6163      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6164      * </ul>
6165      *
6166      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6167      * and 0x0C are guaranteed to be supported.
6168      *
6169      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6170      * considered an error and the channel shall not be opened.
6171      *
6172      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6173      *
6174      * <p>Requires Permission:
6175      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6176      *
6177      * @param slotIndex the physical slot index of the ICC card
6178      * @param aid Application id. See ETSI 102.221 and 101.220.
6179      * @param p2 P2 parameter (described in ISO 7816-4).
6180      * @return an IccOpenLogicalChannelResponse object.
6181      * @hide
6182      */
6183     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6184     @SystemApi
6185     @Nullable
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)6186     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
6187             @Nullable String aid, int p2) {
6188         try {
6189             ITelephony telephony = getITelephony();
6190             if (telephony != null) {
6191                 return telephony.iccOpenLogicalChannelBySlot(slotIndex, getOpPackageName(), aid,
6192                         p2);
6193             }
6194         } catch (RemoteException ex) {
6195         } catch (NullPointerException ex) {
6196         }
6197         return null;
6198     }
6199 
6200     /**
6201      * Opens a logical channel to the ICC card.
6202      *
6203      * This operation wraps two APDU instructions:
6204      * <ul>
6205      *     <li>MANAGE CHANNEL to open a logical channel</li>
6206      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6207      * </ul>
6208      *
6209      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6210      * and 0x0C are guaranteed to be supported.
6211      *
6212      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6213      * considered an error and the channel shall not be opened.
6214      *
6215      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6216      *
6217      * <p>Requires Permission:
6218      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6219      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6220      *
6221      * @param AID Application id. See ETSI 102.221 and 101.220.
6222      * @param p2 P2 parameter (described in ISO 7816-4).
6223      * @return an IccOpenLogicalChannelResponse object.
6224      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6225      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6226      *             {@link android.se.omapi.Reader#openSession()},
6227      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
6228      */
6229     @Deprecated
iccOpenLogicalChannel(String AID, int p2)6230     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
6231         return iccOpenLogicalChannel(getSubId(), AID, p2);
6232     }
6233 
6234     /**
6235      * Opens a logical channel to the ICC card.
6236      *
6237      * This operation wraps two APDU instructions:
6238      * <ul>
6239      *     <li>MANAGE CHANNEL to open a logical channel</li>
6240      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6241      * </ul>
6242      *
6243      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6244      * and 0x0C are guaranteed to be supported.
6245      *
6246      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6247      * considered an error and the channel shall not be opened.
6248      *
6249      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6250      *
6251      * <p>Requires Permission:
6252      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6253      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6254      *
6255      * @param subId The subscription to use.
6256      * @param AID Application id. See ETSI 102.221 and 101.220.
6257      * @param p2 P2 parameter (described in ISO 7816-4).
6258      * @return an IccOpenLogicalChannelResponse object.
6259      * @hide
6260      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6261      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6262      *             {@link android.se.omapi.Reader#openSession()},
6263      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
6264      */
6265     @Deprecated
iccOpenLogicalChannel(int subId, String AID, int p2)6266     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
6267         try {
6268             ITelephony telephony = getITelephony();
6269             if (telephony != null)
6270                 return telephony.iccOpenLogicalChannel(subId, getOpPackageName(), AID, p2);
6271         } catch (RemoteException ex) {
6272         } catch (NullPointerException ex) {
6273         }
6274         return null;
6275     }
6276 
6277     /**
6278      * Closes a previously opened logical channel to the ICC card using the physical slot index.
6279      *
6280      * Use this method when no subscriptions are available on the SIM and the operation must be
6281      * performed using the physical slot index.
6282      *
6283      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6284      *
6285      * <p>Requires Permission:
6286      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6287      *
6288      * @param slotIndex the physical slot index of the ICC card
6289      * @param channel is the channel id to be closed as returned by a successful
6290      *            iccOpenLogicalChannel.
6291      * @return true if the channel was closed successfully.
6292      * @hide
6293      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6294      *             {@link android.se.omapi.Channel#close()}.
6295      */
6296     @Deprecated
6297     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6298     @SystemApi
iccCloseLogicalChannelBySlot(int slotIndex, int channel)6299     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
6300         try {
6301             ITelephony telephony = getITelephony();
6302             if (telephony != null) {
6303                 return telephony.iccCloseLogicalChannelBySlot(slotIndex, channel);
6304             }
6305         } catch (RemoteException ex) {
6306         } catch (NullPointerException ex) {
6307         }
6308         return false;
6309     }
6310 
6311     /**
6312      * Closes a previously opened logical channel to the ICC card.
6313      *
6314      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6315      *
6316      * <p>Requires Permission:
6317      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6318      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6319      *
6320      * @param channel is the channel id to be closed as returned by a successful
6321      *            iccOpenLogicalChannel.
6322      * @return true if the channel was closed successfully.
6323      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6324      *             {@link android.se.omapi.Channel#close()}.
6325      */
6326     @Deprecated
iccCloseLogicalChannel(int channel)6327     public boolean iccCloseLogicalChannel(int channel) {
6328         return iccCloseLogicalChannel(getSubId(), channel);
6329     }
6330 
6331     /**
6332      * Closes a previously opened logical channel to the ICC card.
6333      *
6334      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6335      *
6336      * <p>Requires Permission:
6337      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6338      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6339      *
6340      * @param subId The subscription to use.
6341      * @param channel is the channel id to be closed as returned by a successful
6342      *            iccOpenLogicalChannel.
6343      * @return true if the channel was closed successfully.
6344      * @hide
6345      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6346      *             {@link android.se.omapi.Channel#close()}.
6347      */
6348     @Deprecated
iccCloseLogicalChannel(int subId, int channel)6349     public boolean iccCloseLogicalChannel(int subId, int channel) {
6350         try {
6351             ITelephony telephony = getITelephony();
6352             if (telephony != null)
6353                 return telephony.iccCloseLogicalChannel(subId, channel);
6354         } catch (RemoteException ex) {
6355         } catch (NullPointerException ex) {
6356         }
6357         return false;
6358     }
6359 
6360     /**
6361      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
6362      *
6363      * Use this method when no subscriptions are available on the SIM and the operation must be
6364      * performed using the physical slot index.
6365      *
6366      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6367      *
6368      * <p>Requires Permission:
6369      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6370      *
6371      * @param slotIndex the physical slot index of the ICC card
6372      * @param channel is the channel id to be closed as returned by a successful
6373      *            iccOpenLogicalChannel.
6374      * @param cla Class of the APDU command.
6375      * @param instruction Instruction of the APDU command.
6376      * @param p1 P1 value of the APDU command.
6377      * @param p2 P2 value of the APDU command.
6378      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6379      *            is sent to the SIM.
6380      * @param data Data to be sent with the APDU.
6381      * @return The APDU response from the ICC card with the status appended at the end, or null if
6382      * there is an issue connecting to the Telephony service.
6383      * @hide
6384      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6385      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6386      */
6387     @Deprecated
6388     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6389     @SystemApi
6390     @Nullable
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6391     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
6392             int instruction, int p1, int p2, int p3, @Nullable String data) {
6393         try {
6394             ITelephony telephony = getITelephony();
6395             if (telephony != null) {
6396                 return telephony.iccTransmitApduLogicalChannelBySlot(slotIndex, channel, cla,
6397                         instruction, p1, p2, p3, data);
6398             }
6399         } catch (RemoteException ex) {
6400         } catch (NullPointerException ex) {
6401         }
6402         return null;
6403     }
6404 
6405     /**
6406      * Transmit an APDU to the ICC card over a logical channel.
6407      *
6408      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6409      *
6410      * <p>Requires Permission:
6411      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6412      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6413      *
6414      * @param channel is the channel id to be closed as returned by a successful
6415      *            iccOpenLogicalChannel.
6416      * @param cla Class of the APDU command.
6417      * @param instruction Instruction of the APDU command.
6418      * @param p1 P1 value of the APDU command.
6419      * @param p2 P2 value of the APDU command.
6420      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6421      *            is sent to the SIM.
6422      * @param data Data to be sent with the APDU.
6423      * @return The APDU response from the ICC card with the status appended at
6424      *            the end.
6425      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6426      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6427      */
6428     @Deprecated
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)6429     public String iccTransmitApduLogicalChannel(int channel, int cla,
6430             int instruction, int p1, int p2, int p3, String data) {
6431         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
6432                     instruction, p1, p2, p3, data);
6433     }
6434 
6435     /**
6436      * Transmit an APDU to the ICC card over a logical channel.
6437      *
6438      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6439      *
6440      * <p>Requires Permission:
6441      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6442      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6443      *
6444      * @param subId The subscription to use.
6445      * @param channel is the channel id to be closed as returned by a successful
6446      *            iccOpenLogicalChannel.
6447      * @param cla Class of the APDU command.
6448      * @param instruction Instruction of the APDU command.
6449      * @param p1 P1 value of the APDU command.
6450      * @param p2 P2 value of the APDU command.
6451      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6452      *            is sent to the SIM.
6453      * @param data Data to be sent with the APDU.
6454      * @return The APDU response from the ICC card with the status appended at
6455      *            the end.
6456      * @hide
6457      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6458      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6459      */
6460     @Deprecated
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)6461     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
6462             int instruction, int p1, int p2, int p3, String data) {
6463         try {
6464             ITelephony telephony = getITelephony();
6465             if (telephony != null)
6466                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
6467                     instruction, p1, p2, p3, data);
6468         } catch (RemoteException ex) {
6469         } catch (NullPointerException ex) {
6470         }
6471         return "";
6472     }
6473 
6474     /**
6475      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
6476      *
6477      * Use this method when no subscriptions are available on the SIM and the operation must be
6478      * performed using the physical slot index.
6479      *
6480      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6481      *
6482      * <p>Requires Permission:
6483      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6484      *
6485      * @param slotIndex the physical slot index of the ICC card to target
6486      * @param cla Class of the APDU command.
6487      * @param instruction Instruction of the APDU command.
6488      * @param p1 P1 value of the APDU command.
6489      * @param p2 P2 value of the APDU command.
6490      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6491      *            is sent to the SIM.
6492      * @param data Data to be sent with the APDU.
6493      * @return The APDU response from the ICC card with the status appended at
6494      *            the end.
6495      * @hide
6496      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6497      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6498      *             {@link android.se.omapi.Reader#openSession()},
6499      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6500      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6501      */
6502     @Deprecated
6503     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6504     @SystemApi
6505     @NonNull
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6506     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
6507             int p2, int p3, @Nullable String data) {
6508         try {
6509             ITelephony telephony = getITelephony();
6510             if (telephony != null) {
6511                 return telephony.iccTransmitApduBasicChannelBySlot(slotIndex, getOpPackageName(),
6512                         cla, instruction, p1, p2, p3, data);
6513             }
6514         } catch (RemoteException ex) {
6515         } catch (NullPointerException ex) {
6516         }
6517         return null;
6518     }
6519 
6520     /**
6521      * Transmit an APDU to the ICC card over the basic channel.
6522      *
6523      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6524      *
6525      * <p>Requires Permission:
6526      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6527      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6528      *
6529      * @param cla Class of the APDU command.
6530      * @param instruction Instruction of the APDU command.
6531      * @param p1 P1 value of the APDU command.
6532      * @param p2 P2 value of the APDU command.
6533      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6534      *            is sent to the SIM.
6535      * @param data Data to be sent with the APDU.
6536      * @return The APDU response from the ICC card with the status appended at
6537      *            the end.
6538      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6539      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6540      *             {@link android.se.omapi.Reader#openSession()},
6541      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6542      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6543      */
6544     @Deprecated
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)6545     public String iccTransmitApduBasicChannel(int cla,
6546             int instruction, int p1, int p2, int p3, String data) {
6547         return iccTransmitApduBasicChannel(getSubId(), cla,
6548                     instruction, p1, p2, p3, data);
6549     }
6550 
6551     /**
6552      * Transmit an APDU to the ICC card over the basic channel.
6553      *
6554      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6555      *
6556      * <p>Requires Permission:
6557      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6558      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6559      *
6560      * @param subId The subscription to use.
6561      * @param cla Class of the APDU command.
6562      * @param instruction Instruction of the APDU command.
6563      * @param p1 P1 value of the APDU command.
6564      * @param p2 P2 value of the APDU command.
6565      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6566      *            is sent to the SIM.
6567      * @param data Data to be sent with the APDU.
6568      * @return The APDU response from the ICC card with the status appended at
6569      *            the end.
6570      * @hide
6571      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6572      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6573      *             {@link android.se.omapi.Reader#openSession()},
6574      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6575      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6576      */
6577     @Deprecated
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)6578     public String iccTransmitApduBasicChannel(int subId, int cla,
6579             int instruction, int p1, int p2, int p3, String data) {
6580         try {
6581             ITelephony telephony = getITelephony();
6582             if (telephony != null)
6583                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
6584                     instruction, p1, p2, p3, data);
6585         } catch (RemoteException ex) {
6586         } catch (NullPointerException ex) {
6587         }
6588         return "";
6589     }
6590 
6591     /**
6592      * Returns the response APDU for a command APDU sent through SIM_IO.
6593      *
6594      * <p>Requires Permission:
6595      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6596      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6597      *
6598      * @param fileID
6599      * @param command
6600      * @param p1 P1 value of the APDU command.
6601      * @param p2 P2 value of the APDU command.
6602      * @param p3 P3 value of the APDU command.
6603      * @param filePath
6604      * @return The APDU response.
6605      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6606      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6607      *             {@link android.se.omapi.Reader#openSession()},
6608      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6609      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6610      */
6611     @Deprecated
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)6612     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
6613             String filePath) {
6614         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
6615     }
6616 
6617     /**
6618      * Returns the response APDU for a command APDU sent through SIM_IO.
6619      *
6620      * <p>Requires Permission:
6621      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6622      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6623      *
6624      * @param subId The subscription to use.
6625      * @param fileID
6626      * @param command
6627      * @param p1 P1 value of the APDU command.
6628      * @param p2 P2 value of the APDU command.
6629      * @param p3 P3 value of the APDU command.
6630      * @param filePath
6631      * @return The APDU response.
6632      * @hide
6633      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6634      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6635      *             {@link android.se.omapi.Reader#openSession()},
6636      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6637      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6638      */
6639     @Deprecated
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)6640     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
6641             int p3, String filePath) {
6642         try {
6643             ITelephony telephony = getITelephony();
6644             if (telephony != null)
6645                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
6646         } catch (RemoteException ex) {
6647         } catch (NullPointerException ex) {
6648         }
6649         return null;
6650     }
6651 
6652     /**
6653      * Send ENVELOPE to the SIM and return the response.
6654      *
6655      * <p>Requires Permission:
6656      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6657      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6658      *
6659      * @param content String containing SAT/USAT response in hexadecimal
6660      *                format starting with command tag. See TS 102 223 for
6661      *                details.
6662      * @return The APDU response from the ICC card in hexadecimal format
6663      *         with the last 4 bytes being the status word. If the command fails,
6664      *         returns an empty string.
6665      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6666      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6667      *             {@link android.se.omapi.Reader#openSession()},
6668      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6669      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6670      */
6671     @Deprecated
sendEnvelopeWithStatus(String content)6672     public String sendEnvelopeWithStatus(String content) {
6673         return sendEnvelopeWithStatus(getSubId(), content);
6674     }
6675 
6676     /**
6677      * Send ENVELOPE to the SIM and return the response.
6678      *
6679      * <p>Requires Permission:
6680      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6681      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6682      *
6683      * @param subId The subscription to use.
6684      * @param content String containing SAT/USAT response in hexadecimal
6685      *                format starting with command tag. See TS 102 223 for
6686      *                details.
6687      * @return The APDU response from the ICC card in hexadecimal format
6688      *         with the last 4 bytes being the status word. If the command fails,
6689      *         returns an empty string.
6690      * @hide
6691      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6692      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6693      *             {@link android.se.omapi.Reader#openSession()},
6694      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6695      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6696      */
6697     @Deprecated
sendEnvelopeWithStatus(int subId, String content)6698     public String sendEnvelopeWithStatus(int subId, String content) {
6699         try {
6700             ITelephony telephony = getITelephony();
6701             if (telephony != null)
6702                 return telephony.sendEnvelopeWithStatus(subId, content);
6703         } catch (RemoteException ex) {
6704         } catch (NullPointerException ex) {
6705         }
6706         return "";
6707     }
6708 
6709     /**
6710      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
6711      * Used for device configuration by some CDMA operators.
6712      *
6713      * <p>Requires Permission:
6714      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6715      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6716      *
6717      * @param itemID the ID of the item to read.
6718      * @return the NV item as a String, or null on any failure.
6719      *
6720      * @hide
6721      */
6722     @UnsupportedAppUsage
nvReadItem(int itemID)6723     public String nvReadItem(int itemID) {
6724         try {
6725             ITelephony telephony = getITelephony();
6726             if (telephony != null)
6727                 return telephony.nvReadItem(itemID);
6728         } catch (RemoteException ex) {
6729             Rlog.e(TAG, "nvReadItem RemoteException", ex);
6730         } catch (NullPointerException ex) {
6731             Rlog.e(TAG, "nvReadItem NPE", ex);
6732         }
6733         return "";
6734     }
6735 
6736     /**
6737      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
6738      * Used for device configuration by some CDMA operators.
6739      *
6740      * <p>Requires Permission:
6741      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6742      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6743      *
6744      * @param itemID the ID of the item to read.
6745      * @param itemValue the value to write, as a String.
6746      * @return true on success; false on any failure.
6747      *
6748      * @hide
6749      */
nvWriteItem(int itemID, String itemValue)6750     public boolean nvWriteItem(int itemID, String itemValue) {
6751         try {
6752             ITelephony telephony = getITelephony();
6753             if (telephony != null)
6754                 return telephony.nvWriteItem(itemID, itemValue);
6755         } catch (RemoteException ex) {
6756             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
6757         } catch (NullPointerException ex) {
6758             Rlog.e(TAG, "nvWriteItem NPE", ex);
6759         }
6760         return false;
6761     }
6762 
6763     /**
6764      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
6765      * Used for device configuration by some CDMA operators.
6766      *
6767      * <p>Requires Permission:
6768      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6769      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6770      *
6771      * @param preferredRoamingList byte array containing the new PRL.
6772      * @return true on success; false on any failure.
6773      *
6774      * @hide
6775      */
nvWriteCdmaPrl(byte[] preferredRoamingList)6776     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
6777         try {
6778             ITelephony telephony = getITelephony();
6779             if (telephony != null)
6780                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
6781         } catch (RemoteException ex) {
6782             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
6783         } catch (NullPointerException ex) {
6784             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
6785         }
6786         return false;
6787     }
6788 
6789     /**
6790      * Perform the specified type of NV config reset. The radio will be taken offline
6791      * and the device must be rebooted after the operation. Used for device
6792      * configuration by some CDMA operators.
6793      *
6794      * <p>Requires Permission:
6795      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6796      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6797      *
6798      * TODO: remove this one. use {@link #rebootRadio()} for reset type 1 and
6799      * {@link #resetRadioConfig()} for reset type 3
6800      *
6801      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
6802      * @return true on success; false on any failure.
6803      *
6804      * @hide
6805      */
6806     @UnsupportedAppUsage
nvResetConfig(int resetType)6807     public boolean nvResetConfig(int resetType) {
6808         try {
6809             ITelephony telephony = getITelephony();
6810             if (telephony != null) {
6811                 if (resetType == 1 /*1: reload NV reset */) {
6812                     return telephony.rebootModem(getSlotIndex());
6813                 } else if (resetType == 3 /*3: factory NV reset */) {
6814                     return telephony.resetModemConfig(getSlotIndex());
6815                 } else {
6816                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
6817                 }
6818             }
6819         } catch (RemoteException ex) {
6820             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
6821         } catch (NullPointerException ex) {
6822             Rlog.e(TAG, "nvResetConfig NPE", ex);
6823         }
6824         return false;
6825     }
6826 
6827     /**
6828      * Rollback modem configurations to factory default except some config which are in whitelist.
6829      * Used for device configuration by some carriers.
6830      *
6831      * <p>Requires Permission:
6832      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6833      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6834      *
6835      * @return {@code true} on success; {@code false} on any failure.
6836      *
6837      * @hide
6838      */
6839     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6840     @SystemApi
resetRadioConfig()6841     public boolean resetRadioConfig() {
6842         try {
6843             ITelephony telephony = getITelephony();
6844             if (telephony != null) {
6845                 return telephony.resetModemConfig(getSlotIndex());
6846             }
6847         } catch (RemoteException ex) {
6848             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
6849         } catch (NullPointerException ex) {
6850             Rlog.e(TAG, "resetRadioConfig NPE", ex);
6851         }
6852         return false;
6853     }
6854 
6855     /**
6856      * Generate a radio modem reset. Used for device configuration by some carriers.
6857      *
6858      * <p>Requires Permission:
6859      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6860      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6861      *
6862      * @return {@code true} on success; {@code false} on any failure.
6863      *
6864      * @hide
6865      */
6866     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6867     @SystemApi
rebootRadio()6868     public boolean rebootRadio() {
6869         try {
6870             ITelephony telephony = getITelephony();
6871             if (telephony != null) {
6872                 return telephony.rebootModem(getSlotIndex());
6873             }
6874         } catch (RemoteException ex) {
6875             Rlog.e(TAG, "rebootRadio RemoteException", ex);
6876         } catch (NullPointerException ex) {
6877             Rlog.e(TAG, "rebootRadio NPE", ex);
6878         }
6879         return false;
6880     }
6881 
6882     /**
6883      * Return an appropriate subscription ID for any situation.
6884      *
6885      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6886      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
6887      *
6888      */
getSubscriptionId()6889     public int getSubscriptionId() {
6890         return getSubId();
6891     }
6892 
6893     /**
6894      * Return an appropriate subscription ID for any situation.
6895      *
6896      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6897      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
6898      *
6899      */
getSubId()6900     private int getSubId() {
6901       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
6902         return mSubId;
6903       }
6904       return SubscriptionManager.getDefaultSubscriptionId();
6905     }
6906 
6907     /**
6908      * Return an appropriate subscription ID for any situation.
6909      *
6910      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6911      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
6912      * returned.
6913      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
6914      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
6915      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
6916      */
6917     @UnsupportedAppUsage
getSubId(int preferredSubId)6918     private int getSubId(int preferredSubId) {
6919         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
6920             return mSubId;
6921         }
6922         return preferredSubId;
6923     }
6924 
6925     /**
6926      * Return an appropriate phone ID for any situation.
6927      *
6928      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
6929      * associated with the provided subId is returned. Otherwise, the default phoneId associated
6930      * with the default subId will be returned.
6931      */
getPhoneId()6932     private int getPhoneId() {
6933         return SubscriptionManager.getPhoneId(getSubId());
6934     }
6935 
6936     /**
6937      * Return an appropriate phone ID for any situation.
6938      *
6939      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
6940      * associated with the provided subId is returned. Otherwise, return the phoneId associated
6941      * with the preferred subId based on caller's context.
6942      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
6943      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
6944      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
6945      */
6946     @UnsupportedAppUsage
getPhoneId(int preferredSubId)6947     private int getPhoneId(int preferredSubId) {
6948         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
6949     }
6950 
6951     /**
6952      * Return an appropriate slot index for any situation.
6953      *
6954      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
6955      * associated with the provided subId is returned. Otherwise, return the slot index associated
6956      * with the default subId.
6957      * If SIM is not inserted, return default SIM slot index.
6958      *
6959      * {@hide}
6960      */
6961     @VisibleForTesting
6962     @UnsupportedAppUsage
getSlotIndex()6963     public int getSlotIndex() {
6964         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
6965         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
6966             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
6967         }
6968         return slotIndex;
6969     }
6970 
6971     /**
6972      * Request that the next incoming call from a number matching {@code range} be intercepted.
6973      *
6974      * This API is intended for OEMs to provide a service for apps to verify the device's phone
6975      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
6976      * intercept the next incoming call from a number that lies within the range, within a timeout
6977      * specified by {@code timeoutMillis}.
6978      *
6979      * If such a phone call is received, the caller will be notified via
6980      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
6981      * If verification fails for any reason, the caller will be notified via
6982      * {@link NumberVerificationCallback#onVerificationFailed(int)}
6983      * on the provided {@link Executor}.
6984      *
6985      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
6986      * API must also be listed in the device configuration as an authorized app in
6987      * {@code packages/services/Telephony/res/values/config.xml} under the
6988      * {@code config_number_verification_package_name} key.
6989      *
6990      * @hide
6991      * @param range The range of phone numbers the caller expects a phone call from.
6992      * @param timeoutMillis The amount of time to wait for such a call, or the value of
6993      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
6994      * @param executor The {@link Executor} that callbacks should be executed on.
6995      * @param callback The callback to use for delivering results.
6996      */
6997     @SystemApi
6998     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)6999     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
7000             @NonNull @CallbackExecutor Executor executor,
7001             @NonNull NumberVerificationCallback callback) {
7002         if (executor == null) {
7003             throw new NullPointerException("Executor must be non-null");
7004         }
7005         if (callback == null) {
7006             throw new NullPointerException("Callback must be non-null");
7007         }
7008 
7009         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
7010             @Override
7011             public void onCallReceived(String phoneNumber) {
7012                 final long identity = Binder.clearCallingIdentity();
7013                 try {
7014                     executor.execute(() ->
7015                             callback.onCallReceived(phoneNumber));
7016                 } finally {
7017                     Binder.restoreCallingIdentity(identity);
7018                 }
7019             }
7020 
7021             @Override
7022             public void onVerificationFailed(int reason) {
7023                 final long identity = Binder.clearCallingIdentity();
7024                 try {
7025                     executor.execute(() ->
7026                             callback.onVerificationFailed(reason));
7027                 } finally {
7028                     Binder.restoreCallingIdentity(identity);
7029                 }
7030             }
7031         };
7032 
7033         try {
7034             ITelephony telephony = getITelephony();
7035             if (telephony != null) {
7036                 telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
7037                         getOpPackageName());
7038             }
7039         } catch (RemoteException ex) {
7040             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
7041             executor.execute(() ->
7042                     callback.onVerificationFailed(NumberVerificationCallback.REASON_UNSPECIFIED));
7043         }
7044     }
7045 
7046     /**
7047      * Inserts or updates a list property. Expands the list if its length is not enough.
7048      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)7049     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
7050         List<T> ret = new ArrayList<>(prop);
7051         while (ret.size() <= phoneId) ret.add(null);
7052         ret.set(phoneId, value);
7053         return ret;
7054     }
7055     /**
7056      * Convenience function for retrieving a value from the secure settings
7057      * value list as an integer.  Note that internally setting values are
7058      * always stored as strings; this function converts the string to an
7059      * integer for you.
7060      * <p>
7061      * This version does not take a default value.  If the setting has not
7062      * been set, or the string value is not a number,
7063      * it throws {@link SettingNotFoundException}.
7064      *
7065      * @param cr The ContentResolver to access.
7066      * @param name The name of the setting to retrieve.
7067      * @param index The index of the list
7068      *
7069      * @throws SettingNotFoundException Thrown if a setting by the given
7070      * name can't be found or the setting value is not an integer.
7071      *
7072      * @return The value at the given index of settings.
7073      * @hide
7074      */
7075     @UnsupportedAppUsage
getIntAtIndex(android.content.ContentResolver cr, String name, int index)7076     public static int getIntAtIndex(android.content.ContentResolver cr,
7077             String name, int index)
7078             throws android.provider.Settings.SettingNotFoundException {
7079         String v = android.provider.Settings.Global.getString(cr, name);
7080         if (v != null) {
7081             String valArray[] = v.split(",");
7082             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
7083                 try {
7084                     return Integer.parseInt(valArray[index]);
7085                 } catch (NumberFormatException e) {
7086                     //Log.e(TAG, "Exception while parsing Integer: ", e);
7087                 }
7088             }
7089         }
7090         throw new android.provider.Settings.SettingNotFoundException(name);
7091     }
7092 
7093     /**
7094      * Convenience function for updating settings value as coma separated
7095      * integer values. This will either create a new entry in the table if the
7096      * given name does not exist, or modify the value of the existing row
7097      * with that name.  Note that internally setting values are always
7098      * stored as strings, so this function converts the given value to a
7099      * string before storing it.
7100      *
7101      * @param cr The ContentResolver to access.
7102      * @param name The name of the setting to modify.
7103      * @param index The index of the list
7104      * @param value The new value for the setting to be added to the list.
7105      * @return true if the value was set, false on database errors
7106      * @hide
7107      */
7108     @UnsupportedAppUsage
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)7109     public static boolean putIntAtIndex(android.content.ContentResolver cr,
7110             String name, int index, int value) {
7111         String data = "";
7112         String valArray[] = null;
7113         String v = android.provider.Settings.Global.getString(cr, name);
7114 
7115         if (index == Integer.MAX_VALUE) {
7116             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
7117         }
7118         if (index < 0) {
7119             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
7120         }
7121         if (v != null) {
7122             valArray = v.split(",");
7123         }
7124 
7125         // Copy the elements from valArray till index
7126         for (int i = 0; i < index; i++) {
7127             String str = "";
7128             if ((valArray != null) && (i < valArray.length)) {
7129                 str = valArray[i];
7130             }
7131             data = data + str + ",";
7132         }
7133 
7134         data = data + value;
7135 
7136         // Copy the remaining elements from valArray if any.
7137         if (valArray != null) {
7138             for (int i = index+1; i < valArray.length; i++) {
7139                 data = data + "," + valArray[i];
7140             }
7141         }
7142         return android.provider.Settings.Global.putString(cr, name, data);
7143     }
7144 
7145     /**
7146      * Gets a per-phone telephony property from a property name.
7147      *
7148      * @hide
7149      */
7150     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)7151     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
7152         String propVal = null;
7153         String prop = SystemProperties.get(property);
7154         if ((prop != null) && (prop.length() > 0)) {
7155             String values[] = prop.split(",");
7156             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
7157                 propVal = values[phoneId];
7158             }
7159         }
7160         return propVal == null ? defaultVal : propVal;
7161     }
7162 
7163     /**
7164      * Gets a typed per-phone telephony property from a schematized list property.
7165      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)7166     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
7167         T ret = null;
7168         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
7169         return ret != null ? ret : defaultValue;
7170     }
7171 
7172     /**
7173      * Gets a global telephony property.
7174      *
7175      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
7176      * per-phone.
7177      *
7178      * @hide
7179      */
7180     @UnsupportedAppUsage
getTelephonyProperty(String property, String defaultVal)7181     public static String getTelephonyProperty(String property, String defaultVal) {
7182         String propVal = SystemProperties.get(property);
7183         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
7184     }
7185 
7186     /** @hide */
7187     @UnsupportedAppUsage
getSimCount()7188     public int getSimCount() {
7189         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
7190         // and then this method shouldn't be used at all!
7191         return getPhoneCount();
7192     }
7193 
7194     /**
7195      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
7196      *
7197      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
7198      *
7199      * @return IMS Service Table or null if not present or not loaded
7200      * @hide
7201      */
7202     @Nullable
7203     @SystemApi
7204     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimIst()7205     public String getIsimIst() {
7206         try {
7207             IPhoneSubInfo info = getSubscriberInfoService();
7208             if (info == null)
7209                 return null;
7210             //get the Isim Ist based on subId
7211             return info.getIsimIst(getSubId());
7212         } catch (RemoteException ex) {
7213             return null;
7214         } catch (NullPointerException ex) {
7215             // This could happen before phone restarts due to crashing
7216             return null;
7217         }
7218     }
7219 
7220     /**
7221      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
7222      * @return an array of PCSCF strings with one PCSCF per string, or null if
7223      *         not present or not loaded
7224      * @hide
7225      */
7226     @UnsupportedAppUsage
getIsimPcscf()7227     public String[] getIsimPcscf() {
7228         try {
7229             IPhoneSubInfo info = getSubscriberInfoService();
7230             if (info == null)
7231                 return null;
7232             //get the Isim Pcscf based on subId
7233             return info.getIsimPcscf(getSubId());
7234         } catch (RemoteException ex) {
7235             return null;
7236         } catch (NullPointerException ex) {
7237             // This could happen before phone restarts due to crashing
7238             return null;
7239         }
7240     }
7241 
7242     /** UICC application type is SIM */
7243     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
7244     /** UICC application type is USIM */
7245     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
7246     /** UICC application type is RUIM */
7247     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
7248     /** UICC application type is CSIM */
7249     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
7250     /** UICC application type is ISIM */
7251     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
7252 
7253     // authContext (parameter P2) when doing UICC challenge,
7254     // per 3GPP TS 31.102 (Section 7.1.2)
7255     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
7256     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
7257     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
7258     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
7259 
7260     /**
7261      * Returns the response of authentication for the default subscription.
7262      * Returns null if the authentication hasn't been successful
7263      *
7264      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE or that the calling
7265      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7266      *
7267      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7268      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
7269      * {@link #AUTHTYPE_EAP_SIM}
7270      * @param data authentication challenge data, base64 encoded.
7271      * See 3GPP TS 31.102 7.1.2 for more details.
7272      * @return the response of authentication. This value will be null in the following cases:
7273      *   Authentication error, incorrect MAC
7274      *   Authentication error, security context not supported
7275      *   Key freshness failure
7276      *   Authentication error, no memory space available
7277      *   Authentication error, no memory space available in EFMUK
7278      */
7279     // TODO(b/73660190): This should probably require MODIFY_PHONE_STATE, not
7280     // READ_PRIVILEGED_PHONE_STATE. It certainly shouldn't reference the permission in Javadoc since
7281     // it's not public API.
getIccAuthentication(int appType, int authType, String data)7282     public String getIccAuthentication(int appType, int authType, String data) {
7283         return getIccAuthentication(getSubId(), appType, authType, data);
7284     }
7285 
7286     /**
7287      * Returns the response of USIM Authentication for specified subId.
7288      * Returns null if the authentication hasn't been successful
7289      *
7290      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7291      *
7292      * @param subId subscription ID used for authentication
7293      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7294      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
7295      * {@link #AUTHTYPE_EAP_SIM}
7296      * @param data authentication challenge data, base64 encoded.
7297      * See 3GPP TS 31.102 7.1.2 for more details.
7298      * @return the response of authentication. This value will be null in the following cases only
7299      * (see 3GPP TS 31.102 7.3.1):
7300      *   Authentication error, incorrect MAC
7301      *   Authentication error, security context not supported
7302      *   Key freshness failure
7303      *   Authentication error, no memory space available
7304      *   Authentication error, no memory space available in EFMUK
7305      * @hide
7306      */
7307     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType, int authType, String data)7308     public String getIccAuthentication(int subId, int appType, int authType, String data) {
7309         try {
7310             IPhoneSubInfo info = getSubscriberInfoService();
7311             if (info == null)
7312                 return null;
7313             return info.getIccSimChallengeResponse(subId, appType, authType, data);
7314         } catch (RemoteException ex) {
7315             return null;
7316         } catch (NullPointerException ex) {
7317             // This could happen before phone starts
7318             return null;
7319         }
7320     }
7321 
7322     /**
7323      * Returns an array of Forbidden PLMNs from the USIM App
7324      * Returns null if the query fails.
7325      *
7326      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
7327      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7328      *
7329      * @return an array of forbidden PLMNs or null if not available
7330      */
7331     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7332     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns()7333     public String[] getForbiddenPlmns() {
7334       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
7335     }
7336 
7337     /**
7338      * Returns an array of Forbidden PLMNs from the specified SIM App
7339      * Returns null if the query fails.
7340      *
7341      * @param subId subscription ID used for authentication
7342      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7343      * @return fplmns an array of forbidden PLMNs
7344      * @hide
7345      */
7346     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)7347     public String[] getForbiddenPlmns(int subId, int appType) {
7348         try {
7349             ITelephony telephony = getITelephony();
7350             if (telephony == null)
7351                 return null;
7352             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
7353                     getAttributionTag());
7354         } catch (RemoteException ex) {
7355             return null;
7356         } catch (NullPointerException ex) {
7357             // This could happen before phone starts
7358             return null;
7359         }
7360     }
7361 
7362     /**
7363      * Replace the contents of the forbidden PLMN SIM file with the provided values.
7364      * Passing an empty list will clear the contents of the EFfplmn file.
7365      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
7366      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
7367      * If the list is longer than the size of EFfplmn, then the file will be written from the
7368      * beginning of the list up to the file size.
7369      *
7370      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
7371      * MODIFY_PHONE_STATE}
7372      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7373      *
7374      * @param fplmns a list of PLMNs to be forbidden.
7375      *
7376      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
7377      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
7378      * room for all of the values passed in. Return -1 in the event of an unexpected failure
7379      */
7380     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7381     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setForbiddenPlmns(@onNull List<String> fplmns)7382     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
7383         try {
7384             ITelephony telephony = getITelephony();
7385             if (telephony == null) return -1;
7386             return telephony.setForbiddenPlmns(
7387                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
7388         } catch (RemoteException ex) {
7389             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
7390         } catch (NullPointerException ex) {
7391             // This could happen before phone starts
7392             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
7393         }
7394         return -1;
7395     }
7396 
7397     /**
7398      * Get P-CSCF address from PCO after data connection is established or modified.
7399      * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN
7400      * @return array of P-CSCF address
7401      * @hide
7402      */
getPcscfAddress(String apnType)7403     public String[] getPcscfAddress(String apnType) {
7404         try {
7405             ITelephony telephony = getITelephony();
7406             if (telephony == null)
7407                 return new String[0];
7408             return telephony.getPcscfAddress(apnType, getOpPackageName(), getAttributionTag());
7409         } catch (RemoteException e) {
7410             return new String[0];
7411         }
7412     }
7413 
7414 
7415     /**
7416      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
7417      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
7418      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
7419      * state.
7420      *
7421      * @param slotIndex the sim slot to reset the IMS stack on.
7422      * @hide */
7423     @SystemApi
7424     @WorkerThread
7425     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetIms(int slotIndex)7426     public void resetIms(int slotIndex) {
7427         try {
7428             ITelephony telephony = getITelephony();
7429             if (telephony != null) {
7430                 telephony.resetIms(slotIndex);
7431             }
7432         } catch (RemoteException e) {
7433             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
7434                     + e.getMessage());
7435         }
7436     }
7437 
7438     /**
7439      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
7440      * status updates, if not already enabled.
7441      * @hide
7442      */
enableIms(int slotId)7443     public void enableIms(int slotId) {
7444         try {
7445             ITelephony telephony = getITelephony();
7446             if (telephony != null) {
7447                 telephony.enableIms(slotId);
7448             }
7449         } catch (RemoteException e) {
7450             Rlog.e(TAG, "enableIms, RemoteException: "
7451                     + e.getMessage());
7452         }
7453     }
7454 
7455     /**
7456      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
7457      * status updates to disabled.
7458      * @hide
7459      */
disableIms(int slotId)7460     public void disableIms(int slotId) {
7461         try {
7462             ITelephony telephony = getITelephony();
7463             if (telephony != null) {
7464                 telephony.disableIms(slotId);
7465             }
7466         } catch (RemoteException e) {
7467             Rlog.e(TAG, "disableIms, RemoteException: "
7468                     + e.getMessage());
7469         }
7470     }
7471 
7472     /**
7473      * Returns the {@link IImsMmTelFeature} that corresponds to the given slot Id and MMTel
7474      * feature or {@link null} if the service is not available. If an MMTelFeature is available, the
7475      * {@link IImsServiceFeatureCallback} callback is registered as a listener for feature updates.
7476      * @param slotIndex The SIM slot that we are requesting the {@link IImsMmTelFeature} for.
7477      * @param callback Listener that will send updates to ImsManager when there are updates to
7478      * ImsServiceController.
7479      * @return {@link IImsMmTelFeature} interface for the feature specified or {@code null} if
7480      * it is unavailable.
7481      * @hide
7482      */
getImsMmTelFeatureAndListen(int slotIndex, IImsServiceFeatureCallback callback)7483     public @Nullable IImsMmTelFeature getImsMmTelFeatureAndListen(int slotIndex,
7484             IImsServiceFeatureCallback callback) {
7485         try {
7486             ITelephony telephony = getITelephony();
7487             if (telephony != null) {
7488                 return telephony.getMmTelFeatureAndListen(slotIndex, callback);
7489             }
7490         } catch (RemoteException e) {
7491             Rlog.e(TAG, "getImsMmTelFeatureAndListen, RemoteException: "
7492                     + e.getMessage());
7493         }
7494         return null;
7495     }
7496 
7497     /**
7498      * Returns the {@link IImsRcsFeature} that corresponds to the given slot Id and RCS
7499      * feature for emergency calling or {@link null} if the service is not available. If an
7500      * RcsFeature is available, the {@link IImsServiceFeatureCallback} callback is registered as a
7501      * listener for feature updates.
7502      * @param slotIndex The SIM slot that we are requesting the {@link IImsRcsFeature} for.
7503      * @param callback Listener that will send updates to ImsManager when there are updates to
7504      * ImsServiceController.
7505      * @return {@link IImsRcsFeature} interface for the feature specified or {@code null} if
7506      * it is unavailable.
7507      * @hide
7508      */
getImsRcsFeatureAndListen(int slotIndex, IImsServiceFeatureCallback callback)7509     public @Nullable IImsRcsFeature getImsRcsFeatureAndListen(int slotIndex,
7510             IImsServiceFeatureCallback callback) {
7511         try {
7512             ITelephony telephony = getITelephony();
7513             if (telephony != null) {
7514                 return telephony.getRcsFeatureAndListen(slotIndex, callback);
7515             }
7516         } catch (RemoteException e) {
7517             Rlog.e(TAG, "getImsRcsFeatureAndListen, RemoteException: "
7518                     + e.getMessage());
7519         }
7520         return null;
7521     }
7522 
7523     /**
7524      * Unregister a IImsServiceFeatureCallback previously associated with an ImsFeature through
7525      * {@link #getImsMmTelFeatureAndListen(int, IImsServiceFeatureCallback)} or
7526      * {@link #getImsRcsFeatureAndListen(int, IImsServiceFeatureCallback)}.
7527      * @param slotIndex The SIM slot associated with the callback.
7528      * @param featureType The {@link android.telephony.ims.feature.ImsFeature.FeatureType}
7529      *                    associated with the callback.
7530      * @param callback The callback to be unregistered.
7531      * @hide
7532      */
unregisterImsFeatureCallback(int slotIndex, int featureType, IImsServiceFeatureCallback callback)7533     public void unregisterImsFeatureCallback(int slotIndex, int featureType,
7534             IImsServiceFeatureCallback callback) {
7535         try {
7536             ITelephony telephony = getITelephony();
7537             if (telephony != null) {
7538                 telephony.unregisterImsFeatureCallback(slotIndex, featureType, callback);
7539             }
7540         } catch (RemoteException e) {
7541             Rlog.e(TAG, "unregisterImsFeatureCallback, RemoteException: "
7542                     + e.getMessage());
7543         }
7544     }
7545 
7546     /**
7547      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
7548      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
7549      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
7550      * Corresponds to features defined in ImsFeature.
7551      * @hide
7552      */
7553     @UnsupportedAppUsage
getImsRegistration(int slotIndex, int feature)7554     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
7555         try {
7556             ITelephony telephony = getITelephony();
7557             if (telephony != null) {
7558                 return telephony.getImsRegistration(slotIndex, feature);
7559             }
7560         } catch (RemoteException e) {
7561             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7562         }
7563         return null;
7564     }
7565 
7566     /**
7567      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
7568      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
7569      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
7570      * Corresponds to features defined in ImsFeature.
7571      * @hide
7572      */
7573     @UnsupportedAppUsage
getImsConfig(int slotIndex, int feature)7574     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
7575         try {
7576             ITelephony telephony = getITelephony();
7577             if (telephony != null) {
7578                 return telephony.getImsConfig(slotIndex, feature);
7579             }
7580         } catch (RemoteException e) {
7581             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7582         }
7583         return null;
7584     }
7585 
7586     /**
7587      * Set IMS registration state
7588      *
7589      * @param Registration state
7590      * @hide
7591      */
7592     @UnsupportedAppUsage
setImsRegistrationState(boolean registered)7593     public void setImsRegistrationState(boolean registered) {
7594         try {
7595             ITelephony telephony = getITelephony();
7596             if (telephony != null)
7597                 telephony.setImsRegistrationState(registered);
7598         } catch (RemoteException e) {
7599         }
7600     }
7601 
7602     /** @hide */
7603     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
7604             NETWORK_MODE_WCDMA_PREF,
7605             NETWORK_MODE_GSM_ONLY,
7606             NETWORK_MODE_WCDMA_ONLY,
7607             NETWORK_MODE_GSM_UMTS,
7608             NETWORK_MODE_CDMA_EVDO,
7609             NETWORK_MODE_CDMA_NO_EVDO,
7610             NETWORK_MODE_EVDO_NO_CDMA,
7611             NETWORK_MODE_GLOBAL,
7612             NETWORK_MODE_LTE_CDMA_EVDO,
7613             NETWORK_MODE_LTE_GSM_WCDMA,
7614             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
7615             NETWORK_MODE_LTE_ONLY,
7616             NETWORK_MODE_LTE_WCDMA,
7617             NETWORK_MODE_TDSCDMA_ONLY,
7618             NETWORK_MODE_TDSCDMA_WCDMA,
7619             NETWORK_MODE_LTE_TDSCDMA,
7620             NETWORK_MODE_TDSCDMA_GSM,
7621             NETWORK_MODE_LTE_TDSCDMA_GSM,
7622             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
7623             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
7624             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
7625             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7626             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7627             NETWORK_MODE_NR_ONLY,
7628             NETWORK_MODE_NR_LTE,
7629             NETWORK_MODE_NR_LTE_CDMA_EVDO,
7630             NETWORK_MODE_NR_LTE_GSM_WCDMA,
7631             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
7632             NETWORK_MODE_NR_LTE_WCDMA,
7633             NETWORK_MODE_NR_LTE_TDSCDMA,
7634             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
7635             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
7636             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
7637             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
7638     })
7639     @Retention(RetentionPolicy.SOURCE)
7640     public @interface PrefNetworkMode{}
7641 
7642     /**
7643      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
7644      * @hide
7645      */
7646     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
7647 
7648     /**
7649      * Preferred network mode is GSM only.
7650      * @hide
7651      */
7652     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
7653 
7654     /**
7655      * Preferred network mode is WCDMA only.
7656      * @hide
7657      */
7658     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
7659 
7660     /**
7661      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
7662      * @hide
7663      */
7664     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
7665 
7666     /**
7667      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
7668      * @hide
7669      */
7670     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
7671 
7672     /**
7673      * Preferred network mode is CDMA only.
7674      * @hide
7675      */
7676     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
7677 
7678     /**
7679      * Preferred network mode is EvDo only.
7680      * @hide
7681      */
7682     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
7683 
7684     /**
7685      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
7686      * @hide
7687      */
7688     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
7689 
7690     /**
7691      * Preferred network mode is LTE, CDMA and EvDo.
7692      * @hide
7693      */
7694     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
7695 
7696     /**
7697      * Preferred network mode is LTE, GSM/WCDMA.
7698      * @hide
7699      */
7700     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
7701 
7702     /**
7703      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
7704      * @hide
7705      */
7706     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
7707             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
7708 
7709     /**
7710      * Preferred network mode is LTE Only.
7711      * @hide
7712      */
7713     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
7714 
7715     /**
7716      * Preferred network mode is LTE/WCDMA.
7717      * @hide
7718      */
7719     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
7720 
7721     /**
7722      * Preferred network mode is TD-SCDMA only.
7723      * @hide
7724      */
7725     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
7726 
7727     /**
7728      * Preferred network mode is TD-SCDMA and WCDMA.
7729      * @hide
7730      */
7731     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
7732 
7733     /**
7734      * Preferred network mode is TD-SCDMA and LTE.
7735      * @hide
7736      */
7737     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
7738 
7739     /**
7740      * Preferred network mode is TD-SCDMA and GSM.
7741      * @hide
7742      */
7743     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
7744 
7745     /**
7746      * Preferred network mode is TD-SCDMA,GSM and LTE.
7747      * @hide
7748      */
7749     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
7750             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
7751 
7752     /**
7753      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
7754      * @hide
7755      */
7756     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
7757             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
7758 
7759     /**
7760      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
7761      * @hide
7762      */
7763     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
7764             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
7765 
7766     /**
7767      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
7768      * @hide
7769      */
7770     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
7771             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
7772 
7773     /**
7774      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
7775      * @hide
7776      */
7777     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7778             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7779     /**
7780      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
7781      * @hide
7782      */
7783     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7784             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7785 
7786     /**
7787      * Preferred network mode is NR 5G only.
7788      * @hide
7789      */
7790     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
7791 
7792     /**
7793      * Preferred network mode is NR 5G, LTE.
7794      * @hide
7795      */
7796     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
7797 
7798     /**
7799      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
7800      * @hide
7801      */
7802     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
7803             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
7804 
7805     /**
7806      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
7807      * @hide
7808      */
7809     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
7810             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
7811 
7812     /**
7813      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
7814      * @hide
7815      */
7816     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
7817             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
7818 
7819     /**
7820      * Preferred network mode is NR 5G, LTE and WCDMA.
7821      * @hide
7822      */
7823     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
7824 
7825     /**
7826      * Preferred network mode is NR 5G, LTE and TDSCDMA.
7827      * @hide
7828      */
7829     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
7830 
7831     /**
7832      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
7833      * @hide
7834      */
7835     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
7836             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
7837 
7838     /**
7839      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
7840      * @hide
7841      */
7842     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
7843             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
7844 
7845     /**
7846      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
7847      * @hide
7848      */
7849     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
7850             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
7851 
7852     /**
7853      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
7854      * @hide
7855      */
7856     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7857             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7858 
7859     /**
7860      * The default preferred network mode constant.
7861      *
7862      * <p> This constant is used in case of nothing is set in
7863      * TelephonyProperties#default_network().
7864      *
7865      * @hide
7866      */
7867     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
7868             RILConstants.PREFERRED_NETWORK_MODE;
7869 
7870     /**
7871      * Get the preferred network type.
7872      * Used for device configuration by some CDMA operators.
7873      *
7874      * <p>Requires Permission:
7875      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7876      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7877      *
7878      * @return the preferred network type.
7879      * @hide
7880      * @deprecated Use {@link #getPreferredNetworkTypeBitmask} instead.
7881      */
7882     @Deprecated
7883     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
7884     @UnsupportedAppUsage
getPreferredNetworkType(int subId)7885     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
7886         try {
7887             ITelephony telephony = getITelephony();
7888             if (telephony != null) {
7889                 return telephony.getPreferredNetworkType(subId);
7890             }
7891         } catch (RemoteException ex) {
7892             Rlog.e(TAG, "getPreferredNetworkType RemoteException", ex);
7893         }
7894         return -1;
7895     }
7896 
7897     /**
7898      * Get the preferred network type bitmask.
7899      *
7900      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7901      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7902      *
7903      * <p>Requires Permission:
7904      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7905      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7906      *
7907      * @return The bitmask of preferred network types.
7908      *
7909      * @hide
7910      */
7911     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
7912     @SystemApi
getPreferredNetworkTypeBitmask()7913     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
7914         try {
7915             ITelephony telephony = getITelephony();
7916             if (telephony != null) {
7917                 return (long) RadioAccessFamily.getRafFromNetworkType(
7918                         telephony.getPreferredNetworkType(getSubId()));
7919             }
7920         } catch (RemoteException ex) {
7921             Rlog.e(TAG, "getPreferredNetworkTypeBitmask RemoteException", ex);
7922         }
7923         return 0;
7924     }
7925 
7926     /**
7927      * Get the allowed network types.
7928      *
7929      * <p>Requires Permission:
7930      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7931      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7932      *
7933      * @return the allowed network type bitmask
7934      * @hide
7935      */
7936     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
7937     @SystemApi
getAllowedNetworkTypes()7938     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
7939         try {
7940             ITelephony telephony = getITelephony();
7941             if (telephony != null) {
7942                 return telephony.getAllowedNetworkTypes(getSubId());
7943             }
7944         } catch (RemoteException ex) {
7945             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
7946         }
7947         return -1;
7948     }
7949 
7950     /**
7951      * Sets the network selection mode to automatic.
7952      *
7953      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7954      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7955      *
7956      * <p>Requires Permission:
7957      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7958      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7959      */
7960     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7961     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeAutomatic()7962     public void setNetworkSelectionModeAutomatic() {
7963         try {
7964             ITelephony telephony = getITelephony();
7965             if (telephony != null) {
7966                 telephony.setNetworkSelectionModeAutomatic(getSubId());
7967             }
7968         } catch (RemoteException ex) {
7969             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
7970         } catch (NullPointerException ex) {
7971             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
7972         }
7973     }
7974 
7975     /**
7976      * Perform a radio scan and return the list of available networks.
7977      *
7978      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7979      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7980      *
7981      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
7982      *
7983      * <p>Requires Permissions:
7984      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
7985      * privileges (see {@link #hasCarrierPrivileges})
7986      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
7987      *
7988      * @return {@link CellNetworkScanResult} with the status
7989      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
7990      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
7991      * caused will be included in the result.
7992      *
7993      * @hide
7994      */
7995     @RequiresPermission(allOf = {
7996             android.Manifest.permission.MODIFY_PHONE_STATE,
7997             Manifest.permission.ACCESS_COARSE_LOCATION
7998     })
getAvailableNetworks()7999     public CellNetworkScanResult getAvailableNetworks() {
8000         try {
8001             ITelephony telephony = getITelephony();
8002             if (telephony != null) {
8003                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
8004                         getAttributionTag());
8005             }
8006         } catch (RemoteException ex) {
8007             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
8008         } catch (NullPointerException ex) {
8009             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
8010         }
8011         return new CellNetworkScanResult(
8012                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
8013     }
8014 
8015     /**
8016      * Request a network scan.
8017      *
8018      * This method is asynchronous, so the network scan results will be returned by callback.
8019      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
8020      *
8021      * <p>Requires Permission:
8022      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8023      * app has carrier privileges (see {@link #hasCarrierPrivileges})
8024      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
8025      *
8026      * If the system-wide location switch is off, apps may still call this API, with the
8027      * following constraints:
8028      * <ol>
8029      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
8030      *     <li>The app must not supply any specific bands or channels to scan.</li>
8031      *     <li>The app must only specify MCC/MNC pairs that are
8032      *     associated to a SIM in the device.</li>
8033      *     <li>Returned results will have no meaningful info other than signal strength
8034      *     and MCC/MNC info.</li>
8035      * </ol>
8036      *
8037      * @param request Contains all the RAT with bands/channels that need to be scanned.
8038      * @param executor The executor through which the callback should be invoked. Since the scan
8039      *        request may trigger multiple callbacks and they must be invoked in the same order as
8040      *        they are received by the platform, the user should provide an executor which executes
8041      *        tasks one at a time in serial order. For example AsyncTask.SERIAL_EXECUTOR.
8042      * @param callback Returns network scan results or errors.
8043      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
8044      */
8045     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8046     @RequiresPermission(allOf = {
8047             android.Manifest.permission.MODIFY_PHONE_STATE,
8048             Manifest.permission.ACCESS_FINE_LOCATION
8049     })
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)8050     public NetworkScan requestNetworkScan(
8051             NetworkScanRequest request, Executor executor,
8052             TelephonyScanManager.NetworkScanCallback callback) {
8053         synchronized (this) {
8054             if (mTelephonyScanManager == null) {
8055                 mTelephonyScanManager = new TelephonyScanManager();
8056             }
8057         }
8058         return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback,
8059                 getOpPackageName(), getAttributionTag());
8060     }
8061 
8062     /**
8063      * @deprecated
8064      * Use {@link
8065      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
8066      * @removed
8067      */
8068     @Deprecated
8069     @RequiresPermission(allOf = {
8070             android.Manifest.permission.MODIFY_PHONE_STATE,
8071             Manifest.permission.ACCESS_FINE_LOCATION
8072     })
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)8073     public NetworkScan requestNetworkScan(
8074         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
8075         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
8076     }
8077 
8078     /**
8079      * Ask the radio to connect to the input network and change selection mode to manual.
8080      *
8081      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8082      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8083      *
8084      * <p>Requires Permission:
8085      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8086      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8087      *
8088      * @param operatorNumeric the PLMN ID of the network to select.
8089      * @param persistSelection whether the selection will persist until reboot. If true, only allows
8090      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
8091      * normal network selection next time.
8092      * @return {@code true} on success; {@code false} on any failure.
8093      */
8094     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8095     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)8096     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
8097         return setNetworkSelectionModeManual(
8098                 new OperatorInfo(
8099                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
8100                 persistSelection);
8101     }
8102 
8103     /**
8104      * Ask the radio to connect to the input network and change selection mode to manual.
8105      *
8106      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8107      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8108      *
8109      * <p>Requires Permission:
8110      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8111      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8112      *
8113      * @param operatorNumeric the PLMN ID of the network to select.
8114      * @param persistSelection whether the selection will persist until reboot.
8115      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
8116      *         attach to the chosen PLMN and resume normal network selection next time.
8117      * @param ran the initial suggested radio access network type.
8118      *         If registration fails, the RAN is not available after, the RAN is not within the
8119      *         network types specified by the preferred network types, or the value is
8120      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
8121      *         the next best RAN for network registration.
8122      * @return {@code true} on success; {@code false} on any failure.
8123      */
8124     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)8125     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
8126             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
8127         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
8128                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
8129     }
8130 
8131     /**
8132      * Ask the radio to connect to the input network and change selection mode to manual.
8133      *
8134      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8135      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8136      *
8137      * <p>Requires Permission:
8138      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8139      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8140      *
8141      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
8142      * @param persistSelection whether the selection will persist until reboot. If true, only allows
8143      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
8144      * normal network selection next time.
8145      * @return {@code true} on success; {@code true} on any failure.
8146      *
8147      * @hide
8148      */
8149     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)8150     public boolean setNetworkSelectionModeManual(
8151             OperatorInfo operatorInfo, boolean persistSelection) {
8152         try {
8153             ITelephony telephony = getITelephony();
8154             if (telephony != null) {
8155                 return telephony.setNetworkSelectionModeManual(
8156                         getSubId(), operatorInfo, persistSelection);
8157             }
8158         } catch (RemoteException ex) {
8159             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
8160         }
8161         return false;
8162     }
8163 
8164    /**
8165      * Get the network selection mode.
8166      *
8167      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8168      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8169      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
8170      * READ_PRECISE_PHONE_STATE}
8171      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8172      *
8173      * @return the network selection mode.
8174      */
8175     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
8176     @RequiresPermission(anyOf = {
8177             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8178             android.Manifest.permission.READ_PRECISE_PHONE_STATE
8179     })
getNetworkSelectionMode()8180     public @NetworkSelectionMode int getNetworkSelectionMode() {
8181         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
8182         try {
8183             ITelephony telephony = getITelephony();
8184             if (telephony != null) {
8185                 mode = telephony.getNetworkSelectionMode(getSubId());
8186             }
8187         } catch (RemoteException ex) {
8188             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
8189         }
8190         return mode;
8191     }
8192 
8193     /**
8194      * Get the PLMN chosen for Manual Network Selection if active.
8195      * Return empty string if in automatic selection.
8196      *
8197      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
8198      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
8199      * (see {@link #hasCarrierPrivileges})
8200      *
8201      * @return manually selected network info on success or empty string on failure
8202      */
8203     @SuppressAutoDoc // No support carrier privileges (b/72967236).
8204     @RequiresPermission(android.Manifest.permission.READ_PRECISE_PHONE_STATE)
getManualNetworkSelectionPlmn()8205     public @NonNull String getManualNetworkSelectionPlmn() {
8206         try {
8207             ITelephony telephony = getITelephony();
8208             if (telephony != null && isManualNetworkSelectionAllowed()) {
8209                 return telephony.getManualNetworkSelectionPlmn(getSubId());
8210             }
8211         } catch (RemoteException ex) {
8212             Rlog.e(TAG, "getManualNetworkSelectionPlmn RemoteException", ex);
8213         }
8214         return "";
8215     }
8216 
8217     /**
8218      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
8219      * user and we are still within the time interval after the emergency SMS was sent that we are
8220      * considered in Emergency SMS mode.
8221      *
8222      * <p>This mode is used by other applications to allow them to perform special functionality,
8223      * such as allow the GNSS service to provide user location to the carrier network for emergency
8224      * when an emergency SMS is sent. This interval is set by
8225      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
8226      * the carrier does not support this mode, this function will always return false.
8227      *
8228      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
8229      *
8230      * @hide
8231      */
8232     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isInEmergencySmsMode()8233     public boolean isInEmergencySmsMode() {
8234         try {
8235             ITelephony telephony = getITelephony();
8236             if (telephony != null) {
8237                 return telephony.isInEmergencySmsMode();
8238             }
8239         } catch (RemoteException ex) {
8240             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
8241         }
8242         return false;
8243     }
8244 
8245     /**
8246      * Set the preferred network type.
8247      *
8248      * <p>Requires Permission:
8249      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8250      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8251      *
8252      * @param subId the id of the subscription to set the preferred network type for.
8253      * @param networkType the preferred network type
8254      * @return true on success; false on any failure.
8255      * @hide
8256      * @deprecated Use {@link #setPreferredNetworkTypeBitmask} instead.
8257      */
8258     @Deprecated
8259     @UnsupportedAppUsage
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)8260     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
8261         try {
8262             ITelephony telephony = getITelephony();
8263             if (telephony != null) {
8264                 return telephony.setPreferredNetworkType(subId, networkType);
8265             }
8266         } catch (RemoteException ex) {
8267             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
8268         }
8269         return false;
8270     }
8271 
8272     /**
8273      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
8274      * only the allowed network type will set to the modem.
8275      *
8276      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8277      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8278      *
8279      * <p>Requires Permission:
8280      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8281      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8282      *
8283      * @param networkTypeBitmask The bitmask of preferred network types.
8284      * @return true on success; false on any failure.
8285      * @hide
8286      */
8287     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8288     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)8289     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
8290         try {
8291             ITelephony telephony = getITelephony();
8292             if (telephony != null) {
8293                 return telephony.setPreferredNetworkType(
8294                         getSubId(), RadioAccessFamily.getNetworkTypeFromRaf(
8295                                 (int) networkTypeBitmask));
8296             }
8297         } catch (RemoteException ex) {
8298             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
8299         }
8300         return false;
8301     }
8302 
8303     /**
8304      * Set the allowed network types of the device. This is for carrier or privileged apps to
8305      * enable/disable certain network types on the device. The user preferred network types should
8306      * be set through {@link #setPreferredNetworkTypeBitmask}.
8307      *
8308      * @param allowedNetworkTypes The bitmask of allowed network types.
8309      * @return true on success; false on any failure.
8310      * @hide
8311      */
8312     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8313     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)8314     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
8315         try {
8316             ITelephony telephony = getITelephony();
8317             if (telephony != null) {
8318                 return telephony.setAllowedNetworkTypes(getSubId(), allowedNetworkTypes);
8319             }
8320         } catch (RemoteException ex) {
8321             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
8322         }
8323         return false;
8324     }
8325 
8326     /** @hide */
8327     @IntDef({
8328             ALLOWED_NETWORK_TYPES_REASON_POWER
8329     })
8330     @Retention(RetentionPolicy.SOURCE)
8331     public @interface AllowedNetworkTypesReason{}
8332 
8333     /**
8334      * To indicate allowed network type change is requested by power manager.
8335      * Power Manger configuration won't affect the settings configured through
8336      * {@link setAllowedNetworkTypes} and will result in allowing network types that are in both
8337      * configurations (i.e intersection of both sets).
8338      * @hide
8339      */
8340     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 0;
8341 
8342     /**
8343      * Set the allowed network types of the device and
8344      * provide the reason triggering the allowed network change.
8345      * This can be called for following reasons
8346      * <ol>
8347      * <li>Allowed network types control by power manager
8348      * {@link #ALLOWED_NETWORK_TYPES_REASON_POWER}
8349      * </ol>
8350      * This API will result in allowing an intersection of allowed network types for all reasons,
8351      * including the configuration done through {@link setAllowedNetworkTypes}.
8352      * While this API and {@link setAllowedNetworkTypes} is controlling allowed network types
8353      * on device, user preference will still be set through {@link #setPreferredNetworkTypeBitmask}.
8354      * Thus resultant network type configured on modem will be an intersection of the network types
8355      * from setAllowedNetworkTypesForReason, {@link setAllowedNetworkTypes}
8356      * and {@link #setPreferredNetworkTypeBitmask}.
8357      *
8358      * @param reason the reason the allowed network type change is taking place
8359      * @param allowedNetworkTypes The bitmask of allowed network types.
8360      * @throws IllegalStateException if the Telephony process is not currently available.
8361      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8362      * @hide
8363      */
8364     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)8365     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
8366             @NetworkTypeBitMask long allowedNetworkTypes) {
8367         if (reason != ALLOWED_NETWORK_TYPES_REASON_POWER) {
8368             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8369         }
8370         try {
8371             ITelephony telephony = getITelephony();
8372             if (telephony != null) {
8373                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
8374                         allowedNetworkTypes);
8375             } else {
8376                 throw new IllegalStateException("telephony service is null.");
8377             }
8378         } catch (RemoteException ex) {
8379             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
8380             ex.rethrowFromSystemServer();
8381         }
8382     }
8383 
8384     /**
8385      * Get the allowed network types for certain reason.
8386      *
8387      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
8388      * specific reason. For effective allowed network types configured on device,
8389      * query {@link getEffectiveAllowedNetworkTypes}
8390      *
8391      * <p>Requires Permission:
8392      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8393      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8394      *s
8395      * @param reason the reason the allowed network type change is taking place
8396      * @return the allowed network type bitmask
8397      * @throws IllegalStateException if the Telephony process is not currently available.
8398      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8399      * @hide
8400      */
8401     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)8402     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
8403             @AllowedNetworkTypesReason int reason) {
8404         if (reason != ALLOWED_NETWORK_TYPES_REASON_POWER) {
8405             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8406         }
8407         try {
8408             ITelephony telephony = getITelephony();
8409             if (telephony != null) {
8410                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
8411             } else {
8412                 throw new IllegalStateException("telephony service is null.");
8413             }
8414         } catch (RemoteException ex) {
8415             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
8416             ex.rethrowFromSystemServer();
8417         }
8418         return -1;
8419     }
8420 
8421     /**
8422      * Get bit mask of all network types.
8423      *
8424      * @return bit mask of all network types
8425      * @hide
8426      */
getAllNetworkTypesBitmask()8427     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
8428         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
8429     }
8430 
8431     /**
8432      * Get the allowed network types configured on the device.
8433      * This API will return an intersection of allowed network types for all reasons,
8434      * including the configuration done through setAllowedNetworkTypes
8435      *
8436      * <p>Requires Permission:
8437      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8438      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8439      *
8440      * @return the allowed network type bitmask
8441      * @throws IllegalStateException if the Telephony process is not currently available.
8442      * @hide
8443      */
8444     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEffectiveAllowedNetworkTypes()8445     public @NetworkTypeBitMask long getEffectiveAllowedNetworkTypes() {
8446         try {
8447             ITelephony telephony = getITelephony();
8448             if (telephony != null) {
8449                 return telephony.getEffectiveAllowedNetworkTypes(getSubId());
8450             } else {
8451                 throw new IllegalStateException("telephony service is null.");
8452             }
8453         } catch (RemoteException ex) {
8454             Rlog.e(TAG, "getEffectiveAllowedNetworkTypes RemoteException", ex);
8455             ex.rethrowFromSystemServer();
8456         }
8457         return -1;
8458     }
8459 
8460     /**
8461      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8462      *
8463      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8464      *
8465      * @return true on success; false on any failure.
8466      */
setPreferredNetworkTypeToGlobal()8467     public boolean setPreferredNetworkTypeToGlobal() {
8468         return setPreferredNetworkTypeToGlobal(getSubId());
8469     }
8470 
8471     /**
8472      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8473      *
8474      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8475      *
8476      * @return true on success; false on any failure.
8477      * @hide
8478      */
setPreferredNetworkTypeToGlobal(int subId)8479     public boolean setPreferredNetworkTypeToGlobal(int subId) {
8480         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
8481     }
8482 
8483     /**
8484      * Check whether DUN APN is required for tethering.
8485      * <p>
8486      * Requires Permission: MODIFY_PHONE_STATE.
8487      *
8488      * @return {@code true} if DUN APN is required for tethering.
8489      * @hide
8490      */
8491     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8492     @SystemApi
isTetheringApnRequired()8493     public boolean isTetheringApnRequired() {
8494         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
8495     }
8496 
8497     /**
8498      * Check whether DUN APN is required for tethering with subId.
8499      *
8500      * @param subId the id of the subscription to require tethering.
8501      * @return {@code true} if DUN APN is required for tethering.
8502      * @hide
8503      */
isTetheringApnRequired(int subId)8504     public boolean isTetheringApnRequired(int subId) {
8505         try {
8506             ITelephony telephony = getITelephony();
8507             if (telephony != null)
8508                 return telephony.isTetheringApnRequiredForSubscriber(subId);
8509         } catch (RemoteException ex) {
8510             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
8511         } catch (NullPointerException ex) {
8512             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
8513         }
8514         return false;
8515     }
8516 
8517 
8518     /**
8519      * Values used to return status for hasCarrierPrivileges call.
8520      */
8521     /** @hide */ @SystemApi @TestApi
8522     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
8523     /** @hide */ @SystemApi @TestApi
8524     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
8525     /** @hide */ @SystemApi @TestApi
8526     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
8527     /** @hide */ @SystemApi @TestApi
8528     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
8529 
8530     /**
8531      * Has the calling application been granted carrier privileges by the carrier.
8532      *
8533      * If any of the packages in the calling UID has carrier privileges, the
8534      * call will return true. This access is granted by the owner of the UICC
8535      * card and does not depend on the registered carrier.
8536      *
8537      * Note that this API applies to both physical and embedded subscriptions and
8538      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
8539      *
8540      * @return true if the app has carrier privileges.
8541      */
hasCarrierPrivileges()8542     public boolean hasCarrierPrivileges() {
8543         return hasCarrierPrivileges(getSubId());
8544     }
8545 
8546     /**
8547      * Has the calling application been granted carrier privileges by the carrier.
8548      *
8549      * If any of the packages in the calling UID has carrier privileges, the
8550      * call will return true. This access is granted by the owner of the UICC
8551      * card and does not depend on the registered carrier.
8552      *
8553      * Note that this API applies to both physical and embedded subscriptions and
8554      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
8555      *
8556      * @param subId The subscription to use.
8557      * @return true if the app has carrier privileges.
8558      * @hide
8559      */
hasCarrierPrivileges(int subId)8560     public boolean hasCarrierPrivileges(int subId) {
8561         try {
8562             ITelephony telephony = getITelephony();
8563             if (telephony != null) {
8564                 return telephony.getCarrierPrivilegeStatus(subId)
8565                         == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
8566             }
8567         } catch (RemoteException ex) {
8568             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
8569         } catch (NullPointerException ex) {
8570             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
8571         }
8572         return false;
8573     }
8574 
8575     /**
8576      * Override the branding for the current ICCID.
8577      *
8578      * Once set, whenever the SIM is present in the device, the service
8579      * provider name (SPN) and the operator name will both be replaced by the
8580      * brand value input. To unset the value, the same function should be
8581      * called with a null brand value.
8582      *
8583      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8584      *
8585      * @param brand The brand name to display/set.
8586      * @return true if the operation was executed correctly.
8587      */
setOperatorBrandOverride(String brand)8588     public boolean setOperatorBrandOverride(String brand) {
8589         return setOperatorBrandOverride(getSubId(), brand);
8590     }
8591 
8592     /**
8593      * Override the branding for the current ICCID.
8594      *
8595      * Once set, whenever the SIM is present in the device, the service
8596      * provider name (SPN) and the operator name will both be replaced by the
8597      * brand value input. To unset the value, the same function should be
8598      * called with a null brand value.
8599      *
8600      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8601      *
8602      * @param subId The subscription to use.
8603      * @param brand The brand name to display/set.
8604      * @return true if the operation was executed correctly.
8605      * @hide
8606      */
setOperatorBrandOverride(int subId, String brand)8607     public boolean setOperatorBrandOverride(int subId, String brand) {
8608         try {
8609             ITelephony telephony = getITelephony();
8610             if (telephony != null)
8611                 return telephony.setOperatorBrandOverride(subId, brand);
8612         } catch (RemoteException ex) {
8613             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
8614         } catch (NullPointerException ex) {
8615             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
8616         }
8617         return false;
8618     }
8619 
8620     /**
8621      * Override the roaming preference for the current ICCID.
8622      *
8623      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
8624      * the platform's notion of a network operator being considered roaming or not.
8625      * The change only affects the ICCID that was active when this call was made.
8626      *
8627      * If null is passed as any of the input, the corresponding value is deleted.
8628      *
8629      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
8630      *
8631      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
8632      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
8633      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
8634      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
8635      * @return true if the operation was executed correctly.
8636      *
8637      * @hide
8638      */
8639     @UnsupportedAppUsage
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)8640     public boolean setRoamingOverride(List<String> gsmRoamingList,
8641             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
8642             List<String> cdmaNonRoamingList) {
8643         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
8644                 cdmaRoamingList, cdmaNonRoamingList);
8645     }
8646 
8647     /**
8648      * Override the roaming preference for the current ICCID.
8649      *
8650      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
8651      * the platform's notion of a network operator being considered roaming or not.
8652      * The change only affects the ICCID that was active when this call was made.
8653      *
8654      * If null is passed as any of the input, the corresponding value is deleted.
8655      *
8656      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
8657      *
8658      * @param subId for which the roaming overrides apply.
8659      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
8660      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
8661      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
8662      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
8663      * @return true if the operation was executed correctly.
8664      *
8665      * @hide
8666      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)8667     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
8668             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
8669             List<String> cdmaNonRoamingList) {
8670         try {
8671             ITelephony telephony = getITelephony();
8672             if (telephony != null)
8673                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
8674                         cdmaRoamingList, cdmaNonRoamingList);
8675         } catch (RemoteException ex) {
8676             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
8677         } catch (NullPointerException ex) {
8678             Rlog.e(TAG, "setRoamingOverride NPE", ex);
8679         }
8680         return false;
8681     }
8682 
8683     /**
8684      * Expose the rest of ITelephony to @SystemApi
8685      */
8686 
8687     /** @hide */
8688     @SystemApi
8689     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn()8690     public String getCdmaMdn() {
8691         return getCdmaMdn(getSubId());
8692     }
8693 
8694     /** @hide */
8695     @SystemApi
8696     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn(int subId)8697     public String getCdmaMdn(int subId) {
8698         try {
8699             ITelephony telephony = getITelephony();
8700             if (telephony == null)
8701                 return null;
8702             return telephony.getCdmaMdn(subId);
8703         } catch (RemoteException ex) {
8704             return null;
8705         } catch (NullPointerException ex) {
8706             return null;
8707         }
8708     }
8709 
8710     /** @hide */
8711     @SystemApi
8712     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin()8713     public String getCdmaMin() {
8714         return getCdmaMin(getSubId());
8715     }
8716 
8717     /** @hide */
8718     @SystemApi
8719     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin(int subId)8720     public String getCdmaMin(int subId) {
8721         try {
8722             ITelephony telephony = getITelephony();
8723             if (telephony == null)
8724                 return null;
8725             return telephony.getCdmaMin(subId);
8726         } catch (RemoteException ex) {
8727             return null;
8728         } catch (NullPointerException ex) {
8729             return null;
8730         }
8731     }
8732 
8733     /** @hide */
8734     @SystemApi
8735     @TestApi
8736     @SuppressLint("Doclava125")
checkCarrierPrivilegesForPackage(String pkgName)8737     public int checkCarrierPrivilegesForPackage(String pkgName) {
8738         try {
8739             ITelephony telephony = getITelephony();
8740             if (telephony != null)
8741                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
8742         } catch (RemoteException ex) {
8743             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
8744         } catch (NullPointerException ex) {
8745             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
8746         }
8747         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
8748     }
8749 
8750     /** @hide */
8751     @SystemApi
8752     @SuppressLint("Doclava125")
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)8753     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
8754         try {
8755             ITelephony telephony = getITelephony();
8756             if (telephony != null)
8757                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
8758         } catch (RemoteException ex) {
8759             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
8760         } catch (NullPointerException ex) {
8761             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
8762         }
8763         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
8764     }
8765 
8766     /** @hide */
8767     @SystemApi
8768     @TestApi
getCarrierPackageNamesForIntent(Intent intent)8769     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
8770         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
8771     }
8772 
8773     /** @hide */
8774     @SystemApi
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)8775     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
8776         try {
8777             ITelephony telephony = getITelephony();
8778             if (telephony != null)
8779                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
8780         } catch (RemoteException ex) {
8781             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
8782         } catch (NullPointerException ex) {
8783             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
8784         }
8785         return null;
8786     }
8787 
8788     /** @hide */
getPackagesWithCarrierPrivileges()8789     public List<String> getPackagesWithCarrierPrivileges() {
8790         try {
8791             ITelephony telephony = getITelephony();
8792             if (telephony != null) {
8793                 return telephony.getPackagesWithCarrierPrivileges(getPhoneId());
8794             }
8795         } catch (RemoteException ex) {
8796             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
8797         } catch (NullPointerException ex) {
8798             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
8799         }
8800         return Collections.EMPTY_LIST;
8801     }
8802 
8803     /**
8804      * Get the names of packages with carrier privileges for all the active subscriptions.
8805      *
8806      * @hide
8807      */
8808     @SystemApi
8809     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8810     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()8811     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
8812         try {
8813             ITelephony telephony = getITelephony();
8814             if (telephony != null) {
8815                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
8816             }
8817         } catch (RemoteException ex) {
8818             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
8819                     ex);
8820         } catch (NullPointerException ex) {
8821             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
8822         }
8823         return Collections.EMPTY_LIST;
8824     }
8825 
8826 
8827     /** @hide */
8828     @SystemApi
8829     @SuppressLint("Doclava125")
dial(String number)8830     public void dial(String number) {
8831         try {
8832             ITelephony telephony = getITelephony();
8833             if (telephony != null)
8834                 telephony.dial(number);
8835         } catch (RemoteException e) {
8836             Log.e(TAG, "Error calling ITelephony#dial", e);
8837         }
8838     }
8839 
8840     /**
8841      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
8842      * Bundle extras)} instead.
8843      * @hide
8844      */
8845     @Deprecated
8846     @SystemApi
8847     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
call(String callingPackage, String number)8848     public void call(String callingPackage, String number) {
8849         try {
8850             ITelephony telephony = getITelephony();
8851             if (telephony != null)
8852                 telephony.call(callingPackage, number);
8853         } catch (RemoteException e) {
8854             Log.e(TAG, "Error calling ITelephony#call", e);
8855         }
8856     }
8857 
8858     /**
8859      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
8860      * @hide
8861      * @removed
8862      */
8863     @Deprecated
8864     @SystemApi
8865     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()8866     public boolean endCall() {
8867         return false;
8868     }
8869 
8870     /**
8871      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
8872      * @hide
8873      * @removed
8874      */
8875     @Deprecated
8876     @SystemApi
8877     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()8878     public void answerRingingCall() {
8879         // No-op
8880     }
8881 
8882     /**
8883      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
8884      * @hide
8885      */
8886     @Deprecated
8887     @SystemApi
8888     @SuppressLint("Doclava125")
silenceRinger()8889     public void silenceRinger() {
8890         // No-op
8891     }
8892 
8893     /**
8894      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
8895      * @hide
8896      */
8897     @Deprecated
8898     @SystemApi
8899     @RequiresPermission(anyOf = {
8900             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8901             android.Manifest.permission.READ_PHONE_STATE
8902     })
isOffhook()8903     public boolean isOffhook() {
8904         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8905         return tm.isInCall();
8906     }
8907 
8908     /**
8909      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
8910      * @hide
8911      */
8912     @Deprecated
8913     @SystemApi
8914     @RequiresPermission(anyOf = {
8915             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8916             android.Manifest.permission.READ_PHONE_STATE
8917     })
isRinging()8918     public boolean isRinging() {
8919         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8920         return tm.isRinging();
8921     }
8922 
8923     /**
8924      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
8925      * @hide
8926      */
8927     @Deprecated
8928     @SystemApi
8929     @RequiresPermission(anyOf = {
8930             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8931             android.Manifest.permission.READ_PHONE_STATE
8932     })
isIdle()8933     public boolean isIdle() {
8934         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8935         return !tm.isInCall();
8936     }
8937 
8938     /**
8939      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
8940      * @hide
8941      */
8942     @Deprecated
8943     @SystemApi
8944     @RequiresPermission(anyOf = {
8945             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8946             android.Manifest.permission.READ_PHONE_STATE
8947     })
isRadioOn()8948     public boolean isRadioOn() {
8949         try {
8950             ITelephony telephony = getITelephony();
8951             if (telephony != null)
8952                 return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
8953         } catch (RemoteException e) {
8954             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
8955         }
8956         return false;
8957     }
8958 
8959     /** @hide */
8960     @SystemApi
8961     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPin(String pin)8962     public boolean supplyPin(String pin) {
8963         try {
8964             ITelephony telephony = getITelephony();
8965             if (telephony != null)
8966                 return telephony.supplyPinForSubscriber(getSubId(), pin);
8967         } catch (RemoteException e) {
8968             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
8969         }
8970         return false;
8971     }
8972 
8973     /** @hide */
8974     @SystemApi
8975     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPuk(String puk, String pin)8976     public boolean supplyPuk(String puk, String pin) {
8977         try {
8978             ITelephony telephony = getITelephony();
8979             if (telephony != null)
8980                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
8981         } catch (RemoteException e) {
8982             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
8983         }
8984         return false;
8985     }
8986 
8987     /** @hide */
8988     @SystemApi
8989     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPinReportResult(String pin)8990     public int[] supplyPinReportResult(String pin) {
8991         try {
8992             ITelephony telephony = getITelephony();
8993             if (telephony != null)
8994                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
8995         } catch (RemoteException e) {
8996             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
8997         }
8998         return new int[0];
8999     }
9000 
9001     /** @hide */
9002     @SystemApi
9003     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPukReportResult(String puk, String pin)9004     public int[] supplyPukReportResult(String puk, String pin) {
9005         try {
9006             ITelephony telephony = getITelephony();
9007             if (telephony != null)
9008                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
9009         } catch (RemoteException e) {
9010             Log.e(TAG, "Error calling ITelephony#]", e);
9011         }
9012         return new int[0];
9013     }
9014 
9015     /**
9016      * Used when the user attempts to enter their pin.
9017      *
9018      * @param pin The user entered pin.
9019      * @return The result of the pin.
9020      *
9021      * @hide
9022      */
9023     @Nullable
9024     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPinReportPinResult(@onNull String pin)9025     public PinResult supplyPinReportPinResult(@NonNull String pin) {
9026         try {
9027             ITelephony telephony = getITelephony();
9028             if (telephony != null) {
9029                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
9030                 return new PinResult(result[0], result[1]);
9031             }
9032         } catch (RemoteException e) {
9033             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
9034         }
9035         return null;
9036     }
9037 
9038     /**
9039      * Used when the user attempts to enter the puk or their pin.
9040      *
9041      * @param puk The product unblocking key.
9042      * @param pin The user entered pin.
9043      * @return The result of the pin.
9044      *
9045      * @hide
9046      */
9047     @Nullable
9048     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPukReportPinResult(@onNull String puk, @NonNull String pin)9049     public PinResult supplyPukReportPinResult(@NonNull String puk, @NonNull String pin) {
9050         try {
9051             ITelephony telephony = getITelephony();
9052             if (telephony != null) {
9053                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
9054                 return new PinResult(result[0], result[1]);
9055             }
9056         } catch (RemoteException e) {
9057             Log.e(TAG, "Error calling ITelephony#]", e);
9058         }
9059         return null;
9060     }
9061 
9062     /**
9063      * Used to notify callers of
9064      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
9065      * network either successfully executes a USSD request, or if there was a failure while
9066      * executing the request.
9067      * <p>
9068      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
9069      * USSD request has succeeded.
9070      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
9071      * USSD request has failed.
9072      */
9073     public static abstract class UssdResponseCallback {
9074        /**
9075         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
9076         * response received from the network.  The calling app can choose to either display the
9077         * response to the user or perform some operation based on the response.
9078         * <p>
9079         * USSD responses are unstructured text and their content is determined by the mobile network
9080         * operator.
9081         *
9082         * @param telephonyManager the TelephonyManager the callback is registered to.
9083         * @param request the USSD request sent to the mobile network.
9084         * @param response the response to the USSD request provided by the mobile network.
9085         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)9086        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
9087                                          String request, CharSequence response) {};
9088 
9089        /**
9090         * Called when a USSD request has failed to complete.
9091         *
9092         * @param telephonyManager the TelephonyManager the callback is registered to.
9093         * @param request the USSD request sent to the mobile network.
9094         * @param failureCode failure code indicating why the request failed.  Will be either
9095         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
9096         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
9097         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)9098        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
9099                                                String request, int failureCode) {};
9100     }
9101 
9102     /**
9103      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
9104      * informs the caller of the response via the supplied {@code callback}.
9105      * <p>Carriers define USSD codes which can be sent by the user to request information such as
9106      * the user's current data balance or minutes balance.
9107      * <p>Requires permission:
9108      * {@link android.Manifest.permission#CALL_PHONE}
9109      * @param ussdRequest the USSD command to be executed.
9110      * @param callback called by the framework to inform the caller of the result of executing the
9111      *                 USSD request (see {@link UssdResponseCallback}).
9112      * @param handler the {@link Handler} to run the request on.
9113      */
9114     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)9115     public void sendUssdRequest(String ussdRequest,
9116                                 final UssdResponseCallback callback, Handler handler) {
9117         checkNotNull(callback, "UssdResponseCallback cannot be null.");
9118         final TelephonyManager telephonyManager = this;
9119 
9120         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
9121             @Override
9122             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
9123                 Rlog.d(TAG, "USSD:" + resultCode);
9124                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
9125                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE);
9126 
9127                 if (resultCode == USSD_RETURN_SUCCESS) {
9128                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
9129                             response.getReturnMessage());
9130                 } else {
9131                     callback.onReceiveUssdResponseFailed(telephonyManager,
9132                             response.getUssdRequest(), resultCode);
9133                 }
9134             }
9135         };
9136 
9137         try {
9138             ITelephony telephony = getITelephony();
9139             if (telephony != null) {
9140                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
9141             }
9142         } catch (RemoteException e) {
9143             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
9144             UssdResponse response = new UssdResponse(ussdRequest, "");
9145             Bundle returnData = new Bundle();
9146             returnData.putParcelable(USSD_RESPONSE, response);
9147             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
9148         }
9149     }
9150 
9151     /**
9152      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
9153      * voice and data simultaneously. This can change based on location or network condition.
9154      *
9155      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
9156      */
isConcurrentVoiceAndDataSupported()9157     public boolean isConcurrentVoiceAndDataSupported() {
9158         try {
9159             ITelephony telephony = getITelephony();
9160             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
9161                     getSubId()));
9162         } catch (RemoteException e) {
9163             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
9164         }
9165         return false;
9166     }
9167 
9168     /** @hide */
9169     @SystemApi
9170     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmi(String dialString)9171     public boolean handlePinMmi(String dialString) {
9172         try {
9173             ITelephony telephony = getITelephony();
9174             if (telephony != null)
9175                 return telephony.handlePinMmi(dialString);
9176         } catch (RemoteException e) {
9177             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
9178         }
9179         return false;
9180     }
9181 
9182     /** @hide */
9183     @SystemApi
9184     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmiForSubscriber(int subId, String dialString)9185     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
9186         try {
9187             ITelephony telephony = getITelephony();
9188             if (telephony != null)
9189                 return telephony.handlePinMmiForSubscriber(subId, dialString);
9190         } catch (RemoteException e) {
9191             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
9192         }
9193         return false;
9194     }
9195 
9196     /** @hide */
9197     @SystemApi
9198     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
toggleRadioOnOff()9199     public void toggleRadioOnOff() {
9200         try {
9201             ITelephony telephony = getITelephony();
9202             if (telephony != null)
9203                 telephony.toggleRadioOnOff();
9204         } catch (RemoteException e) {
9205             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
9206         }
9207     }
9208 
9209     /** @hide */
9210     @SystemApi
9211     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadio(boolean turnOn)9212     public boolean setRadio(boolean turnOn) {
9213         try {
9214             ITelephony telephony = getITelephony();
9215             if (telephony != null)
9216                 return telephony.setRadio(turnOn);
9217         } catch (RemoteException e) {
9218             Log.e(TAG, "Error calling ITelephony#setRadio", e);
9219         }
9220         return false;
9221     }
9222 
9223     /** @hide */
9224     @SystemApi
9225     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioPower(boolean turnOn)9226     public boolean setRadioPower(boolean turnOn) {
9227         try {
9228             ITelephony telephony = getITelephony();
9229             if (telephony != null)
9230                 return telephony.setRadioPower(turnOn);
9231         } catch (RemoteException e) {
9232             Log.e(TAG, "Error calling ITelephony#setRadioPower", e);
9233         }
9234         return false;
9235     }
9236 
9237     /**
9238      * Shut down all the live radios over all the slot indexes.
9239      *
9240      * <p>To know when the radio has completed powering off, use
9241      * {@link PhoneStateListener#LISTEN_SERVICE_STATE LISTEN_SERVICE_STATE}.
9242      *
9243      * @hide
9244      */
9245     @SystemApi
9246     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
shutdownAllRadios()9247     public void shutdownAllRadios() {
9248         try {
9249             ITelephony telephony = getITelephony();
9250             if (telephony != null) {
9251                 telephony.shutdownMobileRadios();
9252             }
9253         } catch (RemoteException e) {
9254             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
9255             e.rethrowAsRuntimeException();
9256         }
9257     }
9258 
9259     /**
9260      * Check if any radio is on over all the slot indexes.
9261      *
9262      * @return {@code true} if any radio is on over any slot index.
9263      * @hide
9264      */
9265     @SystemApi
9266     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isAnyRadioPoweredOn()9267     public boolean isAnyRadioPoweredOn() {
9268         try {
9269             ITelephony telephony = getITelephony();
9270             if (telephony != null) {
9271                 return telephony.needMobileRadioShutdown();
9272             }
9273         } catch (RemoteException e) {
9274             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
9275             e.rethrowAsRuntimeException();
9276         }
9277         return false;
9278     }
9279 
9280     /**
9281      * Radio explicitly powered off (e.g, airplane mode).
9282      * @hide
9283      */
9284     @SystemApi
9285     public static final int RADIO_POWER_OFF = 0;
9286 
9287     /**
9288      * Radio power is on.
9289      * @hide
9290      */
9291     @SystemApi
9292     public static final int RADIO_POWER_ON = 1;
9293 
9294     /**
9295      * Radio power unavailable (eg, modem resetting or not booted).
9296      * @hide
9297      */
9298     @SystemApi
9299     public static final int RADIO_POWER_UNAVAILABLE = 2;
9300 
9301     /**
9302      * @return current modem radio state.
9303      *
9304      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
9305      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
9306      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9307      *
9308      * @hide
9309      */
9310     @SystemApi
9311     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9312             android.Manifest.permission.READ_PHONE_STATE})
getRadioPowerState()9313     public @RadioPowerState int getRadioPowerState() {
9314         try {
9315             ITelephony telephony = getITelephony();
9316             if (telephony != null) {
9317                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
9318                         mContext.getAttributionTag());
9319             }
9320         } catch (RemoteException ex) {
9321             // This could happen if binder process crashes.
9322         }
9323         return RADIO_POWER_UNAVAILABLE;
9324     }
9325 
9326     /** @hide */
9327     @SystemApi
9328     @SuppressLint("Doclava125")
updateServiceLocation()9329     public void updateServiceLocation() {
9330         try {
9331             ITelephony telephony = getITelephony();
9332             if (telephony != null)
9333                 telephony.updateServiceLocation();
9334         } catch (RemoteException e) {
9335             Log.e(TAG, "Error calling ITelephony#updateServiceLocation", e);
9336         }
9337     }
9338 
9339     /** @hide */
9340     @SystemApi
9341     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableDataConnectivity()9342     public boolean enableDataConnectivity() {
9343         try {
9344             ITelephony telephony = getITelephony();
9345             if (telephony != null)
9346                 return telephony.enableDataConnectivity();
9347         } catch (RemoteException e) {
9348             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
9349         }
9350         return false;
9351     }
9352 
9353     /** @hide */
9354     @SystemApi
9355     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
disableDataConnectivity()9356     public boolean disableDataConnectivity() {
9357         try {
9358             ITelephony telephony = getITelephony();
9359             if (telephony != null)
9360                 return telephony.disableDataConnectivity();
9361         } catch (RemoteException e) {
9362             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
9363         }
9364         return false;
9365     }
9366 
9367     /** @hide */
9368     @SystemApi
isDataConnectivityPossible()9369     public boolean isDataConnectivityPossible() {
9370         try {
9371             ITelephony telephony = getITelephony();
9372             if (telephony != null)
9373                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
9374                         .getActiveDataSubscriptionId()));
9375         } catch (RemoteException e) {
9376             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
9377         }
9378         return false;
9379     }
9380 
9381     /** @hide */
9382     @SystemApi
needsOtaServiceProvisioning()9383     public boolean needsOtaServiceProvisioning() {
9384         try {
9385             ITelephony telephony = getITelephony();
9386             if (telephony != null)
9387                 return telephony.needsOtaServiceProvisioning();
9388         } catch (RemoteException e) {
9389             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
9390         }
9391         return false;
9392     }
9393 
9394     /**
9395      * Turns mobile data on or off.
9396      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9397      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9398      *
9399      * <p>Requires Permission:
9400      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9401      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9402      *
9403      * @param enable Whether to enable mobile data.
9404      *
9405      */
9406     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9407     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(boolean enable)9408     public void setDataEnabled(boolean enable) {
9409         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
9410     }
9411 
9412     /**
9413      * @hide
9414      * @deprecated use {@link #setDataEnabled(boolean)} instead.
9415     */
9416     @SystemApi
9417     @Deprecated
9418     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(int subId, boolean enable)9419     public void setDataEnabled(int subId, boolean enable) {
9420         try {
9421             Log.d(TAG, "setDataEnabled: enabled=" + enable);
9422             ITelephony telephony = getITelephony();
9423             if (telephony != null)
9424                 telephony.setUserDataEnabled(subId, enable);
9425         } catch (RemoteException e) {
9426             Log.e(TAG, "Error calling ITelephony#setUserDataEnabled", e);
9427         }
9428     }
9429 
9430     /**
9431      * @deprecated use {@link #isDataEnabled()} instead.
9432      * @hide
9433      */
9434     @SystemApi
9435     @Deprecated
getDataEnabled()9436     public boolean getDataEnabled() {
9437         return isDataEnabled();
9438     }
9439 
9440     /**
9441      * Returns whether mobile data is enabled or not per user setting. There are other factors
9442      * that could disable mobile data, but they are not considered here.
9443      *
9444      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9445      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9446      *
9447      * <p>Requires one of the following permissions:
9448      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9449      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or that the calling app has carrier
9450      * privileges (see {@link #hasCarrierPrivileges}).
9451      *
9452      * <p>Note that this does not take into account any data restrictions that may be present on the
9453      * calling app. Such restrictions may be inspected with
9454      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
9455      *
9456      * @return true if mobile data is enabled.
9457      */
9458     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9459             android.Manifest.permission.MODIFY_PHONE_STATE})
isDataEnabled()9460     public boolean isDataEnabled() {
9461         return getDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
9462     }
9463 
9464     /**
9465      * Returns whether mobile data roaming is enabled on the subscription.
9466      *
9467      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9468      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9469      *
9470      * <p>Requires one of the following permissions:
9471      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9472      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling app
9473      * has carrier privileges (see {@link #hasCarrierPrivileges}).
9474      *
9475      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
9476      * {@code false}.
9477      */
9478     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9479             android.Manifest.permission.READ_PHONE_STATE})
isDataRoamingEnabled()9480     public boolean isDataRoamingEnabled() {
9481         boolean isDataRoamingEnabled = false;
9482         try {
9483             ITelephony telephony = getITelephony();
9484             if (telephony != null) {
9485                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
9486                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
9487             }
9488         } catch (RemoteException e) {
9489             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
9490         }
9491         return isDataRoamingEnabled;
9492     }
9493 
9494     /**
9495      * Gets the roaming mode for CDMA phone.
9496      *
9497      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9498      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9499      *
9500      * @return one of {@link #CDMA_ROAMING_MODE_RADIO_DEFAULT}, {@link #CDMA_ROAMING_MODE_HOME},
9501      * {@link #CDMA_ROAMING_MODE_AFFILIATED}, {@link #CDMA_ROAMING_MODE_ANY}.
9502      *
9503      * @hide
9504      */
9505     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaRoamingMode()9506     public @CdmaRoamingMode int getCdmaRoamingMode() {
9507         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
9508         try {
9509             ITelephony telephony = getITelephony();
9510             if (telephony != null) {
9511                 mode = telephony.getCdmaRoamingMode(getSubId());
9512             }
9513         } catch (RemoteException ex) {
9514             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
9515         }
9516         return mode;
9517     }
9518 
9519     /**
9520      * Sets the roaming mode for CDMA phone to the given mode {@code mode}.
9521      *
9522      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9523      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9524      *
9525      * @param mode should be one of {@link #CDMA_ROAMING_MODE_RADIO_DEFAULT},
9526      * {@link #CDMA_ROAMING_MODE_HOME}, {@link #CDMA_ROAMING_MODE_AFFILIATED},
9527      * {@link #CDMA_ROAMING_MODE_ANY}.
9528      *
9529      * @return {@code true} if successed.
9530      *
9531      * @hide
9532      */
9533     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaRoamingMode(@dmaRoamingMode int mode)9534     public boolean setCdmaRoamingMode(@CdmaRoamingMode int mode) {
9535         try {
9536             ITelephony telephony = getITelephony();
9537             if (telephony != null) {
9538                 return telephony.setCdmaRoamingMode(getSubId(), mode);
9539             }
9540         } catch (RemoteException ex) {
9541             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
9542         }
9543         return false;
9544     }
9545 
9546     /** @hide */
9547     @IntDef(flag = true, prefix = { "CDMA_SUBSCRIPTION_" }, value = {
9548             CDMA_SUBSCRIPTION_UNKNOWN,
9549             CDMA_SUBSCRIPTION_RUIM_SIM,
9550             CDMA_SUBSCRIPTION_NV
9551     })
9552     @Retention(RetentionPolicy.SOURCE)
9553     public @interface CdmaSubscription{}
9554 
9555     /** Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
9556      * @hide
9557      */
9558     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
9559 
9560     /** Used for CDMA subscription mode: RUIM/SIM (default)
9561      * @hide
9562      */
9563     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
9564 
9565     /** Used for CDMA subscription mode: NV -> non-volatile memory
9566      * @hide
9567      */
9568     public static final int CDMA_SUBSCRIPTION_NV       = 1;
9569 
9570     /** @hide */
9571     public static final int PREFERRED_CDMA_SUBSCRIPTION = CDMA_SUBSCRIPTION_RUIM_SIM;
9572 
9573     /**
9574      * Sets the subscription mode for CDMA phone to the given mode {@code mode}.
9575      *
9576      * @param mode CDMA subscription mode
9577      *
9578      * @return {@code true} if successed.
9579      *
9580      * @see #CDMA_SUBSCRIPTION_UNKNOWN
9581      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
9582      * @see #CDMA_SUBSCRIPTION_NV
9583      *
9584      * @hide
9585      */
9586     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaSubscriptionMode(@dmaSubscription int mode)9587     public boolean setCdmaSubscriptionMode(@CdmaSubscription int mode) {
9588         try {
9589             ITelephony telephony = getITelephony();
9590             if (telephony != null) {
9591                 return telephony.setCdmaSubscriptionMode(getSubId(), mode);
9592             }
9593         } catch (RemoteException ex) {
9594             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
9595         }
9596         return false;
9597     }
9598 
9599     /**
9600      * Enables/Disables the data roaming on the subscription.
9601      *
9602      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9603      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9604      *
9605      * <p> Requires permission:
9606      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
9607      * privileges (see {@link #hasCarrierPrivileges}).
9608      *
9609      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
9610      *
9611      * @hide
9612      */
9613     @SystemApi
9614     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataRoamingEnabled(boolean isEnabled)9615     public void setDataRoamingEnabled(boolean isEnabled) {
9616         try {
9617             ITelephony telephony = getITelephony();
9618             if (telephony != null) {
9619                 telephony.setDataRoamingEnabled(
9620                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
9621             }
9622         } catch (RemoteException e) {
9623             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
9624         }
9625     }
9626 
9627     /**
9628      * @deprecated use {@link #isDataEnabled()} instead.
9629      * @hide
9630      */
9631     @Deprecated
9632     @SystemApi
getDataEnabled(int subId)9633     public boolean getDataEnabled(int subId) {
9634         boolean retVal = false;
9635         try {
9636             ITelephony telephony = getITelephony();
9637             if (telephony != null)
9638                 retVal = telephony.isUserDataEnabled(subId);
9639         } catch (RemoteException | NullPointerException e) {
9640             Log.e(TAG, "Error calling ITelephony#isUserDataEnabled", e);
9641         }
9642         return retVal;
9643     }
9644 
9645     /**
9646      * Returns the result and response from RIL for oem request
9647      *
9648      * @param oemReq the data is sent to ril.
9649      * @param oemResp the respose data from RIL.
9650      * @return negative value request was not handled or get error
9651      *         0 request was handled succesfully, but no response data
9652      *         positive value success, data length of response
9653      * @hide
9654      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
9655      */
9656     @Deprecated
invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp)9657     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
9658         try {
9659             ITelephony telephony = getITelephony();
9660             if (telephony != null)
9661                 return telephony.invokeOemRilRequestRaw(oemReq, oemResp);
9662         } catch (RemoteException ex) {
9663         } catch (NullPointerException ex) {
9664         }
9665         return -1;
9666     }
9667 
9668     /**
9669      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
9670      * instead.
9671      * @hide
9672      */
9673     @Deprecated
9674     @SystemApi
9675     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableVideoCalling(boolean enable)9676     public void enableVideoCalling(boolean enable) {
9677         try {
9678             ITelephony telephony = getITelephony();
9679             if (telephony != null)
9680                 telephony.enableVideoCalling(enable);
9681         } catch (RemoteException e) {
9682             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
9683         }
9684     }
9685 
9686     /**
9687      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
9688      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
9689      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
9690      * determine if video calling is capable.
9691      * @hide
9692      */
9693     @Deprecated
9694     @SystemApi
9695     @RequiresPermission(anyOf = {
9696             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9697             android.Manifest.permission.READ_PHONE_STATE
9698     })
isVideoCallingEnabled()9699     public boolean isVideoCallingEnabled() {
9700         try {
9701             ITelephony telephony = getITelephony();
9702             if (telephony != null)
9703                 return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
9704         } catch (RemoteException e) {
9705             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
9706         }
9707         return false;
9708     }
9709 
9710     /**
9711      * Whether the device supports configuring the DTMF tone length.
9712      *
9713      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
9714      */
canChangeDtmfToneLength()9715     public boolean canChangeDtmfToneLength() {
9716         try {
9717             ITelephony telephony = getITelephony();
9718             if (telephony != null) {
9719                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
9720                         getAttributionTag());
9721             }
9722         } catch (RemoteException e) {
9723             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
9724         } catch (SecurityException e) {
9725             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
9726         }
9727         return false;
9728     }
9729 
9730     /**
9731      * Whether the device is a world phone.
9732      *
9733      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
9734      */
isWorldPhone()9735     public boolean isWorldPhone() {
9736         try {
9737             ITelephony telephony = getITelephony();
9738             if (telephony != null) {
9739                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
9740             }
9741         } catch (RemoteException e) {
9742             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
9743         } catch (SecurityException e) {
9744             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
9745         }
9746         return false;
9747     }
9748 
9749     /**
9750      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
9751      * Whether the phone supports TTY mode.
9752      *
9753      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
9754      *
9755      */
9756     @Deprecated
isTtyModeSupported()9757     public boolean isTtyModeSupported() {
9758         try {
9759             TelecomManager telecomManager = null;
9760             if (mContext != null) {
9761                 telecomManager = mContext.getSystemService(TelecomManager.class);
9762             }
9763             if (telecomManager != null) {
9764                 return telecomManager.isTtySupported();
9765             }
9766         } catch (SecurityException e) {
9767             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
9768         }
9769         return false;
9770     }
9771 
9772     /**
9773      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
9774      * support for the feature and device firmware support.
9775      *
9776      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
9777      */
isRttSupported()9778     public boolean isRttSupported() {
9779         try {
9780             ITelephony telephony = getITelephony();
9781             if (telephony != null) {
9782                 return telephony.isRttSupported(mSubId);
9783             }
9784         } catch (RemoteException e) {
9785             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
9786         } catch (SecurityException e) {
9787             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
9788         }
9789         return false;
9790     }
9791     /**
9792      * Whether the phone supports hearing aid compatibility.
9793      *
9794      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
9795      * otherwise.
9796      */
isHearingAidCompatibilitySupported()9797     public boolean isHearingAidCompatibilitySupported() {
9798         try {
9799             ITelephony telephony = getITelephony();
9800             if (telephony != null) {
9801                 return telephony.isHearingAidCompatibilitySupported();
9802             }
9803         } catch (RemoteException e) {
9804             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
9805         } catch (SecurityException e) {
9806             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
9807         }
9808         return false;
9809     }
9810 
9811     /**
9812      * Returns the IMS Registration Status for a particular Subscription ID.
9813      *
9814      * @param subId Subscription ID
9815      * @return true if IMS status is registered, false if the IMS status is not registered or a
9816      * RemoteException occurred.
9817      * Use {@link ImsMmTelManager.RegistrationCallback} instead.
9818      * @hide
9819      */
isImsRegistered(int subId)9820     public boolean isImsRegistered(int subId) {
9821         try {
9822             return getITelephony().isImsRegistered(subId);
9823         } catch (RemoteException | NullPointerException ex) {
9824             return false;
9825         }
9826     }
9827 
9828     /**
9829      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
9830      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
9831      * invalid subscription ID is used during creation, will the default subscription ID will be
9832      * used.
9833      *
9834      * @return true if IMS status is registered, false if the IMS status is not registered or a
9835      * RemoteException occurred.
9836      * @see SubscriptionManager#getDefaultSubscriptionId()
9837      * @hide
9838      */
9839     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()9840     public boolean isImsRegistered() {
9841        try {
9842            return getITelephony().isImsRegistered(getSubId());
9843        } catch (RemoteException | NullPointerException ex) {
9844            return false;
9845        }
9846     }
9847 
9848     /**
9849      * The current status of Voice over LTE for the subscription associated with this instance when
9850      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
9851      * used during creation, the default subscription ID will be used.
9852      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
9853      * @see SubscriptionManager#getDefaultSubscriptionId()
9854      * <p>
9855      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9856      * @hide
9857      */
9858     @UnsupportedAppUsage
isVolteAvailable()9859     public boolean isVolteAvailable() {
9860         try {
9861             return getITelephony().isAvailable(getSubId(),
9862                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
9863                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
9864         } catch (RemoteException | NullPointerException ex) {
9865             return false;
9866         }
9867     }
9868 
9869     /**
9870      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
9871      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
9872      * used during creation, the default subscription ID will be used. To query the
9873      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
9874      * @return true if VT is available, or false if it is unavailable or unknown.
9875      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9876      * @hide
9877      */
9878     @UnsupportedAppUsage
isVideoTelephonyAvailable()9879     public boolean isVideoTelephonyAvailable() {
9880         try {
9881             return getITelephony().isVideoTelephonyAvailable(getSubId());
9882         } catch (RemoteException | NullPointerException ex) {
9883             return false;
9884         }
9885     }
9886 
9887     /**
9888      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
9889      * @param subId the subscription ID.
9890      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
9891      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9892      * @hide
9893      */
9894     @UnsupportedAppUsage
isWifiCallingAvailable()9895     public boolean isWifiCallingAvailable() {
9896        try {
9897            return getITelephony().isWifiCallingAvailable(getSubId());
9898        } catch (RemoteException | NullPointerException ex) {
9899            return false;
9900        }
9901    }
9902 
9903     /**
9904      * The technology that IMS is registered for for the MMTEL feature.
9905      * @param subId subscription ID to get IMS registration technology for.
9906      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
9907      * Valid return results are:
9908      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
9909      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
9910      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
9911      *  result is unavailable.
9912      *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
9913      *  @hide
9914      */
getImsRegTechnologyForMmTel()9915     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
9916         try {
9917             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
9918         } catch (RemoteException ex) {
9919             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
9920         }
9921     }
9922 
9923    /**
9924     * Set TelephonyProperties.icc_operator_numeric for the default phone.
9925     *
9926     * @hide
9927     */
setSimOperatorNumeric(String numeric)9928     public void setSimOperatorNumeric(String numeric) {
9929         int phoneId = getPhoneId();
9930         setSimOperatorNumericForPhone(phoneId, numeric);
9931     }
9932 
9933    /**
9934     * Set TelephonyProperties.icc_operator_numeric for the given phone.
9935     *
9936     * @hide
9937     */
9938     @UnsupportedAppUsage
setSimOperatorNumericForPhone(int phoneId, String numeric)9939     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
9940         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9941             List<String> newList = updateTelephonyProperty(
9942                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
9943             TelephonyProperties.icc_operator_numeric(newList);
9944         }
9945     }
9946 
9947     /**
9948      * Set TelephonyProperties.icc_operator_alpha for the default phone.
9949      *
9950      * @hide
9951      */
setSimOperatorName(String name)9952     public void setSimOperatorName(String name) {
9953         int phoneId = getPhoneId();
9954         setSimOperatorNameForPhone(phoneId, name);
9955     }
9956 
9957     /**
9958      * Set TelephonyProperties.icc_operator_alpha for the given phone.
9959      *
9960      * @hide
9961      */
9962     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)9963     public void setSimOperatorNameForPhone(int phoneId, String name) {
9964         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9965             List<String> newList = updateTelephonyProperty(
9966                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
9967             TelephonyProperties.icc_operator_alpha(newList);
9968         }
9969     }
9970 
9971    /**
9972     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
9973     *
9974     * @hide
9975     */
setSimCountryIso(String iso)9976     public void setSimCountryIso(String iso) {
9977         int phoneId = getPhoneId();
9978         setSimCountryIsoForPhone(phoneId, iso);
9979     }
9980 
9981    /**
9982     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
9983     *
9984     * @hide
9985     */
9986     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)9987     public void setSimCountryIsoForPhone(int phoneId, String iso) {
9988         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9989             List<String> newList = updateTelephonyProperty(
9990                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
9991             TelephonyProperties.icc_operator_iso_country(newList);
9992         }
9993     }
9994 
9995     /**
9996      * Set TelephonyProperties.sim_state for the default phone.
9997      *
9998      * @hide
9999      */
setSimState(String state)10000     public void setSimState(String state) {
10001         int phoneId = getPhoneId();
10002         setSimStateForPhone(phoneId, state);
10003     }
10004 
10005     /**
10006      * Set TelephonyProperties.sim_state for the given phone.
10007      *
10008      * @hide
10009      */
10010     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)10011     public void setSimStateForPhone(int phoneId, String state) {
10012         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10013             List<String> newList = updateTelephonyProperty(
10014                     TelephonyProperties.sim_state(), phoneId, state);
10015             TelephonyProperties.sim_state(newList);
10016         }
10017     }
10018 
10019     /**
10020      * Powers down the SIM. SIM must be up prior.
10021      * @hide
10022      */
10023     public static final int CARD_POWER_DOWN = 0;
10024 
10025     /**
10026      * Powers up the SIM normally. SIM must be down prior.
10027      * @hide
10028      */
10029     public static final int CARD_POWER_UP = 1;
10030 
10031     /**
10032      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
10033      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
10034      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
10035      * and the SIM card is controlled completely by Telephony sending APDUs
10036      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
10037      * number of card apps will be 0.
10038      * No new error code is generated. Emergency calls are supported in the
10039      * same way as if the SIM card is absent.
10040      * The PASS_THROUGH mode is valid only for the specific card session where it
10041      * is activated, and normal behavior occurs at the next SIM initialization,
10042      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
10043      * is NOT persistent across boots. On reboot, SIM will power up normally.
10044      * @hide
10045      */
10046     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
10047 
10048     /**
10049      * Set SIM card power state.
10050      *
10051      * @param state  State of SIM (power down, power up, pass through)
10052      * @see #CARD_POWER_DOWN
10053      * @see #CARD_POWER_UP
10054      * @see #CARD_POWER_UP_PASS_THROUGH
10055      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
10056      * broadcasts to determine success or failure and timeout if needed.
10057      *
10058      * <p>Requires Permission:
10059      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10060      *
10061      * {@hide}
10062      **/
10063     @SystemApi
10064     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerState(int state)10065     public void setSimPowerState(int state) {
10066         setSimPowerStateForSlot(getSlotIndex(), state);
10067     }
10068 
10069     /**
10070      * Set SIM card power state.
10071      *
10072      * @param slotIndex SIM slot id
10073      * @param state  State of SIM (power down, power up, pass through)
10074      * @see #CARD_POWER_DOWN
10075      * @see #CARD_POWER_UP
10076      * @see #CARD_POWER_UP_PASS_THROUGH
10077      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
10078      * broadcasts to determine success or failure and timeout if needed.
10079      *
10080      * <p>Requires Permission:
10081      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10082      *
10083      * {@hide}
10084      **/
10085     @SystemApi
10086     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerStateForSlot(int slotIndex, int state)10087     public void setSimPowerStateForSlot(int slotIndex, int state) {
10088         try {
10089             ITelephony telephony = getITelephony();
10090             if (telephony != null) {
10091                 telephony.setSimPowerStateForSlot(slotIndex, state);
10092             }
10093         } catch (RemoteException e) {
10094             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
10095         } catch (SecurityException e) {
10096             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
10097         }
10098     }
10099 
10100     /**
10101      * Set baseband version for the default phone.
10102      *
10103      * @param version baseband version
10104      * @hide
10105      */
setBasebandVersion(String version)10106     public void setBasebandVersion(String version) {
10107         int phoneId = getPhoneId();
10108         setBasebandVersionForPhone(phoneId, version);
10109     }
10110 
10111     /**
10112      * Set baseband version by phone id.
10113      *
10114      * @param phoneId for which baseband version is set
10115      * @param version baseband version
10116      * @hide
10117      */
10118     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)10119     public void setBasebandVersionForPhone(int phoneId, String version) {
10120         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10121             List<String> newList = updateTelephonyProperty(
10122                     TelephonyProperties.baseband_version(), phoneId, version);
10123             TelephonyProperties.baseband_version(newList);
10124         }
10125     }
10126 
10127     /**
10128      * Get baseband version for the default phone.
10129      *
10130      * @return baseband version.
10131      * @hide
10132      */
getBasebandVersion()10133     public String getBasebandVersion() {
10134         int phoneId = getPhoneId();
10135         return getBasebandVersionForPhone(phoneId);
10136     }
10137 
10138     /**
10139      * Get baseband version by phone id.
10140      *
10141      * @return baseband version.
10142      * @hide
10143      */
getBasebandVersionForPhone(int phoneId)10144     public String getBasebandVersionForPhone(int phoneId) {
10145         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
10146     }
10147 
10148     /**
10149      * Set phone type for the default phone.
10150      *
10151      * @param type phone type
10152      *
10153      * @hide
10154      */
setPhoneType(int type)10155     public void setPhoneType(int type) {
10156         int phoneId = getPhoneId();
10157         setPhoneType(phoneId, type);
10158     }
10159 
10160     /**
10161      * Set phone type by phone id.
10162      *
10163      * @param phoneId for which phone type is set
10164      * @param type phone type
10165      *
10166      * @hide
10167      */
10168     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)10169     public void setPhoneType(int phoneId, int type) {
10170         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10171             List<Integer> newList = updateTelephonyProperty(
10172                     TelephonyProperties.current_active_phone(), phoneId, type);
10173             TelephonyProperties.current_active_phone(newList);
10174         }
10175     }
10176 
10177     /**
10178      * Get OTASP number schema for the default phone.
10179      *
10180      * @param defaultValue default value
10181      * @return OTA SP number schema
10182      *
10183      * @hide
10184      */
getOtaSpNumberSchema(String defaultValue)10185     public String getOtaSpNumberSchema(String defaultValue) {
10186         int phoneId = getPhoneId();
10187         return getOtaSpNumberSchemaForPhone(phoneId, defaultValue);
10188     }
10189 
10190     /**
10191      * Get OTASP number schema by phone id.
10192      *
10193      * @param phoneId for which OTA SP number schema is get
10194      * @param defaultValue default value
10195      * @return OTA SP number schema
10196      *
10197      * @hide
10198      */
10199     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)10200     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
10201         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10202             return getTelephonyProperty(
10203                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
10204         }
10205 
10206         return defaultValue;
10207     }
10208 
10209     /**
10210      * Get SMS receive capable from system property for the default phone.
10211      *
10212      * @param defaultValue default value
10213      * @return SMS receive capable
10214      *
10215      * @hide
10216      */
getSmsReceiveCapable(boolean defaultValue)10217     public boolean getSmsReceiveCapable(boolean defaultValue) {
10218         int phoneId = getPhoneId();
10219         return getSmsReceiveCapableForPhone(phoneId, defaultValue);
10220     }
10221 
10222     /**
10223      * Get SMS receive capable from system property by phone id.
10224      *
10225      * @param phoneId for which SMS receive capable is get
10226      * @param defaultValue default value
10227      * @return SMS receive capable
10228      *
10229      * @hide
10230      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)10231     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
10232         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10233             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
10234         }
10235 
10236         return defaultValue;
10237     }
10238 
10239     /**
10240      * Get SMS send capable from system property for the default phone.
10241      *
10242      * @param defaultValue default value
10243      * @return SMS send capable
10244      *
10245      * @hide
10246      */
getSmsSendCapable(boolean defaultValue)10247     public boolean getSmsSendCapable(boolean defaultValue) {
10248         int phoneId = getPhoneId();
10249         return getSmsSendCapableForPhone(phoneId, defaultValue);
10250     }
10251 
10252     /**
10253      * Get SMS send capable from system property by phone id.
10254      *
10255      * @param phoneId for which SMS send capable is get
10256      * @param defaultValue default value
10257      * @return SMS send capable
10258      *
10259      * @hide
10260      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)10261     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
10262         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10263             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
10264         }
10265 
10266         return defaultValue;
10267     }
10268 
10269     /**
10270      * Gets the default Respond Via Message application, updating the cache if there is no
10271      * respond-via-message application currently configured.
10272      * @return component name of the app and class to direct Respond Via Message intent to, or
10273      * {@code null} if the functionality is not supported.
10274      * @hide
10275      */
10276     @SystemApi
10277     @TestApi
10278     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
getAndUpdateDefaultRespondViaMessageApplication()10279     public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
10280         return SmsApplication.getDefaultRespondViaMessageApplication(mContext, true);
10281     }
10282 
10283     /**
10284      * Gets the default Respond Via Message application.
10285      * @return component name of the app and class to direct Respond Via Message intent to, or
10286      * {@code null} if the functionality is not supported.
10287      * @hide
10288      */
10289     @SystemApi
10290     @TestApi
10291     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
getDefaultRespondViaMessageApplication()10292     public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
10293         return SmsApplication.getDefaultRespondViaMessageApplication(mContext, false);
10294     }
10295 
10296     /**
10297      * Set the alphabetic name of current registered operator.
10298      * @param name the alphabetic name of current registered operator.
10299      * @hide
10300      */
setNetworkOperatorName(String name)10301     public void setNetworkOperatorName(String name) {
10302         int phoneId = getPhoneId();
10303         setNetworkOperatorNameForPhone(phoneId, name);
10304     }
10305 
10306     /**
10307      * Set the alphabetic name of current registered operator.
10308      * @param phoneId which phone you want to set
10309      * @param name the alphabetic name of current registered operator.
10310      * @hide
10311      */
10312     @UnsupportedAppUsage
setNetworkOperatorNameForPhone(int phoneId, String name)10313     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
10314         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10315             List<String> newList = updateTelephonyProperty(
10316                     TelephonyProperties.operator_alpha(), phoneId, name);
10317             TelephonyProperties.operator_alpha(newList);
10318         }
10319     }
10320 
10321     /**
10322      * Set the numeric name (MCC+MNC) of current registered operator.
10323      * @param operator the numeric name (MCC+MNC) of current registered operator
10324      * @hide
10325      */
setNetworkOperatorNumeric(String numeric)10326     public void setNetworkOperatorNumeric(String numeric) {
10327         int phoneId = getPhoneId();
10328         setNetworkOperatorNumericForPhone(phoneId, numeric);
10329     }
10330 
10331     /**
10332      * Set the numeric name (MCC+MNC) of current registered operator.
10333      * @param phoneId for which phone type is set
10334      * @param operator the numeric name (MCC+MNC) of current registered operator
10335      * @hide
10336      */
10337     @UnsupportedAppUsage
setNetworkOperatorNumericForPhone(int phoneId, String numeric)10338     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
10339         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10340             List<String> newList = updateTelephonyProperty(
10341                     TelephonyProperties.operator_numeric(), phoneId, numeric);
10342             TelephonyProperties.operator_numeric(newList);
10343         }
10344     }
10345 
10346     /**
10347      * Set roaming state of the current network, for GSM purposes.
10348      * @param isRoaming is network in romaing state or not
10349      * @hide
10350      */
setNetworkRoaming(boolean isRoaming)10351     public void setNetworkRoaming(boolean isRoaming) {
10352         int phoneId = getPhoneId();
10353         setNetworkRoamingForPhone(phoneId, isRoaming);
10354     }
10355 
10356     /**
10357      * Set roaming state of the current network, for GSM purposes.
10358      * @param phoneId which phone you want to set
10359      * @param isRoaming is network in romaing state or not
10360      * @hide
10361      */
10362     @UnsupportedAppUsage
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)10363     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
10364         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10365             List<Boolean> newList = updateTelephonyProperty(
10366                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
10367             TelephonyProperties.operator_is_roaming(newList);
10368         }
10369     }
10370 
10371     /**
10372      * Set the network type currently in use on the device for data transmission.
10373      *
10374      * If this object has been created with {@link #createForSubscriptionId}, applies to the
10375      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
10376      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10377      * @param type the network type currently in use on the device for data transmission
10378      * @hide
10379      */
setDataNetworkType(int type)10380     public void setDataNetworkType(int type) {
10381         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
10382         setDataNetworkTypeForPhone(phoneId, type);
10383     }
10384 
10385     /**
10386      * Set the network type currently in use on the device for data transmission.
10387      * @param phoneId which phone you want to set
10388      * @param type the network type currently in use on the device for data transmission
10389      * @hide
10390      */
10391     @UnsupportedAppUsage
setDataNetworkTypeForPhone(int phoneId, int type)10392     public void setDataNetworkTypeForPhone(int phoneId, int type) {
10393         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10394             List<String> newList = updateTelephonyProperty(
10395                     TelephonyProperties.data_network_type(), phoneId,
10396                     ServiceState.rilRadioTechnologyToString(type));
10397             TelephonyProperties.data_network_type(newList);
10398         }
10399     }
10400 
10401     /**
10402      * Returns the subscription ID for the given phone account.
10403      * @hide
10404      */
10405     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)10406     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
10407         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
10408         try {
10409             ITelephony service = getITelephony();
10410             if (service != null) {
10411                 retval = service.getSubIdForPhoneAccount(phoneAccount);
10412             }
10413         } catch (RemoteException e) {
10414         }
10415 
10416         return retval;
10417     }
10418 
10419     /**
10420      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
10421      *
10422      * @param subscriptionId The subscription Id to check.
10423      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
10424      * there is no associated {@link PhoneAccountHandle}.
10425      * @hide
10426      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)10427     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
10428         PhoneAccountHandle returnValue = null;
10429         try {
10430             ITelephony service = getITelephony();
10431             if (service != null) {
10432                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
10433             }
10434         } catch (RemoteException e) {
10435         }
10436 
10437         return returnValue;
10438     }
10439 
10440     /**
10441      * Returns the subscription ID for the given phone account handle.
10442      *
10443      * @param phoneAccountHandle the phone account handle for outgoing calls
10444      * @return subscription ID for the given phone account handle; or
10445      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
10446      *         if not available; or throw a SecurityException if the caller doesn't have the
10447      *         permission.
10448      */
10449     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)10450     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
10451         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
10452         try {
10453             ITelephony service = getITelephony();
10454             if (service != null) {
10455                 retval = service.getSubIdForPhoneAccountHandle(
10456                         phoneAccountHandle, mContext.getOpPackageName(),
10457                         mContext.getAttributionTag());
10458             }
10459         } catch (RemoteException ex) {
10460             Log.e(TAG, "getSubscriptionId RemoteException", ex);
10461             ex.rethrowAsRuntimeException();
10462         }
10463         return retval;
10464     }
10465 
10466     /**
10467      * Resets telephony manager settings back to factory defaults.
10468      *
10469      * @hide
10470      */
factoryReset(int subId)10471     public void factoryReset(int subId) {
10472         try {
10473             Log.d(TAG, "factoryReset: subId=" + subId);
10474             ITelephony telephony = getITelephony();
10475             if (telephony != null) {
10476                 telephony.factoryReset(subId);
10477             }
10478         } catch (RemoteException e) {
10479         }
10480     }
10481 
10482 
10483     /**
10484      * Resets Telephony and IMS settings back to factory defaults only for the subscription
10485      * associated with this instance.
10486      * @see #createForSubscriptionId(int)
10487      * @hide
10488      */
10489     @SystemApi
10490     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
resetSettings()10491     public void resetSettings() {
10492         try {
10493             Log.d(TAG, "resetSettings: subId=" + getSubId());
10494             ITelephony telephony = getITelephony();
10495             if (telephony != null) {
10496                 telephony.factoryReset(getSubId());
10497             }
10498         } catch (RemoteException e) {
10499         }
10500     }
10501 
10502 
10503     /**
10504      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
10505      * no locale could be derived from subscriptions.
10506      *
10507      * <p>Requires Permission:
10508      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
10509      *
10510      * @see Locale#toLanguageTag()
10511      *
10512      * @hide
10513      */
10514     @SystemApi
10515     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimLocale()10516     @Nullable public Locale getSimLocale() {
10517         try {
10518             final ITelephony telephony = getITelephony();
10519             if (telephony != null) {
10520                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
10521                 if (!TextUtils.isEmpty(languageTag)) {
10522                     return Locale.forLanguageTag(languageTag);
10523                 }
10524             }
10525         } catch (RemoteException ex) {
10526         }
10527         return null;
10528     }
10529 
10530     /**
10531      * TODO delete after SuW migrates to new API.
10532      * @hide
10533      */
getLocaleFromDefaultSim()10534     public String getLocaleFromDefaultSim() {
10535         try {
10536             final ITelephony telephony = getITelephony();
10537             if (telephony != null) {
10538                 return telephony.getSimLocaleForSubscriber(getSubId());
10539             }
10540         } catch (RemoteException ex) {
10541         }
10542         return null;
10543     }
10544 
10545 
10546     /**
10547      * Requests the modem activity info. The recipient will place the result
10548      * in `result`.
10549      * @param result The object on which the recipient will send the resulting
10550      * {@link android.telephony.ModemActivityInfo} object with key of
10551      * {@link #MODEM_ACTIVITY_RESULT_KEY}.
10552      * @hide
10553      */
requestModemActivityInfo(@onNull ResultReceiver result)10554     public void requestModemActivityInfo(@NonNull ResultReceiver result) {
10555         try {
10556             ITelephony service = getITelephony();
10557             if (service != null) {
10558                 service.requestModemActivityInfo(result);
10559                 return;
10560             }
10561         } catch (RemoteException e) {
10562             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
10563         }
10564         result.send(0, null);
10565     }
10566 
10567     /**
10568      * Returns the current {@link ServiceState} information.
10569      *
10570      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10571      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10572      *
10573      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
10574      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
10575      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
10576      */
10577     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
10578     @RequiresPermission(allOf = {
10579             Manifest.permission.READ_PHONE_STATE,
10580             Manifest.permission.ACCESS_COARSE_LOCATION
10581     })
getServiceState()10582     public ServiceState getServiceState() {
10583         return getServiceStateForSubscriber(getSubId());
10584     }
10585 
10586     /**
10587      * Returns the service state information on specified subscription. Callers require
10588      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
10589      * @hide
10590      */
10591     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)10592     public ServiceState getServiceStateForSubscriber(int subId) {
10593         try {
10594             ITelephony service = getITelephony();
10595             if (service != null) {
10596                 return service.getServiceStateForSubscriber(subId, getOpPackageName(),
10597                         getAttributionTag());
10598             }
10599         } catch (RemoteException e) {
10600             Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
10601         } catch (NullPointerException e) {
10602             AnomalyReporter.reportAnomaly(
10603                     UUID.fromString("a3ab0b9d-f2aa-4baf-911d-7096c0d4645a"),
10604                     "getServiceStateForSubscriber " + subId + " NPE");
10605         }
10606         return null;
10607     }
10608 
10609     /**
10610      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
10611      *
10612      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
10613      * voicemail ringtone.
10614      * @return The URI for the ringtone to play when receiving a voicemail from a specific
10615      * PhoneAccount.
10616      */
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)10617     public Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
10618         try {
10619             ITelephony service = getITelephony();
10620             if (service != null) {
10621                 return service.getVoicemailRingtoneUri(accountHandle);
10622             }
10623         } catch (RemoteException e) {
10624             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
10625         }
10626         return null;
10627     }
10628 
10629     /**
10630      * Sets the per-account voicemail ringtone.
10631      *
10632      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
10633      * {@link #hasCarrierPrivileges}, or has permission
10634      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10635      *
10636      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
10637      * voicemail ringtone.
10638      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
10639      * PhoneAccount.
10640      *
10641      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
10642      * instead.
10643      */
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)10644     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
10645         try {
10646             ITelephony service = getITelephony();
10647             if (service != null) {
10648                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
10649             }
10650         } catch (RemoteException e) {
10651             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
10652         }
10653     }
10654 
10655     /**
10656      * Returns whether vibration is set for voicemail notification in Phone settings.
10657      *
10658      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
10659      * voicemail vibration setting.
10660      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
10661      */
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)10662     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
10663         try {
10664             ITelephony service = getITelephony();
10665             if (service != null) {
10666                 return service.isVoicemailVibrationEnabled(accountHandle);
10667             }
10668         } catch (RemoteException e) {
10669             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
10670         }
10671         return false;
10672     }
10673 
10674     /**
10675      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
10676      *
10677      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
10678      * {@link #hasCarrierPrivileges}, or has permission
10679      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10680      *
10681      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
10682      * voicemail vibration setting.
10683      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
10684      * specific PhoneAccount.
10685      *
10686      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
10687      * instead.
10688      */
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)10689     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
10690             boolean enabled) {
10691         try {
10692             ITelephony service = getITelephony();
10693             if (service != null) {
10694                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
10695                         enabled);
10696             }
10697         } catch (RemoteException e) {
10698             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
10699         }
10700     }
10701 
10702     /**
10703      * Returns carrier id of the current subscription.
10704      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
10705      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
10706      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
10707      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10708      *
10709      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
10710      * as an Android platform-wide identifier for carriers.
10711      *
10712      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
10713      * subscription is unavailable or the carrier cannot be identified.
10714      */
getSimCarrierId()10715     public int getSimCarrierId() {
10716         try {
10717             ITelephony service = getITelephony();
10718             if (service != null) {
10719                 return service.getSubscriptionCarrierId(getSubId());
10720             }
10721         } catch (RemoteException ex) {
10722             // This could happen if binder process crashes.
10723         }
10724         return UNKNOWN_CARRIER_ID;
10725     }
10726 
10727     /**
10728      * Returns carrier id name of the current subscription.
10729      * <p>Carrier id name is a user-facing name of carrier id returned by
10730      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
10731      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
10732      * should have a single carrier name. Carrier name is not a canonical identity,
10733      * use {@link #getSimCarrierId()} instead.
10734      * <p>The returned carrier name is unlocalized.
10735      *
10736      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
10737      * unavailable or the carrier cannot be identified.
10738      */
getSimCarrierIdName()10739     public @Nullable CharSequence getSimCarrierIdName() {
10740         try {
10741             ITelephony service = getITelephony();
10742             if (service != null) {
10743                 return service.getSubscriptionCarrierName(getSubId());
10744             }
10745         } catch (RemoteException ex) {
10746             // This could happen if binder process crashes.
10747         }
10748         return null;
10749     }
10750 
10751     /**
10752      * Returns fine-grained carrier ID of the current subscription.
10753      *
10754      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
10755      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
10756      * are used to make up the actual carrier service may have different carrier configurations.
10757      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
10758      * different carrier configuration for different service offering such as a prepaid plan.
10759      *
10760      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
10761      * about the carrier itself should use the regular carrier ID returned by
10762      * {@link #getSimCarrierId()}.
10763      *
10764      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
10765      * subscription while carrier ID remains the same.
10766      *
10767      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
10768      * <p>Specific carrier ids are defined in the same way as carrier id
10769      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10770      * except each with a "parent" id linking to its top-level carrier id.
10771      *
10772      * @return Returns fine-grained carrier id of the current subscription.
10773      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
10774      * be identified.
10775      */
getSimSpecificCarrierId()10776     public int getSimSpecificCarrierId() {
10777         try {
10778             ITelephony service = getITelephony();
10779             if (service != null) {
10780                 return service.getSubscriptionSpecificCarrierId(getSubId());
10781             }
10782         } catch (RemoteException ex) {
10783             // This could happen if binder process crashes.
10784         }
10785         return UNKNOWN_CARRIER_ID;
10786     }
10787 
10788     /**
10789      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
10790      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
10791      *
10792      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
10793      * about the carrier itself should use the regular carrier ID returned by
10794      * {@link #getSimCarrierIdName()}.
10795      *
10796      * <p>The returned name is unlocalized.
10797      *
10798      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
10799      * subscription is unavailable or the carrier cannot be identified.
10800      */
getSimSpecificCarrierIdName()10801     public @Nullable CharSequence getSimSpecificCarrierIdName() {
10802         try {
10803             ITelephony service = getITelephony();
10804             if (service != null) {
10805                 return service.getSubscriptionSpecificCarrierName(getSubId());
10806             }
10807         } catch (RemoteException ex) {
10808             // This could happen if binder process crashes.
10809         }
10810         return null;
10811     }
10812 
10813     /**
10814      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
10815      * This is used for fallback when configurations/logic for exact carrier id
10816      * {@link #getSimCarrierId()} are not found.
10817      *
10818      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10819      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
10820      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
10821      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
10822      * take the update with the new id, it might be helpful to always fallback by using carrier
10823      * id based on MCCMNC if there is no match.
10824      *
10825      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
10826      * subscription is unavailable or the carrier cannot be identified.
10827      */
getCarrierIdFromSimMccMnc()10828     public int getCarrierIdFromSimMccMnc() {
10829         try {
10830             ITelephony service = getITelephony();
10831             if (service != null) {
10832                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
10833             }
10834         } catch (RemoteException ex) {
10835             // This could happen if binder process crashes.
10836         }
10837         return UNKNOWN_CARRIER_ID;
10838     }
10839 
10840      /**
10841       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
10842       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
10843       * are not found.
10844       *
10845       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10846       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
10847       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
10848       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
10849       * take the update with the new id, it might be helpful to always fallback by using carrier
10850       * id based on MCCMNC if there is no match.
10851       *
10852       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
10853       * subscription is unavailable or the carrier cannot be identified.
10854       * @hide
10855       */
10856      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)10857      public int getCarrierIdFromMccMnc(String mccmnc) {
10858         try {
10859             ITelephony service = getITelephony();
10860             if (service != null) {
10861                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
10862             }
10863         } catch (RemoteException ex) {
10864             // This could happen if binder process crashes.
10865         }
10866         return UNKNOWN_CARRIER_ID;
10867     }
10868 
10869     /**
10870      * Return a list of certs in hex string from loaded carrier privileges access rules.
10871      *
10872      * @return a list of certificate in hex string. return {@code null} if there is no certs
10873      * or privilege rules are not loaded yet.
10874      *
10875      * <p>Requires Permission:
10876      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
10877      * @hide
10878      */
10879     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCertsFromCarrierPrivilegeAccessRules()10880     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
10881         try {
10882             ITelephony service = getITelephony();
10883             if (service != null) {
10884                 return service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
10885             }
10886         } catch (RemoteException ex) {
10887             // This could happen if binder process crashes.
10888         }
10889         return null;
10890     }
10891 
10892     /**
10893      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
10894      * All uicc applications are uniquely identified by application ID, represented by the hex
10895      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
10896      * <p>Requires Permission:
10897      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
10898      *
10899      * @param appType the uicc app type.
10900      * @return Application ID for specified app type or {@code null} if no uicc or error.
10901      * @hide
10902      */
10903     @Nullable
10904     @SystemApi
10905     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAidForAppType(@iccAppType int appType)10906     public String getAidForAppType(@UiccAppType int appType) {
10907         return getAidForAppType(getSubId(), appType);
10908     }
10909 
10910     /**
10911      * same as {@link #getAidForAppType(int)}
10912      * @hide
10913      */
getAidForAppType(int subId, int appType)10914     public String getAidForAppType(int subId, int appType) {
10915         try {
10916             ITelephony service = getITelephony();
10917             if (service != null) {
10918                 return service.getAidForAppType(subId, appType);
10919             }
10920         } catch (RemoteException e) {
10921             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
10922         }
10923         return null;
10924     }
10925 
10926     /**
10927      * Return the Electronic Serial Number.
10928      *
10929      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10930      *
10931      * @return ESN or null if error.
10932      * @hide
10933      */
getEsn()10934     public String getEsn() {
10935         return getEsn(getSubId());
10936     }
10937 
10938     /**
10939      * Return the Electronic Serial Number.
10940      *
10941      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10942      *
10943      * @param subId the subscription ID that this request applies to.
10944      * @return ESN or null if error.
10945      * @hide
10946      */
getEsn(int subId)10947     public String getEsn(int subId) {
10948         try {
10949             ITelephony service = getITelephony();
10950             if (service != null) {
10951                 return service.getEsn(subId);
10952             }
10953         } catch (RemoteException e) {
10954             Log.e(TAG, "Error calling ITelephony#getEsn", e);
10955         }
10956         return null;
10957     }
10958 
10959     /**
10960      * Return the Preferred Roaming List Version
10961      *
10962      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10963      *
10964      * @return PRLVersion or null if error.
10965      * @hide
10966      */
10967     @SystemApi
getCdmaPrlVersion()10968     public String getCdmaPrlVersion() {
10969         return getCdmaPrlVersion(getSubId());
10970     }
10971 
10972     /**
10973      * Return the Preferred Roaming List Version
10974      *
10975      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10976      *
10977      * @param subId the subscription ID that this request applies to.
10978      * @return PRLVersion or null if error.
10979      * @hide
10980      */
getCdmaPrlVersion(int subId)10981     public String getCdmaPrlVersion(int subId) {
10982         try {
10983             ITelephony service = getITelephony();
10984             if (service != null) {
10985                 return service.getCdmaPrlVersion(subId);
10986             }
10987         } catch (RemoteException e) {
10988             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
10989         }
10990         return null;
10991     }
10992 
10993     /**
10994      * Get snapshot of Telephony histograms
10995      * @return List of Telephony histograms
10996      * Requires Permission:
10997      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10998      * Or the calling app has carrier privileges.
10999      * @hide
11000      */
11001     @SystemApi
11002     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()11003     public List<TelephonyHistogram> getTelephonyHistograms() {
11004         try {
11005             ITelephony service = getITelephony();
11006             if (service != null) {
11007                 return service.getTelephonyHistograms();
11008             }
11009         } catch (RemoteException e) {
11010             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
11011         }
11012         return null;
11013     }
11014 
11015     /**
11016      * Set the allowed carrier list for slotIndex
11017      * Require system privileges. In the future we may add this to carrier APIs.
11018      *
11019      * <p>Requires Permission:
11020      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
11021      *
11022      * <p>This method works only on devices with {@link
11023      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11024      *
11025      * @deprecated use setCarrierRestrictionRules instead
11026      *
11027      * @return The number of carriers set successfully. Should be length of
11028      * carrierList on success; -1 if carrierList null or on error.
11029      * @hide
11030      */
11031     @SystemApi
11032     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)11033     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
11034         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
11035             return -1;
11036         }
11037         // Execute the method setCarrierRestrictionRules with an empty excluded list and
11038         // indicating priority for the allowed list.
11039         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
11040                 .setAllowedCarriers(carriers)
11041                 .setDefaultCarrierRestriction(
11042                     CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
11043                 .build();
11044 
11045         int result = setCarrierRestrictionRules(carrierRestrictionRules);
11046 
11047         // Convert result into int, as required by this method.
11048         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
11049             return carriers.size();
11050         } else {
11051             return -1;
11052         }
11053     }
11054 
11055     /**
11056      * The carrier restrictions were successfully set.
11057      * @hide
11058      */
11059     @SystemApi
11060     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
11061 
11062     /**
11063      * The carrier restrictions were not set due to lack of support in the modem. This can happen
11064      * if the modem does not support setting the carrier restrictions or if the configuration
11065      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
11066      * @hide
11067      */
11068     @SystemApi
11069     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
11070 
11071     /**
11072      * The setting of carrier restrictions failed.
11073      * @hide
11074      */
11075     @SystemApi
11076     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
11077 
11078     /** @hide */
11079     @Retention(RetentionPolicy.SOURCE)
11080     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
11081             value = {
11082                     SET_CARRIER_RESTRICTION_SUCCESS,
11083                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
11084                     SET_CARRIER_RESTRICTION_ERROR
11085             })
11086     public @interface SetCarrierRestrictionResult {}
11087 
11088     /**
11089      * Set the allowed carrier list and the excluded carrier list indicating the priority between
11090      * the two lists.
11091      * Requires system privileges.
11092      *
11093      * <p>Requires Permission:
11094      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
11095      *
11096      * <p>This method works only on devices with {@link
11097      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11098      *
11099      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
11100      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
11101      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
11102      * @hide
11103      */
11104     @SystemApi
11105     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11106     @SetCarrierRestrictionResult
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)11107     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
11108         try {
11109             ITelephony service = getITelephony();
11110             if (service != null) {
11111                 return service.setAllowedCarriers(rules);
11112             }
11113         } catch (RemoteException e) {
11114             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
11115         } catch (NullPointerException e) {
11116             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
11117         }
11118         return SET_CARRIER_RESTRICTION_ERROR;
11119     }
11120 
11121     /**
11122      * Get the allowed carrier list for slotIndex.
11123      * Requires system privileges.
11124      *
11125      * <p>This method returns valid data on devices with {@link
11126      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11127      *
11128      * @deprecated Apps should use {@link getCarriersRestrictionRules} to retrieve the list of
11129      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
11130      * list is empty. This API could return an empty list, even if some restrictions are present.
11131      *
11132      * @return List of {@link android.telephony.CarrierIdentifier}; empty list
11133      * means all carriers are allowed.
11134      * @hide
11135      */
11136     @Deprecated
11137     @SystemApi
11138     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedCarriers(int slotIndex)11139     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
11140         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
11141             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
11142             if (carrierRestrictionRule != null) {
11143                 return carrierRestrictionRule.getAllowedCarriers();
11144             }
11145         }
11146         return new ArrayList<CarrierIdentifier>(0);
11147     }
11148 
11149     /**
11150      * Get the allowed carrier list and the excluded carrier list indicating the priority between
11151      * the two lists.
11152      * Require system privileges. In the future we may add this to carrier APIs.
11153      *
11154      * <p>This method returns valid data on devices with {@link
11155      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11156      *
11157      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
11158      * excluded carrier list with the priority between the two lists. Returns {@code null}
11159      * in case of error.
11160      * @hide
11161      */
11162     @SystemApi
11163     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11164     @Nullable
getCarrierRestrictionRules()11165     public CarrierRestrictionRules getCarrierRestrictionRules() {
11166         try {
11167             ITelephony service = getITelephony();
11168             if (service != null) {
11169                 return service.getAllowedCarriers();
11170             }
11171         } catch (RemoteException e) {
11172             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
11173         } catch (NullPointerException e) {
11174             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
11175         }
11176         return null;
11177     }
11178 
11179     /**
11180      * Used to enable or disable carrier data by the system based on carrier signalling or
11181      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
11182      * user settings, carrier data on/off won't affect user settings but will bypass the
11183      * settings and turns off data internally if set to {@code false}.
11184      *
11185      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11186      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11187      *
11188      * <p>Requires Permission:
11189      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11190      *
11191      * @param enabled control enable or disable carrier data.
11192      * @see #resetAllCarrierActions()
11193      * @hide
11194      */
11195     @SystemApi
11196     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCarrierDataEnabled(boolean enabled)11197     public void setCarrierDataEnabled(boolean enabled) {
11198         try {
11199             ITelephony service = getITelephony();
11200             if (service != null) {
11201                 service.carrierActionSetMeteredApnsEnabled(
11202                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
11203             }
11204         } catch (RemoteException e) {
11205             Log.e(TAG, "Error calling ITelephony#setCarrierDataEnabled", e);
11206         }
11207     }
11208 
11209     /**
11210      * Carrier action to enable or disable the radio.
11211      *
11212      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11213      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11214      *
11215      * <p>Requires Permission:
11216      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11217      *
11218      * @param enabled control enable or disable radio.
11219      * @see #resetAllCarrierActions()
11220      * @hide
11221      */
11222     @SystemApi
11223     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioEnabled(boolean enabled)11224     public void setRadioEnabled(boolean enabled) {
11225         try {
11226             ITelephony service = getITelephony();
11227             if (service != null) {
11228                 service.carrierActionSetRadioEnabled(
11229                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
11230             }
11231         } catch (RemoteException e) {
11232             Log.e(TAG, "Error calling ITelephony#carrierActionSetRadioEnabled", e);
11233         }
11234     }
11235 
11236     /**
11237      * Carrier action to start or stop reporting default network available events.
11238      *
11239      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11240      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11241      *
11242      * <p>Requires Permission:
11243      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11244      *
11245      * @param report control start/stop reporting network status.
11246      * @see #resetAllCarrierActions()
11247      * @hide
11248      */
11249     @SystemApi
11250     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
reportDefaultNetworkStatus(boolean report)11251     public void reportDefaultNetworkStatus(boolean report) {
11252         try {
11253             ITelephony service = getITelephony();
11254             if (service != null) {
11255                 service.carrierActionReportDefaultNetworkStatus(
11256                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
11257             }
11258         } catch (RemoteException e) {
11259             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
11260         }
11261     }
11262 
11263     /**
11264      * Reset all carrier actions previously set by {@link #setRadioEnabled},
11265      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
11266      *
11267      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11268      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11269      *
11270      * <p>Requires Permission:
11271      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11272      * @hide
11273      */
11274     @SystemApi
11275     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetAllCarrierActions()11276     public void resetAllCarrierActions() {
11277         try {
11278             ITelephony service = getITelephony();
11279             if (service != null) {
11280                 service.carrierActionResetAll(
11281                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
11282             }
11283         } catch (RemoteException e) {
11284             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
11285         }
11286     }
11287 
11288     /**
11289      * Policy control of data connection. Usually used when data limit is passed.
11290      * @param enabled True if enabling the data, otherwise disabling.
11291      * @hide
11292      */
11293     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setPolicyDataEnabled(boolean enabled)11294     public void setPolicyDataEnabled(boolean enabled) {
11295         try {
11296             ITelephony service = getITelephony();
11297             if (service != null) {
11298                 service.setPolicyDataEnabled(enabled, getSubId());
11299             }
11300         } catch (RemoteException e) {
11301             Log.e(TAG, "Error calling ITelephony#setPolicyDataEnabled", e);
11302         }
11303     }
11304 
11305     /**
11306      * Get Client request stats which will contain statistical information
11307      * on each request made by client.
11308      * Callers require either READ_PRIVILEGED_PHONE_STATE or
11309      * READ_PHONE_STATE to retrieve the information.
11310      * @param subId sub id
11311      * @return List of Client Request Stats
11312      * @hide
11313      */
getClientRequestStats(int subId)11314     public List<ClientRequestStats> getClientRequestStats(int subId) {
11315         try {
11316             ITelephony service = getITelephony();
11317             if (service != null) {
11318                 return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
11319                         subId);
11320             }
11321         } catch (RemoteException e) {
11322             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
11323         }
11324 
11325         return null;
11326     }
11327 
11328     /**
11329      * Checks if phone is in emergency callback mode.
11330      *
11331      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11332      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11333      *
11334      * @return true if phone is in emergency callback mode.
11335      * @hide
11336      */
11337     @SystemApi
11338     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyCallbackMode()11339     public boolean getEmergencyCallbackMode() {
11340         return getEmergencyCallbackMode(getSubId());
11341     }
11342 
11343     /**
11344      * Check if phone is in emergency callback mode
11345      * @return true if phone is in emergency callback mode
11346      * @param subId the subscription ID that this action applies to.
11347      * @hide
11348      */
getEmergencyCallbackMode(int subId)11349     public boolean getEmergencyCallbackMode(int subId) {
11350         try {
11351             ITelephony telephony = getITelephony();
11352             if (telephony == null) {
11353                 return false;
11354             }
11355             return telephony.getEmergencyCallbackMode(subId);
11356         } catch (RemoteException e) {
11357             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
11358         }
11359         return false;
11360     }
11361 
11362     /**
11363      * Checks if manual network selection is allowed.
11364      *
11365      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
11366      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
11367      * (see {@link #hasCarrierPrivileges})
11368      *
11369      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11370      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
11371      *
11372      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
11373      */
11374     @SuppressAutoDoc // No support carrier privileges (b/72967236).
11375     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRECISE_PHONE_STATE,
11376             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
isManualNetworkSelectionAllowed()11377     public boolean isManualNetworkSelectionAllowed() {
11378         try {
11379             ITelephony telephony = getITelephony();
11380             if (telephony != null) {
11381                 return telephony.isManualNetworkSelectionAllowed(getSubId());
11382             }
11383         } catch (RemoteException e) {
11384             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
11385         }
11386         return true;
11387     }
11388 
11389     /**
11390      * Enable or disable signal strength changes from radio will always be reported in any
11391      * condition (e.g. screen is off). This is only allowed for System caller.
11392      *
11393      * @param isEnabled {@code true} for enabling; {@code false} for disabling.
11394      * @hide
11395      */
11396     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysReportSignalStrength(boolean isEnabled)11397     public void setAlwaysReportSignalStrength(boolean isEnabled) {
11398         try {
11399             ITelephony telephony = getITelephony();
11400             if (telephony != null) {
11401                 telephony.setAlwaysReportSignalStrength(getSubId(), isEnabled);
11402             }
11403         } catch (RemoteException ex) {
11404             Log.e(TAG, "setAlwaysReportSignalStrength RemoteException", ex);
11405             ex.rethrowAsRuntimeException();
11406         }
11407     }
11408 
11409     /**
11410      * Get the most recently available signal strength information.
11411      *
11412      * Get the most recent SignalStrength information reported by the modem. Due
11413      * to power saving this information may not always be current.
11414      * @return the most recent cached signal strength info from the modem
11415      */
11416     @Nullable
getSignalStrength()11417     public SignalStrength getSignalStrength() {
11418         try {
11419             ITelephony service = getITelephony();
11420             if (service != null) {
11421                 return service.getSignalStrength(getSubId());
11422             }
11423         } catch (RemoteException e) {
11424             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
11425         }
11426         return null;
11427     }
11428 
11429     /**
11430      * Checks whether cellular data connection is allowed in the device.
11431      *
11432      * <p>Whether cellular data connection is allowed considers all factors below:
11433      * <UL>
11434      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
11435      *   <LI>Carrier allows data to be on.</LI>
11436      *   <LI>Network policy.</LI>
11437      *   <LI>And possibly others.</LI>
11438      * </UL>
11439      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
11440      * @hide
11441      */
11442     @SystemApi
11443     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataConnectionAllowed()11444     public boolean isDataConnectionAllowed() {
11445         boolean retVal = false;
11446         try {
11447             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
11448             ITelephony telephony = getITelephony();
11449             if (telephony != null)
11450                 retVal = telephony.isDataEnabled(subId);
11451         } catch (RemoteException e) {
11452             Log.e(TAG, "Error isDataConnectionAllowed", e);
11453         }
11454         return retVal;
11455     }
11456 
11457     /**
11458      * @return true if the current device is "data capable" over a radio on the device.
11459      * <p>
11460      * "Data capable" means that this device supports packet-switched
11461      * data connections over the telephony network.
11462      * <p>
11463      * Note: the meaning of this flag is subtly different from the
11464      * PackageManager.FEATURE_TELEPHONY system feature, which is available
11465      * on any device with a telephony radio, even if the device is
11466      * voice-only.
11467      *
11468      * @hide
11469      */
isDataCapable()11470     public boolean isDataCapable() {
11471         if (mContext == null) return true;
11472         return mContext.getResources().getBoolean(
11473                 com.android.internal.R.bool.config_mobile_data_capable);
11474     }
11475 
11476     /**
11477      * In this mode, modem will not send specified indications when screen is off.
11478      * @hide
11479      */
11480     public static final int INDICATION_UPDATE_MODE_NORMAL                   = 1;
11481 
11482     /**
11483      * In this mode, modem will still send specified indications when screen is off.
11484      * @hide
11485      */
11486     public static final int INDICATION_UPDATE_MODE_IGNORE_SCREEN_OFF        = 2;
11487 
11488     /**
11489      * The indication for signal strength update.
11490      * @hide
11491      */
11492     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
11493 
11494     /**
11495      * The indication for full network state update.
11496      * @hide
11497      */
11498     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
11499 
11500     /**
11501      * The indication for data call dormancy changed update.
11502      * @hide
11503      */
11504     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
11505 
11506     /**
11507      * The indication for link capacity estimate update.
11508      * @hide
11509      */
11510     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
11511 
11512     /**
11513      * The indication for physical channel config update.
11514      * @hide
11515      */
11516     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
11517 
11518     /**
11519      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
11520      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
11521      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
11522      *
11523      * <p>Requires Permission:
11524      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11525      *
11526      *
11527      * @deprecated
11528      * @hide
11529      */
11530     @Deprecated
11531     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)11532     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
11533             String gid2, String plmn, String spn) {
11534         try {
11535             ITelephony telephony = getITelephony();
11536             if (telephony != null) {
11537                 telephony.setCarrierTestOverride(
11538                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
11539                         null, null);
11540             }
11541         } catch (RemoteException ex) {
11542             // This could happen if binder process crashes.
11543         }
11544     }
11545 
11546     /**
11547      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
11548      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
11549      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
11550      * a test SIM with a call box.
11551      *
11552      * <p>Requires Permission:
11553      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11554      *
11555      * @hide
11556      */
11557     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)11558     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
11559                                        String gid2, String plmn, String spn,
11560                                        String carrierPriviledgeRules, String apn) {
11561         try {
11562             ITelephony telephony = getITelephony();
11563             if (telephony != null) {
11564                 telephony.setCarrierTestOverride(
11565                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
11566                         carrierPriviledgeRules, apn);
11567             }
11568         } catch (RemoteException ex) {
11569             // This could happen if binder process crashes.
11570         }
11571     }
11572 
11573     /**
11574      * A test API to return installed carrier id list version
11575      *
11576      * <p>Requires Permission:
11577      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11578      *
11579      * @hide
11580      */
11581     @UnsupportedAppUsage
11582     @TestApi
getCarrierIdListVersion()11583     public int getCarrierIdListVersion() {
11584         try {
11585             ITelephony telephony = getITelephony();
11586             if (telephony != null) {
11587                 return telephony.getCarrierIdListVersion(getSubId());
11588             }
11589         } catch (RemoteException ex) {
11590             // This could happen if binder process crashes.
11591         }
11592         return UNKNOWN_CARRIER_ID_LIST_VERSION;
11593     }
11594 
11595     /**
11596      * How many modems can have simultaneous data connections.
11597      * @hide
11598      */
11599     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()11600     public int getNumberOfModemsWithSimultaneousDataConnections() {
11601         try {
11602             ITelephony telephony = getITelephony();
11603             if (telephony != null) {
11604                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
11605                         getSubId(), getOpPackageName(), getAttributionTag());
11606             }
11607         } catch (RemoteException ex) {
11608             // This could happen if binder process crashes.
11609         }
11610         return 0;
11611     }
11612 
11613     /**
11614      * Enable or disable OpportunisticNetworkService.
11615      *
11616      * This method should be called to enable or disable
11617      * OpportunisticNetwork service on the device.
11618      *
11619      * <p>
11620      * Requires Permission:
11621      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11622      *
11623      * @param enable enable(True) or disable(False)
11624      * @return returns true if successfully set.
11625      * @hide
11626      */
11627     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11628     @SystemApi
setOpportunisticNetworkState(boolean enable)11629     public boolean setOpportunisticNetworkState(boolean enable) {
11630         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11631         boolean ret = false;
11632         try {
11633             IOns iOpportunisticNetworkService = getIOns();
11634             if (iOpportunisticNetworkService != null) {
11635                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
11636             }
11637         } catch (RemoteException ex) {
11638             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
11639         }
11640 
11641         return ret;
11642     }
11643 
11644     /**
11645      * is OpportunisticNetworkService enabled
11646      *
11647      * This method should be called to determine if the OpportunisticNetworkService is
11648      * enabled
11649      *
11650      * <p>
11651      * Requires Permission:
11652      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11653      * @hide
11654      */
11655     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11656     @SystemApi
isOpportunisticNetworkEnabled()11657     public boolean isOpportunisticNetworkEnabled() {
11658         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11659         boolean isEnabled = false;
11660 
11661         try {
11662             IOns iOpportunisticNetworkService = getIOns();
11663             if (iOpportunisticNetworkService != null) {
11664                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
11665             }
11666         } catch (RemoteException ex) {
11667             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
11668         }
11669 
11670         return isEnabled;
11671     }
11672 
11673     /** @hide */
11674     @Retention(RetentionPolicy.SOURCE)
11675     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
11676             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
11677                     NETWORK_TYPE_BITMASK_GSM,
11678                     NETWORK_TYPE_BITMASK_GPRS,
11679                     NETWORK_TYPE_BITMASK_EDGE,
11680                     NETWORK_TYPE_BITMASK_CDMA,
11681                     NETWORK_TYPE_BITMASK_1xRTT,
11682                     NETWORK_TYPE_BITMASK_EVDO_0,
11683                     NETWORK_TYPE_BITMASK_EVDO_A,
11684                     NETWORK_TYPE_BITMASK_EVDO_B,
11685                     NETWORK_TYPE_BITMASK_EHRPD,
11686                     NETWORK_TYPE_BITMASK_HSUPA,
11687                     NETWORK_TYPE_BITMASK_HSDPA,
11688                     NETWORK_TYPE_BITMASK_HSPA,
11689                     NETWORK_TYPE_BITMASK_HSPAP,
11690                     NETWORK_TYPE_BITMASK_UMTS,
11691                     NETWORK_TYPE_BITMASK_TD_SCDMA,
11692                     NETWORK_TYPE_BITMASK_LTE,
11693                     NETWORK_TYPE_BITMASK_LTE_CA,
11694                     NETWORK_TYPE_BITMASK_NR,
11695             })
11696     public @interface NetworkTypeBitMask {}
11697 
11698     // 2G
11699     /**
11700      * network type bitmask unknown.
11701      * @hide
11702      */
11703     @SystemApi
11704     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
11705     /**
11706      * network type bitmask indicating the support of radio tech GSM.
11707      * @hide
11708      */
11709     @SystemApi
11710     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
11711     /**
11712      * network type bitmask indicating the support of radio tech GPRS.
11713      * @hide
11714      */
11715     @SystemApi
11716     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
11717     /**
11718      * network type bitmask indicating the support of radio tech EDGE.
11719      * @hide
11720      */
11721     @SystemApi
11722     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
11723     /**
11724      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
11725      * @hide
11726      */
11727     @SystemApi
11728     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
11729     /**
11730      * network type bitmask indicating the support of radio tech 1xRTT.
11731      * @hide
11732      */
11733     @SystemApi
11734     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
11735     // 3G
11736     /**
11737      * network type bitmask indicating the support of radio tech EVDO 0.
11738      * @hide
11739      */
11740     @SystemApi
11741     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
11742     /**
11743      * network type bitmask indicating the support of radio tech EVDO A.
11744      * @hide
11745      */
11746     @SystemApi
11747     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
11748     /**
11749      * network type bitmask indicating the support of radio tech EVDO B.
11750      * @hide
11751      */
11752     @SystemApi
11753     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
11754     /**
11755      * network type bitmask indicating the support of radio tech EHRPD.
11756      * @hide
11757      */
11758     @SystemApi
11759     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
11760     /**
11761      * network type bitmask indicating the support of radio tech HSUPA.
11762      * @hide
11763      */
11764     @SystemApi
11765     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
11766     /**
11767      * network type bitmask indicating the support of radio tech HSDPA.
11768      * @hide
11769      */
11770     @SystemApi
11771     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
11772     /**
11773      * network type bitmask indicating the support of radio tech HSPA.
11774      * @hide
11775      */
11776     @SystemApi
11777     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
11778     /**
11779      * network type bitmask indicating the support of radio tech HSPAP.
11780      * @hide
11781      */
11782     @SystemApi
11783     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
11784     /**
11785      * network type bitmask indicating the support of radio tech UMTS.
11786      * @hide
11787      */
11788     @SystemApi
11789     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
11790     /**
11791      * network type bitmask indicating the support of radio tech TD_SCDMA.
11792      * @hide
11793      */
11794     @SystemApi
11795     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
11796     // 4G
11797     /**
11798      * network type bitmask indicating the support of radio tech LTE.
11799      * @hide
11800      */
11801     @SystemApi
11802     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
11803     /**
11804      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
11805      * @hide
11806      */
11807     @SystemApi
11808     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
11809 
11810     /**
11811      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
11812      * @hide
11813      */
11814     @SystemApi
11815     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
11816 
11817     /**
11818      * network type bitmask indicating the support of radio tech IWLAN.
11819      * @hide
11820      */
11821     @SystemApi
11822     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
11823 
11824     /** @hide */
11825     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
11826                 | NETWORK_TYPE_BITMASK_GPRS
11827                 | NETWORK_TYPE_BITMASK_EDGE
11828                 | NETWORK_TYPE_BITMASK_CDMA
11829                 | NETWORK_TYPE_BITMASK_1xRTT;
11830 
11831     /** @hide */
11832     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
11833             | NETWORK_TYPE_BITMASK_EVDO_A
11834             | NETWORK_TYPE_BITMASK_EVDO_B
11835             | NETWORK_TYPE_BITMASK_EHRPD
11836             | NETWORK_TYPE_BITMASK_HSUPA
11837             | NETWORK_TYPE_BITMASK_HSDPA
11838             | NETWORK_TYPE_BITMASK_HSPA
11839             | NETWORK_TYPE_BITMASK_HSPAP
11840             | NETWORK_TYPE_BITMASK_UMTS
11841             | NETWORK_TYPE_BITMASK_TD_SCDMA;
11842 
11843     /** @hide */
11844     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
11845             | NETWORK_TYPE_BITMASK_LTE_CA
11846             | NETWORK_TYPE_BITMASK_IWLAN;
11847 
11848     /** @hide */
11849     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
11850 
11851     /** @hide */
11852     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
11853             | NETWORK_TYPE_BITMASK_GPRS
11854             | NETWORK_TYPE_BITMASK_EDGE
11855             | NETWORK_TYPE_BITMASK_HSUPA
11856             | NETWORK_TYPE_BITMASK_HSDPA
11857             | NETWORK_TYPE_BITMASK_HSPA
11858             | NETWORK_TYPE_BITMASK_HSPAP
11859             | NETWORK_TYPE_BITMASK_UMTS
11860             | NETWORK_TYPE_BITMASK_TD_SCDMA
11861             | NETWORK_TYPE_BITMASK_LTE
11862             | NETWORK_TYPE_BITMASK_LTE_CA
11863             | NETWORK_TYPE_BITMASK_NR;
11864 
11865     /** @hide */
11866     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
11867             | NETWORK_TYPE_BITMASK_1xRTT
11868             | NETWORK_TYPE_BITMASK_EVDO_0
11869             | NETWORK_TYPE_BITMASK_EVDO_A
11870             | NETWORK_TYPE_BITMASK_EVDO_B
11871             | NETWORK_TYPE_BITMASK_EHRPD;
11872 
11873     /**
11874      * @return Modem supported radio access family bitmask
11875      *
11876      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
11877      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11878      * @hide
11879      */
11880     @SystemApi
11881     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSupportedRadioAccessFamily()11882     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
11883         try {
11884             ITelephony telephony = getITelephony();
11885             if (telephony != null) {
11886                 return (long) telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
11887             } else {
11888                 // This can happen when the ITelephony interface is not up yet.
11889                 return NETWORK_TYPE_BITMASK_UNKNOWN;
11890             }
11891         } catch (RemoteException ex) {
11892             // This shouldn't happen in the normal case
11893             return NETWORK_TYPE_BITMASK_UNKNOWN;
11894         } catch (NullPointerException ex) {
11895             // This could happen before phone restarts due to crashing
11896             return NETWORK_TYPE_BITMASK_UNKNOWN;
11897         }
11898     }
11899 
11900     /**
11901      * Indicates Emergency number database version is invalid.
11902      *
11903      * @hide
11904      */
11905     @TestApi
11906     @SystemApi
11907     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
11908 
11909     /**
11910      * Notify Telephony for OTA emergency number database installation complete.
11911      *
11912      * <p> Requires permission:
11913      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11914      *
11915      * @hide
11916      */
11917     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11918     @SystemApi
notifyOtaEmergencyNumberDbInstalled()11919     public void notifyOtaEmergencyNumberDbInstalled() {
11920         try {
11921             ITelephony telephony = getITelephony();
11922             if (telephony != null) {
11923                 telephony.notifyOtaEmergencyNumberDbInstalled();
11924             } else {
11925                 throw new IllegalStateException("telephony service is null.");
11926             }
11927         } catch (RemoteException ex) {
11928             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
11929             ex.rethrowAsRuntimeException();
11930         }
11931     }
11932 
11933     /**
11934      * Override the file path for OTA emergency number database in a file partition.
11935      *
11936      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
11937      *
11938      * <p> Requires permission:
11939      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
11940      *
11941      * @hide
11942      */
11943     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
11944     @SystemApi
11945     @TestApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)11946     public void updateOtaEmergencyNumberDbFilePath(
11947             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
11948         try {
11949             ITelephony telephony = getITelephony();
11950             if (telephony != null) {
11951                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
11952             } else {
11953                 throw new IllegalStateException("telephony service is null.");
11954             }
11955         } catch (RemoteException ex) {
11956             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
11957             ex.rethrowAsRuntimeException();
11958         }
11959     }
11960 
11961     /**
11962      * Reset the file path to default for OTA emergency number database in a file partition.
11963      *
11964      * <p> Requires permission:
11965      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
11966      *
11967      * @hide
11968      */
11969     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
11970     @SystemApi
11971     @TestApi
resetOtaEmergencyNumberDbFilePath()11972     public void resetOtaEmergencyNumberDbFilePath() {
11973         try {
11974             ITelephony telephony = getITelephony();
11975             if (telephony != null) {
11976                 telephony.resetOtaEmergencyNumberDbFilePath();
11977             } else {
11978                 throw new IllegalStateException("telephony service is null.");
11979             }
11980         } catch (RemoteException ex) {
11981             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
11982             ex.rethrowAsRuntimeException();
11983         }
11984     }
11985 
11986     /**
11987      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
11988      * available on the device.
11989      * <p>
11990      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
11991      *
11992      * @return {@code true} if emergency assistance is available, {@code false} otherwise
11993      *
11994      * @hide
11995      */
11996     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11997     @SystemApi
isEmergencyAssistanceEnabled()11998     public boolean isEmergencyAssistanceEnabled() {
11999         mContext.enforceCallingOrSelfPermission(
12000                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
12001                 "isEmergencyAssistanceEnabled");
12002         return EMERGENCY_ASSISTANCE_ENABLED;
12003     }
12004 
12005     /**
12006      * Get the emergency number list based on current locale, sim, default, modem and network.
12007      *
12008      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
12009      * priority sources will be located at the smaller index; the priority order of sources are:
12010      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
12011      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
12012      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
12013      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
12014      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
12015      *
12016      * <p>The subscriptions which the returned list would be based on, are all the active
12017      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12018      *
12019      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
12020      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
12021      *
12022      * @return Map including the keys as the active subscription IDs (Note: if there is no active
12023      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
12024      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
12025      * or throw a SecurityException if the caller does not have the permission.
12026      */
12027     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12028     @NonNull
getEmergencyNumberList()12029     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
12030         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
12031         try {
12032             ITelephony telephony = getITelephony();
12033             if (telephony != null) {
12034                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
12035                         mContext.getAttributionTag());
12036             } else {
12037                 throw new IllegalStateException("telephony service is null.");
12038             }
12039         } catch (RemoteException ex) {
12040             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
12041             ex.rethrowAsRuntimeException();
12042         }
12043         return emergencyNumberList;
12044     }
12045 
12046     /**
12047      * Get the per-category emergency number list based on current locale, sim, default, modem
12048      * and network.
12049      *
12050      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
12051      * priority sources will be located at the smaller index; the priority order of sources are:
12052      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
12053      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
12054      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
12055      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
12056      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
12057      *
12058      * <p>The subscriptions which the returned list would be based on, are all the active
12059      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12060      *
12061      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
12062      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
12063      *
12064      * @param categories the emergency service categories which are the bitwise-OR combination of
12065      * the following constants:
12066      * <ol>
12067      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
12068      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
12069      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
12070      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
12071      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
12072      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
12073      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
12074      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
12075      * </ol>
12076      * @return Map including the keys as the active subscription IDs (Note: if there is no active
12077      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
12078      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
12079      * or throw a SecurityException if the caller does not have the permission.
12080      * @throws IllegalStateException if the Telephony process is not currently available.
12081      */
12082     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12083     @NonNull
getEmergencyNumberList( @mergencyServiceCategories int categories)12084     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
12085             @EmergencyServiceCategories int categories) {
12086         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
12087         try {
12088             ITelephony telephony = getITelephony();
12089             if (telephony != null) {
12090                 emergencyNumberList = telephony.getEmergencyNumberList(
12091                         mContext.getOpPackageName(), mContext.getAttributionTag());
12092                 if (emergencyNumberList != null) {
12093                     for (Integer subscriptionId : emergencyNumberList.keySet()) {
12094                         List<EmergencyNumber> numberList = emergencyNumberList.get(subscriptionId);
12095                         for (EmergencyNumber number : numberList) {
12096                             if (!number.isInEmergencyServiceCategories(categories)) {
12097                                 numberList.remove(number);
12098                             }
12099                         }
12100                     }
12101                 }
12102                 return emergencyNumberList;
12103             } else {
12104                 throw new IllegalStateException("telephony service is null.");
12105             }
12106         } catch (RemoteException ex) {
12107             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
12108             ex.rethrowAsRuntimeException();
12109         }
12110         return emergencyNumberList;
12111     }
12112 
12113     /**
12114      * Identifies if the supplied phone number is an emergency number that matches a known
12115      * emergency number based on current locale, SIM card(s), Android database, modem, network,
12116      * or defaults.
12117      *
12118      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
12119      * numbers are not considered emergency numbers. A dialable phone number consists only
12120      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
12121      *
12122      * <p>The subscriptions which the identification would be based on, are all the active
12123      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12124      *
12125      * @param number - the number to look up
12126      * @return {@code true} if the given number is an emergency number based on current locale,
12127      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
12128      * @throws IllegalStateException if the Telephony process is not currently available.
12129      */
isEmergencyNumber(@onNull String number)12130     public boolean isEmergencyNumber(@NonNull String number) {
12131         try {
12132             ITelephony telephony = getITelephony();
12133             if (telephony != null) {
12134                 return telephony.isEmergencyNumber(number, true);
12135             } else {
12136                 throw new IllegalStateException("telephony service is null.");
12137             }
12138         } catch (RemoteException ex) {
12139             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
12140             ex.rethrowAsRuntimeException();
12141         }
12142         return false;
12143     }
12144 
12145     /**
12146      * Checks if the supplied number is an emergency number based on current locale, sim, default,
12147      * modem and network.
12148      *
12149      * <p> Specifically, this method will return {@code true} if the specified number is an
12150      * emergency number, *or* if the number simply starts with the same digits as any current
12151      * emergency number.
12152      *
12153      * <p>The subscriptions which the identification would be based on, are all the active
12154      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12155      *
12156      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
12157      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12158      *
12159      * @param number - the number to look up
12160      * @return {@code true} if the given number is an emergency number or it simply starts with
12161      * the same digits of any current emergency number based on current locale, sim, modem and
12162      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
12163      * have the required permission/privileges
12164      * @throws IllegalStateException if the Telephony process is not currently available.
12165      * @hide
12166      */
12167     @SystemApi
12168     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isPotentialEmergencyNumber(@onNull String number)12169     public boolean isPotentialEmergencyNumber(@NonNull String number) {
12170         try {
12171             ITelephony telephony = getITelephony();
12172             if (telephony != null) {
12173                 return telephony.isEmergencyNumber(number, false);
12174             } else {
12175                 throw new IllegalStateException("telephony service is null.");
12176             }
12177         } catch (RemoteException ex) {
12178             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
12179             ex.rethrowAsRuntimeException();
12180         }
12181         return false;
12182     }
12183 
12184     /**
12185      * Returns the emergency number database version.
12186      *
12187      * <p>Requires Permission:
12188      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12189      *
12190      * @hide
12191      */
12192     @TestApi
12193     @SystemApi
12194     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyNumberDbVersion()12195     public int getEmergencyNumberDbVersion() {
12196         try {
12197             ITelephony telephony = getITelephony();
12198             if (telephony != null) {
12199                 return telephony.getEmergencyNumberDbVersion(getSubId());
12200             }
12201         } catch (RemoteException ex) {
12202             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
12203             ex.rethrowAsRuntimeException();
12204         }
12205         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
12206     }
12207 
12208     /** @hide */
12209     @Retention(RetentionPolicy.SOURCE)
12210     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
12211             SET_OPPORTUNISTIC_SUB_SUCCESS,
12212             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
12213             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
12214             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
12215             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
12216     public @interface SetOpportunisticSubscriptionResult {}
12217 
12218     /**
12219      * No error. Operation succeeded.
12220      */
12221     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
12222 
12223     /**
12224      * Validation failed when trying to switch to preferred subscription.
12225      */
12226     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
12227 
12228     /**
12229      * The subscription is not valid. It must be an active opportunistic subscription.
12230      */
12231     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
12232 
12233     /**
12234      * The subscription is not valid. It must be an opportunistic subscription.
12235      */
12236     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
12237 
12238     /**
12239      * Subscription service happened remote exception.
12240      */
12241     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
12242 
12243 
12244     /** @hide */
12245     @Retention(RetentionPolicy.SOURCE)
12246     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
12247             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
12248             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
12249             UPDATE_AVAILABLE_NETWORKS_ABORTED,
12250             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
12251             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
12252             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
12253             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
12254             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
12255             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
12256             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
12257             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED})
12258     public @interface UpdateAvailableNetworksResult {}
12259 
12260     /**
12261      * No error. Operation succeeded.
12262      */
12263     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
12264 
12265     /**
12266      * There is a unknown failure happened.
12267      */
12268     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
12269 
12270     /**
12271      * The request is aborted.
12272      */
12273     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
12274 
12275     /**
12276      * The parameter passed in is invalid.
12277      */
12278     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
12279 
12280     /**
12281      * No carrier privilege.
12282      */
12283     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
12284 
12285     /**
12286      * Disable modem fail.
12287      */
12288     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
12289 
12290     /**
12291      * Enable modem fail.
12292      */
12293     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
12294 
12295     /**
12296      * Carrier app does not support multiple available networks.
12297      */
12298     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
12299 
12300     /**
12301      * The subscription is not valid. It must be an opportunistic subscription.
12302      */
12303     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
12304 
12305     /**
12306      * There is no OpportunisticNetworkService.
12307      */
12308     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
12309 
12310     /**
12311      * OpportunisticNetworkService is disabled.
12312      */
12313     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
12314 
12315     /**
12316      * Set preferred opportunistic data subscription id.
12317      *
12318      * Switch internet data to preferred opportunistic data subscription id. This api
12319      * can result in lose of internet connectivity for short period of time while internet data
12320      * is handed over.
12321      * <p>Requires that the calling app has carrier privileges on both primary and
12322      * secondary subscriptions (see
12323      * {@link #hasCarrierPrivileges}), or has permission
12324      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12325      *
12326      * @param subId which opportunistic subscription
12327      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
12328      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
12329      * @param needValidation whether validation is needed before switch happens.
12330      * @param executor The executor of where the callback will execute.
12331      * @param callback Callback will be triggered once it succeeds or failed.
12332      *                 See {@link TelephonyManager.SetOpportunisticSubscriptionResult}
12333      *                 for more details. Pass null if don't care about the result.
12334      */
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)12335     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
12336             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
12337         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12338         try {
12339             IOns iOpportunisticNetworkService = getIOns();
12340             if (iOpportunisticNetworkService == null) {
12341                 if (executor == null || callback == null) {
12342                     return;
12343                 }
12344                 final long identity = Binder.clearCallingIdentity();
12345                 try {
12346                     executor.execute(() -> {
12347                         if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
12348                             callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
12349                         } else {
12350                             callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
12351                         }
12352                     });
12353                 } finally {
12354                     Binder.restoreCallingIdentity(identity);
12355                 }
12356                 return;
12357             }
12358             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
12359                 @Override
12360                 public void onComplete(int result) {
12361                     if (executor == null || callback == null) {
12362                         return;
12363                     }
12364                     final long identity = Binder.clearCallingIdentity();
12365                     try {
12366                         executor.execute(() -> {
12367                             callback.accept(result);
12368                         });
12369                     } finally {
12370                         Binder.restoreCallingIdentity(identity);
12371                     }
12372                 }
12373             };
12374 
12375             iOpportunisticNetworkService
12376                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
12377                             pkgForDebug);
12378         } catch (RemoteException ex) {
12379             Rlog.e(TAG, "setPreferredDataSubscriptionId RemoteException", ex);
12380         }
12381         return;
12382     }
12383 
12384     /**
12385      * Get preferred opportunistic data subscription Id
12386      *
12387      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
12388      * or has either READ_PRIVILEGED_PHONE_STATE
12389      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
12390      * @return subId preferred opportunistic subscription id or
12391      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
12392      * subscription id
12393      *
12394      */
12395     @RequiresPermission(anyOf = {
12396             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
12397             android.Manifest.permission.READ_PHONE_STATE
12398     })
getPreferredOpportunisticDataSubscription()12399     public int getPreferredOpportunisticDataSubscription() {
12400         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12401         String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
12402         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
12403         try {
12404             IOns iOpportunisticNetworkService = getIOns();
12405             if (iOpportunisticNetworkService != null) {
12406                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
12407                         packageName, attributionTag);
12408             }
12409         } catch (RemoteException ex) {
12410             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
12411         }
12412         return subId;
12413     }
12414 
12415     /**
12416      * Update availability of a list of networks in the current location.
12417      *
12418      * This api should be called to inform OpportunisticNetwork Service about the availability
12419      * of a network at the current location. This information will be used by OpportunisticNetwork
12420      * service to enable modem stack and to attach to the network. If an empty list is passed,
12421      * it is assumed that no network is available and will result in disabling the modem stack
12422      * to save power. This api do not switch internet data once network attach is completed.
12423      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
12424      * to switch internet data after network attach is complete.
12425      * Requires that the calling app has carrier privileges on both primary and
12426      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
12427      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12428      * @param availableNetworks is a list of available network information.
12429      * @param executor The executor of where the callback will execute.
12430      * @param callback Callback will be triggered once it succeeds or failed.
12431      *
12432      */
12433     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)12434     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
12435             @Nullable @CallbackExecutor Executor executor,
12436             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
12437         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12438         try {
12439             IOns iOpportunisticNetworkService = getIOns();
12440             if (iOpportunisticNetworkService == null || availableNetworks == null) {
12441                 if (executor == null || callback == null) {
12442                     return;
12443                 }
12444                 if (iOpportunisticNetworkService == null) {
12445                     final long identity = Binder.clearCallingIdentity();
12446                     try {
12447                         executor.execute(() -> {
12448                             if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
12449                                 callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
12450                             } else {
12451                                 callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
12452                             }
12453                         });
12454                     } finally {
12455                         Binder.restoreCallingIdentity(identity);
12456                     }
12457                 } else {
12458                     final long identity = Binder.clearCallingIdentity();
12459                     try {
12460                         executor.execute(() -> {
12461                             callback.accept(UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS);
12462                         });
12463                     } finally {
12464                         Binder.restoreCallingIdentity(identity);
12465                     }
12466                 }
12467                 return;
12468             }
12469             IUpdateAvailableNetworksCallback callbackStub =
12470                     new IUpdateAvailableNetworksCallback.Stub() {
12471                         @Override
12472                         public void onComplete(int result) {
12473                             if (executor == null || callback == null) {
12474                                 return;
12475                             }
12476                             final long identity = Binder.clearCallingIdentity();
12477                             try {
12478                                 executor.execute(() -> {
12479                                     callback.accept(result);
12480                                 });
12481                             } finally {
12482                                 Binder.restoreCallingIdentity(identity);
12483                             }
12484                         }
12485                     };
12486             iOpportunisticNetworkService.updateAvailableNetworks(availableNetworks, callbackStub,
12487                     pkgForDebug);
12488         } catch (RemoteException ex) {
12489             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
12490         }
12491     }
12492 
12493     /**
12494      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
12495      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
12496      * For example, we will disable a modem when user or system believes the corresponding SIM
12497      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
12498      *
12499      * Requires that the calling app has permission
12500      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12501      * @param slotIndex which corresponding modem will operate on.
12502      * @param enable whether to enable or disable the modem stack.
12503      * @return whether the operation is successful.
12504      *
12505      * @hide
12506      */
12507     @SystemApi
12508     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableModemForSlot(int slotIndex, boolean enable)12509     public boolean enableModemForSlot(int slotIndex, boolean enable) {
12510         boolean ret = false;
12511         try {
12512             ITelephony telephony = getITelephony();
12513             if (telephony != null) {
12514                 ret = telephony.enableModemForSlot(slotIndex, enable);
12515             }
12516         } catch (RemoteException ex) {
12517             Log.e(TAG, "enableModem RemoteException", ex);
12518         }
12519         return ret;
12520     }
12521 
12522     /**
12523      * It indicates whether modem is enabled or not per slot.
12524      * It's the corresponding status of TelephonyManager.enableModemForSlot.
12525      *
12526      * <p>Requires Permission:
12527      * READ_PRIVILEGED_PHONE_STATE or
12528      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12529      * @param slotIndex which slot it's checking.
12530      */
12531     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isModemEnabledForSlot(int slotIndex)12532     public boolean isModemEnabledForSlot(int slotIndex) {
12533         try {
12534             ITelephony telephony = getITelephony();
12535             if (telephony != null) {
12536                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
12537                         mContext.getAttributionTag());
12538             }
12539         } catch (RemoteException ex) {
12540             Log.e(TAG, "enableModem RemoteException", ex);
12541         }
12542         return false;
12543     }
12544 
12545     /**
12546      * Broadcast intent action for network country code changes.
12547      *
12548      * <p>
12549      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
12550      * network returned by {@link #getNetworkCountryIso()}.
12551      *
12552      * <p>There may be a delay of several minutes before reporting that no country is detected.
12553      *
12554      * @see #EXTRA_NETWORK_COUNTRY
12555      * @see #getNetworkCountryIso()
12556      */
12557     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
12558             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
12559 
12560     /**
12561      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
12562      * the country code in ISO-3166-1 alpha-2 format.
12563      * <p class="note">
12564      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
12565      */
12566     public static final String EXTRA_NETWORK_COUNTRY =
12567             "android.telephony.extra.NETWORK_COUNTRY";
12568 
12569     /**
12570      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
12571      * last known the country code in ISO-3166-1 alpha-2 format.
12572      * <p class="note">
12573      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
12574      *
12575      * @hide
12576      */
12577     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
12578             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
12579 
12580     /**
12581      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
12582      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
12583      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
12584      * policies of the carrier.
12585      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
12586      * access to the network.
12587      *
12588      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
12589      * otherwise.
12590      *
12591      * @hide
12592      */
12593     @SystemApi
12594     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)12595     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
12596         try {
12597             ITelephony service = getITelephony();
12598             if (service != null) {
12599                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
12600             }
12601         } catch (RemoteException e) {
12602             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
12603         }
12604     }
12605 
12606     /**
12607      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12608      * Standby or Dual Active) is supported.
12609      */
12610     public static final int MULTISIM_ALLOWED = 0;
12611 
12612     /**
12613      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12614      * Standby or Dual Active) is not supported by the hardware.
12615      */
12616     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
12617 
12618     /**
12619      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12620      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
12621      */
12622     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
12623 
12624     /** @hide */
12625     @Retention(RetentionPolicy.SOURCE)
12626     @IntDef(prefix = {"MULTISIM_"},
12627             value = {
12628                     MULTISIM_ALLOWED,
12629                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
12630                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
12631             })
12632     public @interface IsMultiSimSupportedResult {}
12633 
12634     /**
12635      * Returns if the usage of multiple SIM cards at the same time to register on the network
12636      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
12637      *
12638      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12639      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12640      *
12641      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
12642      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
12643      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
12644      * functionality is restricted by the carrier.
12645      */
12646     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12647     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12648     @IsMultiSimSupportedResult
isMultiSimSupported()12649     public int isMultiSimSupported() {
12650         if (getSupportedModemCount() < 2) {
12651             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
12652         }
12653         try {
12654             ITelephony service = getITelephony();
12655             if (service != null) {
12656                 return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
12657             }
12658         } catch (RemoteException e) {
12659             Log.e(TAG, "isMultiSimSupported RemoteException", e);
12660         }
12661         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
12662     }
12663 
12664     /**
12665      * Switch configs to enable multi-sim or switch back to single-sim
12666      * <p>Requires Permission:
12667      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
12668      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12669      *
12670      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
12671      * to single-sim
12672      *
12673      * @param numOfSims number of live SIMs we want to switch to
12674      * @throws android.os.RemoteException
12675      */
12676     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12677     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchMultiSimConfig(int numOfSims)12678     public void switchMultiSimConfig(int numOfSims) {
12679         try {
12680             ITelephony telephony = getITelephony();
12681             if (telephony != null) {
12682                 telephony.switchMultiSimConfig(numOfSims);
12683             }
12684         } catch (RemoteException ex) {
12685             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
12686         }
12687     }
12688 
12689     /**
12690      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
12691      * trigger device reboot.
12692      * The modem configuration change refers to switching from single SIM configuration to DSDS
12693      * or the other way around.
12694      *
12695      *  <p>Requires Permission:
12696      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
12697      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12698      *
12699      * @return {@code true} if reboot will be triggered after making changes to modem
12700      * configurations, otherwise return {@code false}.
12701      */
12702     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
doesSwitchMultiSimConfigTriggerReboot()12703     public boolean doesSwitchMultiSimConfigTriggerReboot() {
12704         try {
12705             ITelephony service = getITelephony();
12706             if (service != null) {
12707                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
12708                         getOpPackageName(), getAttributionTag());
12709             }
12710         } catch (RemoteException e) {
12711             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
12712         }
12713         return false;
12714     }
12715 
12716     /**
12717      * Retrieve the Radio HAL Version for this device.
12718      *
12719      * Get the HAL version for the IRadio interface for test purposes.
12720      *
12721      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
12722      *
12723      * @hide
12724      */
12725     @UnsupportedAppUsage
12726     @TestApi
getRadioHalVersion()12727     public Pair<Integer, Integer> getRadioHalVersion() {
12728         try {
12729             ITelephony service = getITelephony();
12730             if (service != null) {
12731                 int version = service.getRadioHalVersion();
12732                 if (version == -1) return new Pair<Integer, Integer>(-1, -1);
12733                 return new Pair<Integer, Integer>(version / 100, version % 100);
12734             }
12735         } catch (RemoteException e) {
12736             Log.e(TAG, "getRadioHalVersion() RemoteException", e);
12737         }
12738         return new Pair<Integer, Integer>(-1, -1);
12739     }
12740 
12741     /**
12742      * Get the calling application status about carrier privileges for the subscription created
12743      * in TelephonyManager. Used by Telephony Module for permission checking.
12744      *
12745      * @param uid Uid to check.
12746      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
12747      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
12748      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
12749      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
12750      *
12751      * @hide
12752      */
12753     @SystemApi
12754     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierPrivilegeStatus(int uid)12755     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
12756         try {
12757             ITelephony telephony = getITelephony();
12758             if (telephony != null) {
12759                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
12760             }
12761         } catch (RemoteException ex) {
12762             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
12763         }
12764         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
12765     }
12766 
12767     /**
12768      * Returns a list of APNs set as overrides by the device policy manager via
12769      * {@link #addDevicePolicyOverrideApn}.
12770      * This method must only be called from the system or phone processes.
12771      *
12772      * @param context Context to use.
12773      * @return {@link List} of APNs that have been set as overrides.
12774      * @throws {@link SecurityException} if the caller is not the system or phone process.
12775      * @hide
12776      */
12777     @TestApi
12778     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)12779     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
12780         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
12781             if (cursor == null) {
12782                 return Collections.emptyList();
12783             }
12784             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
12785             cursor.moveToPosition(-1);
12786             while (cursor.moveToNext()) {
12787                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
12788                 apnList.add(apn);
12789             }
12790             return apnList;
12791         }
12792     }
12793 
12794     /**
12795      * Used by the device policy manager to add a new override APN.
12796      * This method must only be called from the system or phone processes.
12797      *
12798      * @param context Context to use.
12799      * @param apnSetting The {@link ApnSetting} describing the new APN.
12800      * @return An integer, corresponding to a primary key in a database, that allows the caller to
12801      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
12802      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
12803      *         failed.
12804      * @throws {@link SecurityException} if the caller is not the system or phone process.
12805      * @hide
12806      */
12807     @TestApi
12808     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)12809     public int addDevicePolicyOverrideApn(@NonNull Context context,
12810             @NonNull ApnSetting apnSetting) {
12811         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
12812 
12813         int resultId = INVALID_APN_ID;
12814         if (resultUri != null) {
12815             try {
12816                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
12817             } catch (NumberFormatException e) {
12818                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
12819                         + resultUri.getLastPathSegment());
12820             }
12821         }
12822         return resultId;
12823     }
12824 
12825     /**
12826      * Used by the device policy manager to modify an override APN.
12827      * This method must only be called from the system or phone processes.
12828      *
12829      * @param context Context to use.
12830      * @param apnId The integer key of the APN to modify, as returned by
12831      *              {@link #addDevicePolicyOverrideApn}
12832      * @param apnSetting The {@link ApnSetting} describing the updated APN.
12833      * @return {@code true} if successful, {@code false} otherwise.
12834      * @throws {@link SecurityException} if the caller is not the system or phone process.
12835      * @hide
12836      */
12837     @TestApi
12838     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)12839     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
12840             @NonNull ApnSetting apnSetting) {
12841         return context.getContentResolver().update(
12842                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
12843                 apnSetting.toContentValues(), null, null) > 0;
12844     }
12845 
12846     /**
12847      * Return whether data is enabled for certain APN type. This will tell if framework will accept
12848      * corresponding network requests on a subId.
12849      *
12850      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
12851      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
12852      *
12853      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
12854      * It will return true if:
12855      *
12856      *  1) User data is turned on, or
12857      *  2) APN is un-metered for this subscription, or
12858      *  3) APN type is whitelisted. E.g. MMS is whitelisted if
12859      *  {@link #setAlwaysAllowMmsData(boolean)} is turned on.
12860      *
12861      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
12862      * @return whether data is enabled for a apn type.
12863      *
12864      * @hide
12865      */
12866     @SystemApi
12867     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataEnabledForApn(@pnType int apnType)12868     public boolean isDataEnabledForApn(@ApnType int apnType) {
12869         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12870         try {
12871             ITelephony service = getITelephony();
12872             if (service != null) {
12873                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
12874             }
12875         } catch (RemoteException ex) {
12876             if (!isSystemProcess()) {
12877                 ex.rethrowAsRuntimeException();
12878             }
12879         }
12880         return false;
12881     }
12882 
12883     /**
12884      * Whether an APN type is metered or not. It will be evaluated with the subId associated
12885      * with the TelephonyManager instance.
12886      *
12887      * @hide
12888      */
12889     @SystemApi
12890     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApnMetered(@pnType int apnType)12891     public boolean isApnMetered(@ApnType int apnType) {
12892         try {
12893             ITelephony service = getITelephony();
12894             if (service != null) {
12895                 return service.isApnMetered(apnType, getSubId());
12896             }
12897         } catch (RemoteException ex) {
12898             if (!isSystemProcess()) {
12899                 ex.rethrowAsRuntimeException();
12900             }
12901         }
12902         return true;
12903     }
12904 
12905     /**
12906      * Specify which bands modem's background scan must act on.
12907      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
12908      * Otherwise, it scans all bands.
12909      *
12910      * For example, CBRS is only on LTE band 48. By specifying this band,
12911      * modem saves more power.
12912      *
12913      * @param specifiers which bands to scan.
12914      * @param executor The executor to execute the callback on
12915      * @param callback The callback that gets invoked when the radio responds to the request. Called
12916      *                 with {@code true} if the request succeeded, {@code false} otherwise.
12917      * @hide
12918      */
12919     @SystemApi
12920     @TestApi
12921     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)12922     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
12923             @NonNull @CallbackExecutor Executor executor,
12924             @NonNull Consumer<Boolean> callback) {
12925         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
12926         Objects.requireNonNull(executor, "Executor must not be null.");
12927         Objects.requireNonNull(callback, "Callback must not be null.");
12928         setSystemSelectionChannelsInternal(specifiers, executor, callback);
12929     }
12930 
12931     /**
12932      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
12933      * used when the caller does not need feedback on the results of the operation.
12934      * @param specifiers which bands to scan.
12935      * @hide
12936      */
12937     @SystemApi
12938     @TestApi
12939     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)12940     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
12941         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
12942         setSystemSelectionChannelsInternal(specifiers, null, null);
12943     }
12944 
12945 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)12946     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
12947             @Nullable @CallbackExecutor Executor executor,
12948             @Nullable Consumer<Boolean> callback) {
12949         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
12950             @Override
12951             public void accept(boolean result) {
12952                 executor.execute(() -> callback.accept(result));
12953             }
12954         };
12955 
12956         try {
12957             ITelephony service = getITelephony();
12958             if (service != null) {
12959                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
12960             }
12961         } catch (RemoteException ex) {
12962             if (!isSystemProcess()) {
12963                 ex.rethrowAsRuntimeException();
12964             }
12965         }
12966     }
12967 
12968     /**
12969      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
12970      *
12971      * @param mccmnc the carrier's mccmnc that you want to match
12972      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
12973      * @param mvnoMatchData the MVNO match data
12974      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
12975      * {@code false} otherwise.
12976      *
12977      * {@hide}
12978      */
12979     @SystemApi
12980     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
matchesCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)12981     public boolean matchesCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
12982             @Nullable String mvnoMatchData) {
12983         try {
12984             if (!mccmnc.equals(getSimOperator())) {
12985                 return false;
12986             }
12987             ITelephony service = getITelephony();
12988             if (service != null) {
12989                 return service.isMvnoMatched(getSubId(), mvnoType, mvnoMatchData);
12990             }
12991         } catch (RemoteException ex) {
12992             if (!isSystemProcess()) {
12993                 ex.rethrowAsRuntimeException();
12994             }
12995         }
12996         return false;
12997     }
12998 
12999     /**
13000      * Gets the voice call forwarding info {@link CallForwardingInfo}, given the call forward
13001      * reason.
13002      *
13003      * @param callForwardingReason the call forwarding reasons
13004      *
13005      * @throws IllegalArgumentException if callForwardingReason is not any of
13006      * {@link CallForwardingInfo.REASON_UNCONDITIONAL}, {@link CallForwardingInfo.REASON_BUSY},
13007      * {@link CallForwardingInfo.REASON_NO_REPLY}, {@link CallForwardingInfo.REASON_NOT_REACHABLE},
13008      * {@link CallForwardingInfo.REASON_ALL}, {@link CallForwardingInfo.REASON_ALL_CONDITIONAL}
13009      *
13010      * @return {@link CallForwardingInfo} with the status {@link CallForwardingInfo#STATUS_ACTIVE}
13011      * or {@link CallForwardingInfo#STATUS_INACTIVE} and the target phone number to forward calls
13012      * to, if it's available. Otherwise, it will return a {@link CallForwardingInfo} with status
13013      * {@link CallForwardingInfo#STATUS_UNKNOWN_ERROR},
13014      * {@link CallForwardingInfo#STATUS_NOT_SUPPORTED},
13015      * or {@link CallForwardingInfo#STATUS_FDN_CHECK_FAILURE} depending on the situation.
13016      *
13017      * @hide
13018      */
13019     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13020     @NonNull
getCallForwarding(@allForwardingReason int callForwardingReason)13021     public CallForwardingInfo getCallForwarding(@CallForwardingReason int callForwardingReason) {
13022         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
13023                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
13024             throw new IllegalArgumentException("callForwardingReason is out of range");
13025         }
13026         try {
13027             ITelephony telephony = getITelephony();
13028             if (telephony != null) {
13029                 return telephony.getCallForwarding(getSubId(), callForwardingReason);
13030             }
13031         } catch (RemoteException ex) {
13032             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
13033         } catch (NullPointerException ex) {
13034             Rlog.e(TAG, "getCallForwarding NPE", ex);
13035         }
13036         return new CallForwardingInfo(
13037                 CallForwardingInfo.STATUS_UNKNOWN_ERROR, 0 /* reason */, null /* number */,
13038                         0 /* timeout */);
13039     }
13040 
13041     /**
13042      * Sets the voice call forwarding info including status (enable/disable), call forwarding
13043      * reason, the number to forward, and the timeout before the forwarding is attempted.
13044      *
13045      * @param callForwardingInfo {@link CallForwardingInfo} to setup the call forwarding.
13046      * Enabling if {@link CallForwardingInfo#getStatus()} returns
13047      * {@link CallForwardingInfo#STATUS_ACTIVE}; Disabling if
13048      * {@link CallForwardingInfo#getStatus()} returns {@link CallForwardingInfo#STATUS_INACTIVE}.
13049      *
13050      * @throws IllegalArgumentException if any of the following for parameter callForwardingInfo:
13051      * 0) it is {@code null}.
13052      * 1) {@link CallForwardingInfo#getStatus()} returns neither
13053      * {@link CallForwardingInfo#STATUS_ACTIVE} nor {@link CallForwardingInfo#STATUS_INACTIVE}.
13054      * 2) {@link CallForwardingInfo#getReason()} is not any of
13055      * {@link CallForwardingInfo.REASON_UNCONDITIONAL}, {@link CallForwardingInfo.REASON_BUSY},
13056      * {@link CallForwardingInfo.REASON_NO_REPLY}, {@link CallForwardingInfo.REASON_NOT_REACHABLE},
13057      * {@link CallForwardingInfo.REASON_ALL}, {@link CallForwardingInfo.REASON_ALL_CONDITIONAL}
13058      * 3) {@link CallForwardingInfo#getNumber()} returns {@code null}.
13059      * 4) {@link CallForwardingInfo#getTimeoutSeconds()} doesn't return a positive value.
13060      *
13061      * @return {@code true} to indicate it was set successfully; {@code false} otherwise.
13062      *
13063      * @hide
13064      */
13065     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo)13066     public boolean setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo) {
13067         if (callForwardingInfo == null) {
13068             throw new IllegalArgumentException("callForwardingInfo is null");
13069         }
13070         int callForwardingStatus = callForwardingInfo.getStatus();
13071         if (callForwardingStatus != CallForwardingInfo.STATUS_ACTIVE
13072                 && callForwardingStatus != CallForwardingInfo.STATUS_INACTIVE) {
13073             throw new IllegalArgumentException(
13074                     "callForwardingStatus is neither active nor inactive");
13075         }
13076         int callForwardingReason = callForwardingInfo.getReason();
13077         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
13078                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
13079             throw new IllegalArgumentException("callForwardingReason is out of range");
13080         }
13081         if (callForwardingInfo.getNumber() == null) {
13082             throw new IllegalArgumentException("callForwarding number is null");
13083         }
13084         if (callForwardingInfo.getTimeoutSeconds() <= 0) {
13085             throw new IllegalArgumentException("callForwarding timeout isn't positive");
13086         }
13087         try {
13088             ITelephony telephony = getITelephony();
13089             if (telephony != null) {
13090                 return telephony.setCallForwarding(getSubId(), callForwardingInfo);
13091             }
13092         } catch (RemoteException ex) {
13093             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
13094         } catch (NullPointerException ex) {
13095             Rlog.e(TAG, "setCallForwarding NPE", ex);
13096         }
13097         return false;
13098     }
13099 
13100     /**
13101      * Indicates the call waiting status is active.
13102      *
13103      * @hide
13104      */
13105     public static final int CALL_WAITING_STATUS_ACTIVE = 1;
13106 
13107     /**
13108      * Indicates the call waiting status is inactive.
13109      *
13110      * @hide
13111      */
13112     public static final int CALL_WAITING_STATUS_INACTIVE = 2;
13113 
13114     /**
13115      * Indicates the call waiting status is with an unknown error.
13116      *
13117      * @hide
13118      */
13119     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
13120 
13121     /**
13122      * Indicates the call waiting is not supported (e.g. called via CDMA).
13123      *
13124      * @hide
13125      */
13126     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
13127 
13128     /**
13129      * Call waiting function status
13130      *
13131      * @hide
13132      */
13133     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
13134         CALL_WAITING_STATUS_ACTIVE,
13135         CALL_WAITING_STATUS_INACTIVE,
13136         CALL_WAITING_STATUS_NOT_SUPPORTED,
13137         CALL_WAITING_STATUS_UNKNOWN_ERROR
13138     })
13139     @Retention(RetentionPolicy.SOURCE)
13140     public @interface CallWaitingStatus {
13141     }
13142 
13143     /**
13144      * Gets the status of voice call waiting function. Call waiting function enables the waiting
13145      * for the incoming call when it reaches the user who is busy to make another call and allows
13146      * users to decide whether to switch to the incoming call.
13147      *
13148      * @return the status of call waiting function.
13149      * @hide
13150      */
13151     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCallWaitingStatus()13152     public @CallWaitingStatus int getCallWaitingStatus() {
13153         try {
13154             ITelephony telephony = getITelephony();
13155             if (telephony != null) {
13156                 return telephony.getCallWaitingStatus(getSubId());
13157             }
13158         } catch (RemoteException ex) {
13159             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
13160         } catch (NullPointerException ex) {
13161             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
13162         }
13163         return CALL_WAITING_STATUS_UNKNOWN_ERROR;
13164     }
13165 
13166     /**
13167      * Sets the status for voice call waiting function. Call waiting function enables the waiting
13168      * for the incoming call when it reaches the user who is busy to make another call and allows
13169      * users to decide whether to switch to the incoming call.
13170      *
13171      * @param isEnable {@code true} to enable; {@code false} to disable.
13172      * @return {@code true} to indicate it was set successfully; {@code false} otherwise.
13173      *
13174      * @hide
13175      */
13176     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallWaitingStatus(boolean isEnable)13177     public boolean setCallWaitingStatus(boolean isEnable) {
13178         try {
13179             ITelephony telephony = getITelephony();
13180             if (telephony != null) {
13181                 return telephony.setCallWaitingStatus(getSubId(), isEnable);
13182             }
13183         } catch (RemoteException ex) {
13184             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
13185         } catch (NullPointerException ex) {
13186             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
13187         }
13188         return false;
13189     }
13190 
13191     /**
13192      * Set allowing mobile data during voice call. This is used for allowing data on the non-default
13193      * data SIM. When a voice call is placed on the non-default data SIM on DSDS devices, users will
13194      * not be able to use mobile data. By calling this API, data will be temporarily enabled on the
13195      * non-default data SIM during the life cycle of the voice call.
13196      *
13197      * @param allow {@code true} if allowing using data during voice call, {@code false} if
13198      * disallowed.
13199      *
13200      * @return {@code true} if operation is successful. otherwise {@code false}.
13201      *
13202      * @throws SecurityException if the caller doesn't have the permission.
13203      *
13204      * @hide
13205      */
13206     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataAllowedDuringVoiceCall(boolean allow)13207     public boolean setDataAllowedDuringVoiceCall(boolean allow) {
13208         try {
13209             ITelephony service = getITelephony();
13210             if (service != null) {
13211                 return service.setDataAllowedDuringVoiceCall(getSubId(), allow);
13212             }
13213         } catch (RemoteException ex) {
13214             // This could happen if binder process crashes.
13215             if (!isSystemProcess()) {
13216                 ex.rethrowAsRuntimeException();
13217             }
13218         }
13219         return false;
13220     }
13221 
13222     /**
13223      * Check whether data is allowed during voice call. This is used for allowing data on the
13224      * non-default data SIM. When a voice call is placed on the non-default data SIM on DSDS
13225      * devices, users will not be able to use mobile data. By calling this API, data will be
13226      * temporarily enabled on the non-default data SIM during the life cycle of the voice call.
13227      *
13228      * @return {@code true} if data is allowed during voice call.
13229      *
13230      * @throws SecurityException if the caller doesn't have the permission.
13231      *
13232      * @hide
13233      */
13234     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataAllowedInVoiceCall()13235     public boolean isDataAllowedInVoiceCall() {
13236         try {
13237             ITelephony service = getITelephony();
13238             if (service != null) {
13239                 return service.isDataAllowedInVoiceCall(getSubId());
13240             }
13241         } catch (RemoteException ex) {
13242             // This could happen if binder process crashes.
13243             if (!isSystemProcess()) {
13244                 ex.rethrowAsRuntimeException();
13245             }
13246         }
13247         return false;
13248     }
13249 
13250     /**
13251      * Set whether the specific sim card always allows MMS connection. If true, MMS network
13252      * request will be accepted by telephony even if user turns "mobile data" off
13253      * on this specific sim card.
13254      *
13255      * @param alwaysAllow whether Mms data is always allowed.
13256      * @return whether operation is successful.
13257      *
13258      * @hide
13259      */
13260     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysAllowMmsData(boolean alwaysAllow)13261     public boolean setAlwaysAllowMmsData(boolean alwaysAllow) {
13262         try {
13263             ITelephony service = getITelephony();
13264             if (service != null) {
13265                 return service.setAlwaysAllowMmsData(getSubId(), alwaysAllow);
13266             }
13267         } catch (RemoteException ex) {
13268             if (!isSystemProcess()) {
13269                 ex.rethrowAsRuntimeException();
13270             }
13271         }
13272         return false;
13273     }
13274 
13275     /**
13276      * The IccLock state or password was changed successfully.
13277      * @hide
13278      */
13279     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
13280 
13281     /**
13282      * Check whether ICC pin lock is enabled.
13283      * This is a sync call which returns the cached pin enabled state.
13284      *
13285      * @return {@code true} if ICC lock enabled, {@code false} if ICC lock disabled.
13286      *
13287      * @throws SecurityException if the caller doesn't have the permission.
13288      *
13289      * @hide
13290      */
13291     @WorkerThread
13292     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13293     @SystemApi
isIccLockEnabled()13294     public boolean isIccLockEnabled() {
13295         try {
13296             ITelephony telephony = getITelephony();
13297             if (telephony != null) {
13298                 return telephony.isIccLockEnabled(getSubId());
13299             }
13300         } catch (RemoteException e) {
13301             Log.e(TAG, "isIccLockEnabled RemoteException", e);
13302         }
13303         return false;
13304     }
13305 
13306     /**
13307      * Set the ICC pin lock enabled or disabled.
13308      *
13309      * If enable/disable ICC pin lock successfully, a value of {@link Integer#MAX_VALUE} is
13310      * returned.
13311      * If an incorrect old password is specified, the return value will indicate how many more
13312      * attempts the user can make to change the password before the SIM is locked.
13313      * Using PUK code to unlock SIM if enter the incorrect old password 3 times.
13314      *
13315      * @param enabled    "true" for locked, "false" for unlocked.
13316      * @param password   needed to change the ICC pin state, aka. Pin1
13317      * @return an integer representing the status of IccLock enabled or disabled in the following
13318      * three cases:
13319      *   - {@link TelephonyManager#CHANGE_ICC_LOCK_SUCCESS} if enabled or disabled IccLock
13320      *   successfully.
13321      *   - Positive number and zero for remaining password attempts.
13322      *   - Negative number for other failure cases (such like enabling/disabling PIN failed).
13323      *
13324      * @throws SecurityException if the caller doesn't have the permission.
13325      *
13326      * @hide
13327      */
13328     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setIccLockEnabled(boolean enabled, @NonNull String password)13329     public int setIccLockEnabled(boolean enabled, @NonNull String password) {
13330         checkNotNull(password, "setIccLockEnabled password can't be null.");
13331         try {
13332             ITelephony telephony = getITelephony();
13333             if (telephony != null) {
13334                 return telephony.setIccLockEnabled(getSubId(), enabled, password);
13335             }
13336         } catch (RemoteException e) {
13337             Log.e(TAG, "setIccLockEnabled RemoteException", e);
13338         }
13339         return 0;
13340     }
13341 
13342     /**
13343      * Change the ICC password used in ICC pin lock.
13344      *
13345      * If the password was changed successfully, a value of {@link Integer#MAX_VALUE} is returned.
13346      * If an incorrect old password is specified, the return value will indicate how many more
13347      * attempts the user can make to change the password before the SIM is locked.
13348      * Using PUK code to unlock SIM if enter the incorrect old password 3 times.
13349      *
13350      * @param oldPassword is the old password
13351      * @param newPassword is the new password
13352      * @return an integer representing the status of IccLock changed in the following three cases:
13353      *   - {@link TelephonyManager#CHANGE_ICC_LOCK_SUCCESS} if changed IccLock successfully.
13354      *   - Positive number and zero for remaining password attempts.
13355      *   - Negative number for other failure cases (such like enabling/disabling PIN failed).
13356      *
13357      * @throws SecurityException if the caller doesn't have the permission.
13358      *
13359      * @hide
13360      */
13361     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
changeIccLockPassword(@onNull String oldPassword, @NonNull String newPassword)13362     public int changeIccLockPassword(@NonNull String oldPassword, @NonNull String newPassword) {
13363         checkNotNull(oldPassword, "changeIccLockPassword oldPassword can't be null.");
13364         checkNotNull(newPassword, "changeIccLockPassword newPassword can't be null.");
13365         try {
13366             ITelephony telephony = getITelephony();
13367             if (telephony != null) {
13368                 return telephony.changeIccLockPassword(getSubId(), oldPassword, newPassword);
13369             }
13370         } catch (RemoteException e) {
13371             Log.e(TAG, "changeIccLockPassword RemoteException", e);
13372         }
13373         return 0;
13374     }
13375 
13376     /**
13377      * Called when userActivity is signalled in the power manager.
13378      * This should only be called from system Uid.
13379      * @hide
13380      */
13381     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
notifyUserActivity()13382     public void notifyUserActivity() {
13383         try {
13384             ITelephony service = getITelephony();
13385             if (service != null) {
13386                 service.userActivity();
13387             }
13388         } catch (RemoteException e) {
13389             // one-way notification, if telephony is not available, it is okay to not throw
13390             // exception here.
13391             Log.w(TAG, "notifyUserActivity exception: " + e.getMessage());
13392         }
13393     }
13394 
13395     private static class DeathRecipient implements IBinder.DeathRecipient {
13396         @Override
binderDied()13397         public void binderDied() {
13398             resetServiceCache();
13399         }
13400     }
13401 
13402    /**
13403     * Reset everything in the service cache; if one handle died then they are
13404     * all probably broken.
13405     * @hide
13406     */
resetServiceCache()13407     private static void resetServiceCache() {
13408         synchronized (sCacheLock) {
13409             if (sISub != null) {
13410                 sISub.asBinder().unlinkToDeath(sServiceDeath, 0);
13411                 sISub = null;
13412                 SubscriptionManager.clearCaches();
13413             }
13414             if (sISms != null) {
13415                 sISms.asBinder().unlinkToDeath(sServiceDeath, 0);
13416                 sISms = null;
13417             }
13418             if (sIPhoneSubInfo != null) {
13419                 sIPhoneSubInfo.asBinder().unlinkToDeath(sServiceDeath, 0);
13420                 sIPhoneSubInfo = null;
13421             }
13422         }
13423     }
13424 
13425    /**
13426     * @hide
13427     */
getSubscriberInfoService()13428     static IPhoneSubInfo getSubscriberInfoService() {
13429         // Keeps cache disabled until test fixes are checked into AOSP.
13430         if (!sServiceHandleCacheEnabled) {
13431             return IPhoneSubInfo.Stub.asInterface(
13432                 TelephonyFrameworkInitializer
13433                         .getTelephonyServiceManager()
13434                         .getPhoneSubServiceRegisterer()
13435                         .get());
13436         }
13437 
13438         if (sIPhoneSubInfo == null) {
13439             IPhoneSubInfo temp = IPhoneSubInfo.Stub.asInterface(
13440                     TelephonyFrameworkInitializer
13441                         .getTelephonyServiceManager()
13442                         .getPhoneSubServiceRegisterer()
13443                         .get());
13444             synchronized (sCacheLock) {
13445                 if (sIPhoneSubInfo == null && temp != null) {
13446                     try {
13447                         sIPhoneSubInfo = temp;
13448                         sIPhoneSubInfo.asBinder().linkToDeath(sServiceDeath, 0);
13449                     } catch (Exception e) {
13450                         // something has gone horribly wrong
13451                         sIPhoneSubInfo = null;
13452                     }
13453                 }
13454             }
13455         }
13456         return sIPhoneSubInfo;
13457     }
13458 
13459    /**
13460     * @hide
13461     */
getSubscriptionService()13462     static ISub getSubscriptionService() {
13463         // Keeps cache disabled until test fixes are checked into AOSP.
13464         if (!sServiceHandleCacheEnabled) {
13465             return ISub.Stub.asInterface(
13466                     TelephonyFrameworkInitializer
13467                             .getTelephonyServiceManager()
13468                             .getSubscriptionServiceRegisterer()
13469                             .get());
13470         }
13471 
13472         if (sISub == null) {
13473             ISub temp = ISub.Stub.asInterface(
13474                     TelephonyFrameworkInitializer
13475                             .getTelephonyServiceManager()
13476                             .getSubscriptionServiceRegisterer()
13477                             .get());
13478             synchronized (sCacheLock) {
13479                 if (sISub == null && temp != null) {
13480                     try {
13481                         sISub = temp;
13482                         sISub.asBinder().linkToDeath(sServiceDeath, 0);
13483                     } catch (Exception e) {
13484                         // something has gone horribly wrong
13485                         sISub = null;
13486                     }
13487                 }
13488             }
13489         }
13490         return sISub;
13491     }
13492 
13493     /**
13494     * @hide
13495     */
getSmsService()13496     static ISms getSmsService() {
13497         // Keeps cache disabled until test fixes are checked into AOSP.
13498         if (!sServiceHandleCacheEnabled) {
13499             return ISms.Stub.asInterface(
13500                     TelephonyFrameworkInitializer
13501                             .getTelephonyServiceManager()
13502                             .getSmsServiceRegisterer()
13503                             .get());
13504         }
13505 
13506         if (sISms == null) {
13507             ISms temp = ISms.Stub.asInterface(
13508                     TelephonyFrameworkInitializer
13509                             .getTelephonyServiceManager()
13510                             .getSmsServiceRegisterer()
13511                             .get());
13512             synchronized (sCacheLock) {
13513                 if (sISms == null && temp != null) {
13514                     try {
13515                         sISms = temp;
13516                         sISms.asBinder().linkToDeath(sServiceDeath, 0);
13517                     } catch (Exception e) {
13518                         // something has gone horribly wrong
13519                         sISms = null;
13520                     }
13521                 }
13522             }
13523         }
13524         return sISms;
13525     }
13526 
13527     /**
13528      * Disables service handle caching for tests that utilize mock services.
13529      * @hide
13530      */
13531     @VisibleForTesting
disableServiceHandleCaching()13532     public static void disableServiceHandleCaching() {
13533         sServiceHandleCacheEnabled = false;
13534     }
13535 
13536     /**
13537      * Reenables service handle caching.
13538      * @hide
13539      */
13540     @VisibleForTesting
enableServiceHandleCaching()13541     public static void enableServiceHandleCaching() {
13542         sServiceHandleCacheEnabled = true;
13543     }
13544 
13545     /**
13546      * Whether device can connect to 5G network when two SIMs are active.
13547      * @hide
13548      * TODO b/153669716: remove or make system API.
13549      */
canConnectTo5GInDsdsMode()13550     public boolean canConnectTo5GInDsdsMode() {
13551         ITelephony telephony = getITelephony();
13552         if (telephony == null) return true;
13553         try {
13554             return telephony.canConnectTo5GInDsdsMode();
13555         } catch (RemoteException ex) {
13556             return true;
13557         } catch (NullPointerException ex) {
13558             return true;
13559         }
13560     }
13561 }
13562