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      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1498      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1499      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1500      *
1501      * @hide
1502      */
1503     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1504             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1505 
1506     /** @hide */
1507     @IntDef({
1508             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1509             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1510     })
1511     @Retention(RetentionPolicy.SOURCE)
1512     public @interface SimCombinationWarningType{}
1513 
1514     /**
1515      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1516      * to indicate there's no SIM combination warning.
1517      * @hide
1518      */
1519     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1520 
1521     /**
1522      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1523      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1524      * @hide
1525      */
1526     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1527 
1528     /**
1529      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1530      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1531      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1532      * name will be "operator1 & operator2".
1533      *
1534      * @hide
1535      */
1536     public static final String EXTRA_SIM_COMBINATION_NAMES =
1537             "android.telephony.extra.SIM_COMBINATION_NAMES";
1538 
1539     /**
1540      * <p>Broadcast Action: The emergency callback mode is changed.
1541      * <ul>
1542      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1543      *   false=ECM off</li>
1544      * </ul>
1545      * <p class="note">
1546      * You can <em>not</em> receive this through components declared
1547      * in manifests, only by explicitly registering for it with
1548      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1549      * android.content.IntentFilter) Context.registerReceiver()}.
1550      *
1551      * <p class="note">This is a protected intent that can only be sent by the system.
1552      *
1553      * @see #EXTRA_PHONE_IN_ECM_STATE
1554      *
1555      * @hide
1556      */
1557     @SystemApi
1558     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1559     @SuppressLint("ActionValue")
1560     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1561             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1562 
1563 
1564     /**
1565      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1566      * Indicates whether the phone is in an emergency phone state.
1567      *
1568      * @hide
1569      */
1570     @SystemApi
1571     public static final String EXTRA_PHONE_IN_ECM_STATE =
1572             "android.telephony.extra.PHONE_IN_ECM_STATE";
1573 
1574     /**
1575      * <p>Broadcast Action: when data connections get redirected with validation failure.
1576      * intended for sim/account status checks and only sent to the specified carrier app
1577      * The intent will have the following extra values:</p>
1578      * <ul>
1579      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1580      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1581      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>redirection url string</dd>
1582      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1583      * </ul>
1584      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1585      * @hide
1586      */
1587     @SuppressLint("ActionValue")
1588     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1589             "com.android.internal.telephony.CARRIER_SIGNAL_REDIRECTED";
1590 
1591     /**
1592      * <p>Broadcast Action: when data connections setup fails.
1593      * intended for sim/account status checks and only sent to the specified carrier app
1594      * The intent will have the following extra values:</p>
1595      * <ul>
1596      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1597      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1598      *   <li>{@link #EXTRA_ERROR_CODE}</li><dd>A integer with dataFailCause.</dd>
1599      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1600      * </ul>
1601      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1602      * @hide
1603      */
1604     @SuppressLint("ActionValue")
1605     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1606             "com.android.internal.telephony.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1607 
1608     /**
1609      * <p>Broadcast Action: when pco value is available.
1610      * intended for sim/account status checks and only sent to the specified carrier app
1611      * The intent will have the following extra values:</p>
1612      * <ul>
1613      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1614      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1615      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>A string with the protocol of the apn connection
1616      *      (IP,IPV6, IPV4V6)</dd>
1617      *   <li>{@link #EXTRA_APN_PROTOCOL_INT}</li><dd>A integer with the protocol of the apn
1618      *      connection (IP,IPV6, IPV4V6)</dd>
1619      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the pco id for the data.</dd>
1620      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of pco data read from modem.</dd>
1621      *   <li>subId</li><dd>Sub Id which associated the data connection.</dd>
1622      * </ul>
1623      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1624      * @hide
1625      */
1626     @SuppressLint("ActionValue")
1627     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1628             "com.android.internal.telephony.CARRIER_SIGNAL_PCO_VALUE";
1629 
1630     /**
1631      * <p>Broadcast Action: when system default network available/unavailable with
1632      * carrier-disabled mobile data. Intended for carrier apps to set/reset carrier actions when
1633      * other network becomes system default network, Wi-Fi for example.
1634      * The intent will have the following extra values:</p>
1635      * <ul>
1636      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1637      *   <dd>A boolean indicates default network available.</dd>
1638      *   <li>subId</li><dd>Sub Id which associated the default data.</dd>
1639      * </ul>
1640      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1641      * @hide
1642      */
1643     @SuppressLint("ActionValue")
1644     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1645             "com.android.internal.telephony.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1646 
1647     /**
1648      * <p>Broadcast Action: when framework reset all carrier actions on sim load or absent.
1649      * intended for carrier apps clean up (clear UI e.g.) and only sent to the specified carrier app
1650      * The intent will have the following extra values:</p>
1651      * <ul>
1652      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1653      * </ul>
1654      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1655      * @hide
1656      */
1657     @SuppressLint("ActionValue")
1658     public static final String ACTION_CARRIER_SIGNAL_RESET =
1659             "com.android.internal.telephony.CARRIER_SIGNAL_RESET";
1660 
1661     // CARRIER_SIGNAL_ACTION extra keys
1662     /**
1663      *  An string extra of redirected url upon {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
1664      *  @hide
1665      */
1666     @SuppressLint("ActionValue")
1667     public static final String EXTRA_REDIRECTION_URL = "redirectionUrl";
1668 
1669     /**
1670      *  An integer extra of error code upon {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}.
1671      *  Check {@link DataFailCause} for all possible values.
1672      *  @hide
1673      */
1674     @SuppressLint("ActionValue")
1675     public static final String EXTRA_ERROR_CODE = "errorCode";
1676 
1677     /**
1678      *  An string extra of corresponding apn type upon
1679      *  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1680      *  {@link #ACTION_CARRIER_SIGNAL_REDIRECTED} and
1681      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1682      *  @deprecated This is kept for backward compatibility reason. Use {@link #EXTRA_APN_TYPE_INT}
1683      *  instead.
1684      *
1685      *  @hide
1686      */
1687     @Deprecated
1688     @SuppressLint("ActionValue")
1689     public static final String EXTRA_APN_TYPE = "apnType";
1690 
1691     /**
1692      *  An string integer of corresponding apn type upon
1693      *  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1694      *  {@link #ACTION_CARRIER_SIGNAL_REDIRECTED} and
1695      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1696      *  Check {@link ApnSetting} TYPE_* for its values.
1697      *  @hide
1698      */
1699     @SuppressLint("ActionValue")
1700     public static final String EXTRA_APN_TYPE_INT = "apnTypeInt";
1701 
1702     /**
1703      *  An string extra with the protocol of the apn connection (IP,IPV6, IPV4V6) upon
1704      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1705      *  @deprecated This is kept for backward compatibility reason.
1706      *  Use {@link #EXTRA_APN_PROTOCOL_INT} instead.
1707      *
1708      *  @hide
1709      */
1710     @Deprecated
1711     @SuppressLint("ActionValue")
1712     public static final String EXTRA_APN_PROTOCOL = "apnProto";
1713 
1714     /**
1715      *  An integer extra with the protocol of the apn connection (IP,IPV6, IPV4V6) upon
1716      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1717      *  Check {@link ApnSetting} PROTOCOL_* for its values.
1718      *  @hide
1719      */
1720     @SuppressLint("ActionValue")
1721     public static final String EXTRA_APN_PROTOCOL_INT = "apnProtoInt";
1722 
1723     /**
1724      *  An integer extra indicating the pco id for the data upon
1725      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1726      *  @hide
1727      */
1728     @SuppressLint("ActionValue")
1729     public static final String EXTRA_PCO_ID = "pcoId";
1730 
1731     /**
1732      *  An extra of byte array of pco data read from modem upon
1733      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1734      *  @hide
1735      */
1736     @SuppressLint("ActionValue")
1737     public static final String EXTRA_PCO_VALUE = "pcoValue";
1738 
1739     /**
1740      *  An boolean extra indicating default network available upon
1741      *  {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcasts.
1742      *  @hide
1743      */
1744     @SuppressLint("ActionValue")
1745     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE = "defaultNetworkAvailable";
1746 
1747     /**
1748      * <p>Broadcast Action: The emergency call state is changed.
1749      * <ul>
1750      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
1751      *   call, false otherwise</li>
1752      * </ul>
1753      * <p class="note">
1754      * You can <em>not</em> receive this through components declared
1755      * in manifests, only by explicitly registering for it with
1756      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1757      * android.content.IntentFilter) Context.registerReceiver()}.
1758      *
1759      * <p class="note">This is a protected intent that can only be sent by the system.
1760      *
1761      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
1762      *
1763      * @hide
1764      */
1765     @SystemApi
1766     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1767     @SuppressLint("ActionValue")
1768     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
1769             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
1770 
1771 
1772     /**
1773      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
1774      * It indicates whether the phone is making an emergency call.
1775      *
1776      * @hide
1777      */
1778     @SystemApi
1779     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
1780             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
1781 
1782     /**
1783      * <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
1784      * <p class="note">.
1785      * This is to pop up a notice to show user that the phone is in emergency callback mode
1786      * and data calls and outgoing sms are blocked.
1787      *
1788      * <p class="note">This is a protected intent that can only be sent by the system.
1789      *
1790      * @hide
1791      */
1792     @SystemApi
1793     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS =
1794             "android.telephony.action.SHOW_NOTICE_ECM_BLOCK_OTHERS";
1795 
1796     /**
1797      * Broadcast Action: The default data subscription has changed in a multi-SIM device.
1798      * This has the following extra values:</p>
1799      * <ul>
1800      *   <li><em>subscription</em> - A int, the current data default subscription.</li>
1801      * </ul>
1802      *
1803      * @hide
1804      */
1805     @SystemApi
1806     @SuppressLint("ActionValue")
1807     public static final String ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED =
1808             "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED";
1809 
1810     /**
1811      * Broadcast Action: The default voice subscription has changed in a mult-SIm device.
1812      * This has the following extra values:</p>
1813      * <ul>
1814      *   <li><em>subscription</em> - A int, the current voice default subscription.</li>
1815      * </ul>
1816      *
1817      * @hide
1818      */
1819     @SystemApi
1820     @SuppressLint("ActionValue")
1821     public static final String ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED =
1822             "android.intent.action.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED";
1823 
1824     /**
1825      * Broadcast Action: This triggers a client initiated OMA-DM session to the OMA server.
1826      * <p class="note">
1827      * Open Mobile Alliance (OMA) Device Management (DM).
1828      *
1829      * This intent is used by the system components to trigger OMA-DM
1830      *
1831      * @hide
1832      */
1833     @SystemApi
1834     @SuppressLint("ActionValue")
1835     public static final String ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE =
1836             "com.android.omadm.service.CONFIGURATION_UPDATE";
1837 
1838     //
1839     //
1840     // Device Info
1841     //
1842     //
1843 
1844     /**
1845      * Returns the software version number for the device, for example,
1846      * the IMEI/SV for GSM phones. Return null if the software version is
1847      * not available.
1848      * <p>
1849      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}.
1850      */
1851     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1852     @Nullable
getDeviceSoftwareVersion()1853     public String getDeviceSoftwareVersion() {
1854         return getDeviceSoftwareVersion(getSlotIndex());
1855     }
1856 
1857     /**
1858      * Returns the software version number for the device, for example,
1859      * the IMEI/SV for GSM phones. Return null if the software version is
1860      * not available.
1861      * <p>
1862      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
1863      *
1864      * @param slotIndex of which deviceID is returned
1865      *
1866      * @hide
1867      */
1868     @SystemApi
1869     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1870     @Nullable
getDeviceSoftwareVersion(int slotIndex)1871     public String getDeviceSoftwareVersion(int slotIndex) {
1872         ITelephony telephony = getITelephony();
1873         if (telephony == null) return null;
1874 
1875         try {
1876             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
1877                     getAttributionTag());
1878         } catch (RemoteException ex) {
1879             return null;
1880         } catch (NullPointerException ex) {
1881             return null;
1882         }
1883     }
1884 
1885     /**
1886      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
1887      * or ESN for CDMA phones. Return null if device ID is not available.
1888      *
1889      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
1890      * restrictions, and apps are recommended to use resettable identifiers (see <a
1891      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
1892      * the following requirements is met:
1893      * <ul>
1894      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
1895      *     is a privileged permission that can only be granted to apps preloaded on the device.
1896      *     <li>If the calling app is the device or profile owner and has been granted the
1897      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
1898      *     owns a managed profile on the device; for more details see <a
1899      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
1900      *     Profile owner access is deprecated and will be removed in a future release.
1901      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
1902      *     active subscription.
1903      *     <li>If the calling app is the default SMS role holder (see {@link
1904      *     RoleManager#isRoleHeld(String)}).
1905      * </ul>
1906      *
1907      * <p>If the calling app does not meet one of these requirements then this method will behave
1908      * as follows:
1909      *
1910      * <ul>
1911      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1912      *     READ_PHONE_STATE permission then null is returned.</li>
1913      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1914      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1915      *     higher, then a SecurityException is thrown.</li>
1916      * </ul>
1917      *
1918      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1919      * MEID for CDMA.
1920      */
1921     @Deprecated
1922     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1923     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()1924     public String getDeviceId() {
1925         try {
1926             ITelephony telephony = getITelephony();
1927             if (telephony == null)
1928                 return null;
1929             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
1930                     mContext.getAttributionTag());
1931         } catch (RemoteException ex) {
1932             return null;
1933         } catch (NullPointerException ex) {
1934             return null;
1935         }
1936     }
1937 
1938     /**
1939      * Returns the unique device ID of a subscription, for example, the IMEI for
1940      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
1941      *
1942      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
1943      * restrictions, and apps are recommended to use resettable identifiers (see <a
1944      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
1945      * the following requirements is met:
1946      * <ul>
1947      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
1948      *     is a privileged permission that can only be granted to apps preloaded on the device.
1949      *     <li>If the calling app is the device or profile owner and has been granted the
1950      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
1951      *     owns a managed profile on the device; for more details see <a
1952      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
1953      *     Profile owner access is deprecated and will be removed in a future release.
1954      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
1955      *     active subscription.
1956      *     <li>If the calling app is the default SMS role holder (see {@link
1957      *     RoleManager#isRoleHeld(String)}).
1958      * </ul>
1959      *
1960      * <p>If the calling app does not meet one of these requirements then this method will behave
1961      * as follows:
1962      *
1963      * <ul>
1964      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1965      *     READ_PHONE_STATE permission then null is returned.</li>
1966      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1967      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1968      *     higher, then a SecurityException is thrown.</li>
1969      * </ul>
1970      *
1971      * @param slotIndex of which deviceID is returned
1972      *
1973      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1974      * MEID for CDMA.
1975      */
1976     @Deprecated
1977     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1978     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)1979     public String getDeviceId(int slotIndex) {
1980         // FIXME this assumes phoneId == slotIndex
1981         try {
1982             IPhoneSubInfo info = getSubscriberInfoService();
1983             if (info == null)
1984                 return null;
1985             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
1986                     mContext.getAttributionTag());
1987         } catch (RemoteException ex) {
1988             return null;
1989         } catch (NullPointerException ex) {
1990             return null;
1991         }
1992     }
1993 
1994     /**
1995      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
1996      * available.
1997      *
1998      * See {@link #getImei(int)} for details on the required permissions and behavior
1999      * when the caller does not hold sufficient permissions.
2000      */
2001     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2002     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei()2003     public String getImei() {
2004         return getImei(getSlotIndex());
2005     }
2006 
2007     /**
2008      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2009      * available.
2010      *
2011      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2012      * restrictions, and apps are recommended to use resettable identifiers (see <a
2013      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
2014      * the following requirements is met:
2015      * <ul>
2016      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2017      *     is a privileged permission that can only be granted to apps preloaded on the device.
2018      *     <li>If the calling app is the device or profile owner and has been granted the
2019      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2020      *     owns a managed profile on the device; for more details see <a
2021      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2022      *     Profile owner access is deprecated and will be removed in a future release.
2023      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2024      *     active subscription.
2025      *     <li>If the calling app is the default SMS role holder (see {@link
2026      *     RoleManager#isRoleHeld(String)}).
2027      * </ul>
2028      *
2029      * <p>If the calling app does not meet one of these requirements then this method will behave
2030      * as follows:
2031      *
2032      * <ul>
2033      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2034      *     READ_PHONE_STATE permission then null is returned.</li>
2035      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2036      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2037      *     higher, then a SecurityException is thrown.</li>
2038      * </ul>
2039      *
2040      * @param slotIndex of which IMEI is returned
2041      */
2042     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2043     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei(int slotIndex)2044     public String getImei(int slotIndex) {
2045         ITelephony telephony = getITelephony();
2046         if (telephony == null) return null;
2047 
2048         try {
2049             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
2050         } catch (RemoteException ex) {
2051             return null;
2052         } catch (NullPointerException ex) {
2053             return null;
2054         }
2055     }
2056 
2057     /**
2058      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2059      * available.
2060      */
2061     @Nullable
getTypeAllocationCode()2062     public String getTypeAllocationCode() {
2063         return getTypeAllocationCode(getSlotIndex());
2064     }
2065 
2066     /**
2067      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2068      * available.
2069      *
2070      * @param slotIndex of which Type Allocation Code is returned
2071      */
2072     @Nullable
getTypeAllocationCode(int slotIndex)2073     public String getTypeAllocationCode(int slotIndex) {
2074         ITelephony telephony = getITelephony();
2075         if (telephony == null) return null;
2076 
2077         try {
2078             return telephony.getTypeAllocationCodeForSlot(slotIndex);
2079         } catch (RemoteException ex) {
2080             return null;
2081         } catch (NullPointerException ex) {
2082             return null;
2083         }
2084     }
2085 
2086     /**
2087      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2088      *
2089      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2090      * restrictions, and apps are recommended to use resettable identifiers (see <a
2091      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
2092      * the following requirements is met:
2093      * <ul>
2094      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2095      *     is a privileged permission that can only be granted to apps preloaded on the device.
2096      *     <li>If the calling app is the device or profile owner and has been granted the
2097      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2098      *     owns a managed profile on the device; for more details see <a
2099      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2100      *     Profile owner access is deprecated and will be removed in a future release.
2101      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2102      *     active subscription.
2103      *     <li>If the calling app is the default SMS role holder (see {@link
2104      *     RoleManager#isRoleHeld(String)}).
2105      * </ul>
2106      *
2107      * <p>If the calling app does not meet one of these requirements then this method will behave
2108      * as follows:
2109      *
2110      * <ul>
2111      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2112      *     READ_PHONE_STATE permission then null is returned.</li>
2113      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2114      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2115      *     higher, then a SecurityException is thrown.</li>
2116      * </ul>
2117      */
2118     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2119     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid()2120     public String getMeid() {
2121         return getMeid(getSlotIndex());
2122     }
2123 
2124     /**
2125      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2126      *
2127      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2128      * restrictions, and apps are recommended to use resettable identifiers (see <a
2129      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
2130      * the following requirements is met:
2131      * <ul>
2132      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2133      *     is a privileged permission that can only be granted to apps preloaded on the device.
2134      *     <li>If the calling app is the device or profile owner and has been granted the
2135      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2136      *     owns a managed profile on the device; for more details see <a
2137      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2138      *     Profile owner access is deprecated and will be removed in a future release.
2139      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2140      *     active subscription.
2141      *     <li>If the calling app is the default SMS role holder (see {@link
2142      *     RoleManager#isRoleHeld(String)}).
2143      * </ul>
2144      *
2145      * <p>If the calling app does not meet one of these requirements then this method will behave
2146      * as follows:
2147      *
2148      * <ul>
2149      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2150      *     READ_PHONE_STATE permission then null is returned.</li>
2151      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2152      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2153      *     higher, then a SecurityException is thrown.</li>
2154      * </ul>
2155      *
2156      * @param slotIndex of which MEID is returned
2157      */
2158     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2159     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid(int slotIndex)2160     public String getMeid(int slotIndex) {
2161         ITelephony telephony = getITelephony();
2162         if (telephony == null) return null;
2163 
2164         try {
2165             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
2166                     getAttributionTag());
2167             if (TextUtils.isEmpty(meid)) {
2168                 Log.d(TAG, "getMeid: return null because MEID is not available");
2169                 return null;
2170             }
2171             return meid;
2172         } catch (RemoteException ex) {
2173             return null;
2174         } catch (NullPointerException ex) {
2175             return null;
2176         }
2177     }
2178 
2179     /**
2180      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2181      * available.
2182      */
2183     @Nullable
getManufacturerCode()2184     public String getManufacturerCode() {
2185         return getManufacturerCode(getSlotIndex());
2186     }
2187 
2188     /**
2189      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2190      * available.
2191      *
2192      * @param slotIndex of which Type Allocation Code is returned
2193      */
2194     @Nullable
getManufacturerCode(int slotIndex)2195     public String getManufacturerCode(int slotIndex) {
2196         ITelephony telephony = getITelephony();
2197         if (telephony == null) return null;
2198 
2199         try {
2200             return telephony.getManufacturerCodeForSlot(slotIndex);
2201         } catch (RemoteException ex) {
2202             return null;
2203         } catch (NullPointerException ex) {
2204             return null;
2205         }
2206     }
2207 
2208     /**
2209      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2210      *
2211      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2212      * restrictions, and apps are recommended to use resettable identifiers (see <a
2213      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
2214      * the following requirements is met:
2215      * <ul>
2216      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2217      *     is a privileged permission that can only be granted to apps preloaded on the device.
2218      *     <li>If the calling app is the device or profile owner and has been granted the
2219      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2220      *     owns a managed profile on the device; for more details see <a
2221      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2222      *     Profile owner access is deprecated and will be removed in a future release.
2223      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2224      *     <li>If the calling app is the default SMS role holder (see {@link
2225      *     RoleManager#isRoleHeld(String)}).
2226      * </ul>
2227      *
2228      * <p>If the calling app does not meet one of these requirements then this method will behave
2229      * as follows:
2230      *
2231      * <ul>
2232      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2233      *     READ_PHONE_STATE permission then null is returned.</li>
2234      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2235      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2236      *     higher, then a SecurityException is thrown.</li>
2237      * </ul>
2238      */
2239     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2240     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNai()2241     public String getNai() {
2242         return getNaiBySubscriberId(getSubId());
2243     }
2244 
2245     /**
2246      * Returns the NAI. Return null if NAI is not available.
2247      *
2248      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2249      * restrictions, and apps are recommended to use resettable identifiers (see <a
2250      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
2251      * the following requirements is met:
2252      * <ul>
2253      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2254      *     is a privileged permission that can only be granted to apps preloaded on the device.
2255      *     <li>If the calling app is the device or profile owner and has been granted the
2256      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
2257      *     owns a managed profile on the device; for more details see <a
2258      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
2259      *     Profile owner access is deprecated and will be removed in a future release.
2260      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2261      *     <li>If the calling app is the default SMS role holder (see {@link
2262      *     RoleManager#isRoleHeld(String)}).
2263      * </ul>
2264      *
2265      * <p>If the calling app does not meet one of these requirements then this method will behave
2266      * as follows:
2267      *
2268      * <ul>
2269      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2270      *     READ_PHONE_STATE permission then null is returned.</li>
2271      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2272      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2273      *     higher, then a SecurityException is thrown.</li>
2274      * </ul>
2275      *
2276      *  @param slotIndex of which Nai is returned
2277      */
2278     /** {@hide}*/
2279     @UnsupportedAppUsage
getNai(int slotIndex)2280     public String getNai(int slotIndex) {
2281         int[] subId = SubscriptionManager.getSubId(slotIndex);
2282         if (subId == null) {
2283             return null;
2284         }
2285         return getNaiBySubscriberId(subId[0]);
2286     }
2287 
getNaiBySubscriberId(int subId)2288     private String getNaiBySubscriberId(int subId) {
2289         try {
2290             IPhoneSubInfo info = getSubscriberInfoService();
2291             if (info == null)
2292                 return null;
2293             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2294                     mContext.getAttributionTag());
2295             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2296                 Rlog.v(TAG, "Nai = " + nai);
2297             }
2298             return nai;
2299         } catch (RemoteException ex) {
2300             return null;
2301         } catch (NullPointerException ex) {
2302             return null;
2303         }
2304     }
2305 
2306     /**
2307      * Returns the current location of the device.
2308      *<p>
2309      * If there is only one radio in the device and that radio has an LTE connection,
2310      * this method will return null. The implementation must not to try add LTE
2311      * identifiers into the existing cdma/gsm classes.
2312      *<p>
2313      * @return Current location of the device or null if not available.
2314      *
2315      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2316      */
2317     @Deprecated
2318     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getCellLocation()2319     public CellLocation getCellLocation() {
2320         try {
2321             ITelephony telephony = getITelephony();
2322             if (telephony == null) {
2323                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2324                 return null;
2325             }
2326 
2327             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2328                     mContext.getAttributionTag());
2329             CellLocation cl = cellIdentity.asCellLocation();
2330             if (cl == null || cl.isEmpty()) {
2331                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2332                         + " phone type doesn't match CellLocation type");
2333                 return null;
2334             }
2335 
2336             return cl;
2337         } catch (RemoteException ex) {
2338             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2339             return null;
2340         }
2341     }
2342 
2343     /**
2344      * Enables location update notifications.  {@link PhoneStateListener#onCellLocationChanged
2345      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
2346      *
2347      * @hide
2348      */
2349     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
enableLocationUpdates()2350     public void enableLocationUpdates() {
2351         enableLocationUpdates(getSubId());
2352     }
2353 
2354     /**
2355      * Enables location update notifications for a subscription.
2356      * {@link PhoneStateListener#onCellLocationChanged
2357      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
2358      *
2359      * @param subId for which the location updates are enabled
2360      * @hide
2361      */
2362     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
enableLocationUpdates(int subId)2363     public void enableLocationUpdates(int subId) {
2364         try {
2365             ITelephony telephony = getITelephony();
2366             if (telephony != null)
2367                 telephony.enableLocationUpdatesForSubscriber(subId);
2368         } catch (RemoteException ex) {
2369         } catch (NullPointerException ex) {
2370         }
2371     }
2372 
2373     /**
2374      * Disables location update notifications.  {@link PhoneStateListener#onCellLocationChanged
2375      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
2376      *
2377      * @hide
2378      */
2379     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
disableLocationUpdates()2380     public void disableLocationUpdates() {
2381         disableLocationUpdates(getSubId());
2382     }
2383 
2384     /** @hide */
disableLocationUpdates(int subId)2385     public void disableLocationUpdates(int subId) {
2386         try {
2387             ITelephony telephony = getITelephony();
2388             if (telephony != null)
2389                 telephony.disableLocationUpdatesForSubscriber(subId);
2390         } catch (RemoteException ex) {
2391         } catch (NullPointerException ex) {
2392         }
2393     }
2394 
2395     /**
2396      * Returns the neighboring cell information of the device.
2397      *
2398      * @return List of NeighboringCellInfo or null if info unavailable.
2399      *
2400      * @removed
2401      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2402      *             from NeighboringCellInfo, including LTE cell information.
2403      */
2404     @Deprecated
2405     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
getNeighboringCellInfo()2406     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2407         try {
2408             ITelephony telephony = getITelephony();
2409             if (telephony == null)
2410                 return null;
2411             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2412                     mContext.getAttributionTag());
2413         } catch (RemoteException ex) {
2414             return null;
2415         } catch (NullPointerException ex) {
2416             return null;
2417         }
2418     }
2419 
2420     /** No phone radio. */
2421     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2422     /** Phone radio is GSM. */
2423     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2424     /** Phone radio is CDMA. */
2425     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2426     /** Phone is via SIP. */
2427     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2428 
2429     /**
2430      * Phone is via IMS.
2431      *
2432      * @hide
2433      */
2434     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2435 
2436     /**
2437      * Phone is via Third Party.
2438      *
2439      * @hide
2440      */
2441     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2442 
2443     /**
2444      * Returns the current phone type.
2445      * TODO: This is a last minute change and hence hidden.
2446      *
2447      * @see #PHONE_TYPE_NONE
2448      * @see #PHONE_TYPE_GSM
2449      * @see #PHONE_TYPE_CDMA
2450      * @see #PHONE_TYPE_SIP
2451      *
2452      * {@hide}
2453      */
2454     @SystemApi
getCurrentPhoneType()2455     public int getCurrentPhoneType() {
2456         return getCurrentPhoneType(getSubId());
2457     }
2458 
2459     /**
2460      * Returns a constant indicating the device phone type for a subscription.
2461      *
2462      * @see #PHONE_TYPE_NONE
2463      * @see #PHONE_TYPE_GSM
2464      * @see #PHONE_TYPE_CDMA
2465      *
2466      * @param subId for which phone type is returned
2467      * @hide
2468      */
2469     @SystemApi
getCurrentPhoneType(int subId)2470     public int getCurrentPhoneType(int subId) {
2471         int phoneId;
2472         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2473             // if we don't have any sims, we don't have subscriptions, but we
2474             // still may want to know what type of phone we've got.
2475             phoneId = 0;
2476         } else {
2477             phoneId = SubscriptionManager.getPhoneId(subId);
2478         }
2479 
2480         return getCurrentPhoneTypeForSlot(phoneId);
2481     }
2482 
2483     /**
2484      * See getCurrentPhoneType.
2485      *
2486      * @hide
2487      */
getCurrentPhoneTypeForSlot(int slotIndex)2488     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2489         try{
2490             ITelephony telephony = getITelephony();
2491             if (telephony != null) {
2492                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2493             } else {
2494                 // This can happen when the ITelephony interface is not up yet.
2495                 return getPhoneTypeFromProperty(slotIndex);
2496             }
2497         } catch (RemoteException ex) {
2498             // This shouldn't happen in the normal case, as a backup we
2499             // read from the system property.
2500             return getPhoneTypeFromProperty(slotIndex);
2501         } catch (NullPointerException ex) {
2502             // This shouldn't happen in the normal case, as a backup we
2503             // read from the system property.
2504             return getPhoneTypeFromProperty(slotIndex);
2505         }
2506     }
2507 
2508     /**
2509      * Returns a constant indicating the device phone type.  This
2510      * indicates the type of radio used to transmit voice calls.
2511      *
2512      * @see #PHONE_TYPE_NONE
2513      * @see #PHONE_TYPE_GSM
2514      * @see #PHONE_TYPE_CDMA
2515      * @see #PHONE_TYPE_SIP
2516      */
getPhoneType()2517     public int getPhoneType() {
2518         if (!isVoiceCapable()) {
2519             return PHONE_TYPE_NONE;
2520         }
2521         return getCurrentPhoneType();
2522     }
2523 
getPhoneTypeFromProperty()2524     private int getPhoneTypeFromProperty() {
2525         return getPhoneTypeFromProperty(getPhoneId());
2526     }
2527 
2528     /** {@hide} */
2529     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2530     private int getPhoneTypeFromProperty(int phoneId) {
2531         Integer type = getTelephonyProperty(
2532                 phoneId, TelephonyProperties.current_active_phone(), null);
2533         if (type != null) return type;
2534         return getPhoneTypeFromNetworkType(phoneId);
2535     }
2536 
getPhoneTypeFromNetworkType()2537     private int getPhoneTypeFromNetworkType() {
2538         return getPhoneTypeFromNetworkType(getPhoneId());
2539     }
2540 
2541     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2542     private int getPhoneTypeFromNetworkType(int phoneId) {
2543         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2544         // use the system property for default network type.
2545         // This is a fail safe, and can only happen at first boot.
2546         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2547         if (mode != null) {
2548             return TelephonyManager.getPhoneType(mode);
2549         }
2550         return TelephonyManager.PHONE_TYPE_NONE;
2551     }
2552 
2553     /**
2554      * This function returns the type of the phone, depending
2555      * on the network mode.
2556      *
2557      * @param networkMode
2558      * @return Phone Type
2559      *
2560      * @hide
2561      */
2562     @UnsupportedAppUsage
getPhoneType(int networkMode)2563     public static int getPhoneType(int networkMode) {
2564         switch(networkMode) {
2565         case RILConstants.NETWORK_MODE_CDMA:
2566         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2567         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2568             return PhoneConstants.PHONE_TYPE_CDMA;
2569 
2570         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2571         case RILConstants.NETWORK_MODE_GSM_ONLY:
2572         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2573         case RILConstants.NETWORK_MODE_GSM_UMTS:
2574         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2575         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2576         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2577         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2578         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2579         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2580         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2581         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2582         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2583         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2584         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2585         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2586             return PhoneConstants.PHONE_TYPE_GSM;
2587 
2588         // Use CDMA Phone for the global mode including CDMA
2589         case RILConstants.NETWORK_MODE_GLOBAL:
2590         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2591         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2592             return PhoneConstants.PHONE_TYPE_CDMA;
2593 
2594         case RILConstants.NETWORK_MODE_LTE_ONLY:
2595             if (getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
2596                 return PhoneConstants.PHONE_TYPE_CDMA;
2597             } else {
2598                 return PhoneConstants.PHONE_TYPE_GSM;
2599             }
2600         default:
2601             return PhoneConstants.PHONE_TYPE_GSM;
2602         }
2603     }
2604 
2605     /**
2606      * The contents of the /proc/cmdline file
2607      */
2608     @UnsupportedAppUsage
getProcCmdLine()2609     private static String getProcCmdLine()
2610     {
2611         String cmdline = "";
2612         FileInputStream is = null;
2613         try {
2614             is = new FileInputStream("/proc/cmdline");
2615             byte [] buffer = new byte[2048];
2616             int count = is.read(buffer);
2617             if (count > 0) {
2618                 cmdline = new String(buffer, 0, count);
2619             }
2620         } catch (IOException e) {
2621             Rlog.d(TAG, "No /proc/cmdline exception=" + e);
2622         } finally {
2623             if (is != null) {
2624                 try {
2625                     is.close();
2626                 } catch (IOException e) {
2627                 }
2628             }
2629         }
2630         Rlog.d(TAG, "/proc/cmdline=" + cmdline);
2631         return cmdline;
2632     }
2633 
2634     /**
2635      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2636      * @hide
2637      */
2638     @SystemApi
getMaxNumberVerificationTimeoutMillis()2639     public static long getMaxNumberVerificationTimeoutMillis() {
2640         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2641     }
2642 
2643     /** Kernel command line */
2644     private static final String sKernelCmdLine = getProcCmdLine();
2645 
2646     /** Pattern for selecting the product type from the kernel command line */
2647     private static final Pattern sProductTypePattern =
2648         Pattern.compile("\\sproduct_type\\s*=\\s*(\\w+)");
2649 
2650     /** The ProductType used for LTE on CDMA devices */
2651     private static final String sLteOnCdmaProductType =
2652             TelephonyProperties.lte_on_cdma_product_type().orElse("");
2653 
2654     /**
2655      * Return if the current radio is LTE on CDMA. This
2656      * is a tri-state return value as for a period of time
2657      * the mode may be unknown.
2658      *
2659      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
2660      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
2661      *
2662      * @hide
2663      */
2664     @UnsupportedAppUsage
getLteOnCdmaModeStatic()2665     public static int getLteOnCdmaModeStatic() {
2666         int retVal;
2667         int curVal;
2668         String productType = "";
2669 
2670         curVal = TelephonyProperties.lte_on_cdma_device().orElse(
2671             PhoneConstants.LTE_ON_CDMA_UNKNOWN);
2672         retVal = curVal;
2673         if (retVal == PhoneConstants.LTE_ON_CDMA_UNKNOWN) {
2674             Matcher matcher = sProductTypePattern.matcher(sKernelCmdLine);
2675             if (matcher.find()) {
2676                 productType = matcher.group(1);
2677                 if (sLteOnCdmaProductType.equals(productType)) {
2678                     retVal = PhoneConstants.LTE_ON_CDMA_TRUE;
2679                 } else {
2680                     retVal = PhoneConstants.LTE_ON_CDMA_FALSE;
2681                 }
2682             } else {
2683                 retVal = PhoneConstants.LTE_ON_CDMA_FALSE;
2684             }
2685         }
2686 
2687         Rlog.d(TAG, "getLteOnCdmaMode=" + retVal + " curVal=" + curVal +
2688                 " product_type='" + productType +
2689                 "' lteOnCdmaProductType='" + sLteOnCdmaProductType + "'");
2690         return retVal;
2691     }
2692 
2693     //
2694     //
2695     // Current Network
2696     //
2697     //
2698 
2699     /**
2700      * Returns the alphabetic name of current registered operator.
2701      * <p>
2702      * Availability: Only when user is registered to a network. Result may be
2703      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2704      * on a CDMA network).
2705      */
getNetworkOperatorName()2706     public String getNetworkOperatorName() {
2707         return getNetworkOperatorName(getSubId());
2708     }
2709 
2710     /**
2711      * Returns the alphabetic name of current registered operator
2712      * for a particular subscription.
2713      * <p>
2714      * Availability: Only when user is registered to a network. Result may be
2715      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2716      * on a CDMA network).
2717      * @param subId
2718      * @hide
2719      */
2720     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2721     public String getNetworkOperatorName(int subId) {
2722         int phoneId = SubscriptionManager.getPhoneId(subId);
2723         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2724     }
2725 
2726     /**
2727      * Returns the numeric name (MCC+MNC) of current registered operator.
2728      * <p>
2729      * Availability: Only when user is registered to a network. Result may be
2730      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2731      * on a CDMA network).
2732      */
getNetworkOperator()2733     public String getNetworkOperator() {
2734         return getNetworkOperatorForPhone(getPhoneId());
2735     }
2736 
2737     /**
2738      * Returns the numeric name (MCC+MNC) of current registered operator
2739      * for a particular subscription.
2740      * <p>
2741      * Availability: Only when user is registered to a network. Result may be
2742      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2743      * on a CDMA network).
2744      *
2745      * @param subId
2746      * @hide
2747      */
2748     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2749     public String getNetworkOperator(int subId) {
2750         int phoneId = SubscriptionManager.getPhoneId(subId);
2751         return getNetworkOperatorForPhone(phoneId);
2752      }
2753 
2754     /**
2755      * Returns the numeric name (MCC+MNC) of current registered operator
2756      * for a particular subscription.
2757      * <p>
2758      * Availability: Only when user is registered to a network. Result may be
2759      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2760      * on a CDMA network).
2761      *
2762      * @param phoneId
2763      * @hide
2764      **/
2765     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2766     public String getNetworkOperatorForPhone(int phoneId) {
2767         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2768     }
2769 
2770 
2771     /**
2772      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2773      * network specifier is used by {@link
2774      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2775      * android.net.NetworkRequest} that connects through the subscription.
2776      *
2777      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2778      * @see #createForSubscriptionId(int)
2779      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2780      */
getNetworkSpecifier()2781     public String getNetworkSpecifier() {
2782         return String.valueOf(getSubId());
2783     }
2784 
2785     /**
2786      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
2787      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
2788      * default values.
2789      *
2790      * <p>This method may take several seconds to complete, so it should only be called from a
2791      * worker thread.
2792      *
2793      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2794      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2795      *
2796      * @see CarrierConfigManager#getConfigForSubId(int)
2797      * @see #createForSubscriptionId(int)
2798      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2799      */
2800     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2801     @WorkerThread
2802     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCarrierConfig()2803     public PersistableBundle getCarrierConfig() {
2804         CarrierConfigManager carrierConfigManager = mContext
2805                 .getSystemService(CarrierConfigManager.class);
2806         return carrierConfigManager.getConfigForSubId(getSubId());
2807     }
2808 
2809     /**
2810      * Returns true if the device is considered roaming on the current
2811      * network, for GSM purposes.
2812      * <p>
2813      * Availability: Only when user registered to a network.
2814      */
isNetworkRoaming()2815     public boolean isNetworkRoaming() {
2816         return isNetworkRoaming(getSubId());
2817     }
2818 
2819     /**
2820      * Returns true if the device is considered roaming on the current
2821      * network for a subscription.
2822      * <p>
2823      * Availability: Only when user registered to a network.
2824      *
2825      * @param subId
2826      * @hide
2827      */
2828     @UnsupportedAppUsage
isNetworkRoaming(int subId)2829     public boolean isNetworkRoaming(int subId) {
2830         int phoneId = SubscriptionManager.getPhoneId(subId);
2831         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
2832     }
2833 
2834     /**
2835      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2836      * the current registered operator or the cell nearby, if available.
2837      *
2838      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2839      * if on a CDMA network).
2840      * <p>
2841      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2842      * available.
2843      */
getNetworkCountryIso()2844     public String getNetworkCountryIso() {
2845         return getNetworkCountryIso(getSlotIndex());
2846     }
2847 
2848     /**
2849      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2850      * the current registered operator or the cell nearby, if available. This is same as
2851      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
2852      * accessing network country info from the SIM slot that does not have SIM inserted.
2853      *
2854      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2855      * if on a CDMA network).
2856      * <p>
2857      *
2858      * @param slotIndex the SIM slot index to get network country ISO.
2859      *
2860      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2861      * available.
2862      *
2863      * @throws IllegalArgumentException when the slotIndex is invalid.
2864      *
2865      */
2866     @NonNull
getNetworkCountryIso(int slotIndex)2867     public String getNetworkCountryIso(int slotIndex) {
2868         try {
2869             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
2870                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
2871                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
2872             }
2873 
2874             ITelephony telephony = getITelephony();
2875             if (telephony == null) return "";
2876             return telephony.getNetworkCountryIsoForPhone(slotIndex);
2877         } catch (RemoteException ex) {
2878             return "";
2879         }
2880     }
2881 
2882     /**
2883      * @hide
2884      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
2885      */
2886     @Deprecated
2887     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
2888             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)2889     public String getNetworkCountryIsoForPhone(int phoneId) {
2890         return getNetworkCountryIso(phoneId);
2891     }
2892 
2893     /*
2894      * When adding a network type to the list below, make sure to add the correct icon to
2895      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
2896      * Do not add negative types.
2897      */
2898     /** Network type is unknown */
2899     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
2900     /** Current network is GPRS */
2901     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
2902     /** Current network is EDGE */
2903     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
2904     /** Current network is UMTS */
2905     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
2906     /** Current network is CDMA: Either IS95A or IS95B*/
2907     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
2908     /** Current network is EVDO revision 0*/
2909     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
2910     /** Current network is EVDO revision A*/
2911     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
2912     /** Current network is 1xRTT*/
2913     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
2914     /** Current network is HSDPA */
2915     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
2916     /** Current network is HSUPA */
2917     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
2918     /** Current network is HSPA */
2919     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
2920     /** Current network is iDen */
2921     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
2922     /** Current network is EVDO revision B*/
2923     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
2924     /** Current network is LTE */
2925     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
2926     /** Current network is eHRPD */
2927     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
2928     /** Current network is HSPA+ */
2929     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
2930     /** Current network is GSM */
2931     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
2932     /** Current network is TD_SCDMA */
2933     public static final int NETWORK_TYPE_TD_SCDMA =
2934             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
2935     /** Current network is IWLAN */
2936     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
2937     /** Current network is LTE_CA {@hide} */
2938     @UnsupportedAppUsage
2939     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
2940     /** Current network is NR(New Radio) 5G. */
2941     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
2942 
2943     private static final @NetworkType int[] NETWORK_TYPES = {
2944             NETWORK_TYPE_GPRS,
2945             NETWORK_TYPE_EDGE,
2946             NETWORK_TYPE_UMTS,
2947             NETWORK_TYPE_CDMA,
2948             NETWORK_TYPE_EVDO_0,
2949             NETWORK_TYPE_EVDO_A,
2950             NETWORK_TYPE_1xRTT,
2951             NETWORK_TYPE_HSDPA,
2952             NETWORK_TYPE_HSUPA,
2953             NETWORK_TYPE_HSPA,
2954             NETWORK_TYPE_IDEN,
2955             NETWORK_TYPE_EVDO_B,
2956             NETWORK_TYPE_LTE,
2957             NETWORK_TYPE_EHRPD,
2958             NETWORK_TYPE_HSPAP,
2959             NETWORK_TYPE_GSM,
2960             NETWORK_TYPE_TD_SCDMA,
2961             NETWORK_TYPE_IWLAN,
2962             NETWORK_TYPE_LTE_CA,
2963             NETWORK_TYPE_NR
2964     };
2965 
2966     /**
2967      * Return a collection of all network types
2968      * @return network types
2969      *
2970      * @hide
2971      */
getAllNetworkTypes()2972     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
2973         return NETWORK_TYPES;
2974     }
2975 
2976     /**
2977      * Return the current data network type.
2978      *
2979      * @deprecated use {@link #getDataNetworkType()}
2980      * @return the NETWORK_TYPE_xxxx for current data connection.
2981      */
2982     @Deprecated
2983     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNetworkType()2984     public @NetworkType int getNetworkType() {
2985         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
2986     }
2987 
2988     /**
2989      * Returns a constant indicating the radio technology (network type)
2990      * currently in use on the device for a subscription.
2991      * @return the network type
2992      *
2993      * @param subId for which network type is returned
2994      *
2995      * @see #NETWORK_TYPE_UNKNOWN
2996      * @see #NETWORK_TYPE_GPRS
2997      * @see #NETWORK_TYPE_EDGE
2998      * @see #NETWORK_TYPE_UMTS
2999      * @see #NETWORK_TYPE_HSDPA
3000      * @see #NETWORK_TYPE_HSUPA
3001      * @see #NETWORK_TYPE_HSPA
3002      * @see #NETWORK_TYPE_CDMA
3003      * @see #NETWORK_TYPE_EVDO_0
3004      * @see #NETWORK_TYPE_EVDO_A
3005      * @see #NETWORK_TYPE_EVDO_B
3006      * @see #NETWORK_TYPE_1xRTT
3007      * @see #NETWORK_TYPE_IDEN
3008      * @see #NETWORK_TYPE_LTE
3009      * @see #NETWORK_TYPE_EHRPD
3010      * @see #NETWORK_TYPE_HSPAP
3011      * @see #NETWORK_TYPE_NR
3012      *
3013      * @hide
3014      */
3015     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3016     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)3017     public int getNetworkType(int subId) {
3018         try {
3019             ITelephony telephony = getITelephony();
3020             if (telephony != null) {
3021                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
3022                         getAttributionTag());
3023             } else {
3024                 // This can happen when the ITelephony interface is not up yet.
3025                 return NETWORK_TYPE_UNKNOWN;
3026             }
3027         } catch (RemoteException ex) {
3028             // This shouldn't happen in the normal case
3029             return NETWORK_TYPE_UNKNOWN;
3030         } catch (NullPointerException ex) {
3031             // This could happen before phone restarts due to crashing
3032             return NETWORK_TYPE_UNKNOWN;
3033         }
3034     }
3035 
3036     /**
3037      * Returns a constant indicating the radio technology (network type)
3038      * currently in use on the device for data transmission.
3039      *
3040      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
3041      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
3042      *
3043      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3044      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3045      *
3046      * @return the network type
3047      *
3048      * @see #NETWORK_TYPE_UNKNOWN
3049      * @see #NETWORK_TYPE_GPRS
3050      * @see #NETWORK_TYPE_EDGE
3051      * @see #NETWORK_TYPE_UMTS
3052      * @see #NETWORK_TYPE_HSDPA
3053      * @see #NETWORK_TYPE_HSUPA
3054      * @see #NETWORK_TYPE_HSPA
3055      * @see #NETWORK_TYPE_CDMA
3056      * @see #NETWORK_TYPE_EVDO_0
3057      * @see #NETWORK_TYPE_EVDO_A
3058      * @see #NETWORK_TYPE_EVDO_B
3059      * @see #NETWORK_TYPE_1xRTT
3060      * @see #NETWORK_TYPE_IDEN
3061      * @see #NETWORK_TYPE_LTE
3062      * @see #NETWORK_TYPE_EHRPD
3063      * @see #NETWORK_TYPE_HSPAP
3064      * @see #NETWORK_TYPE_NR
3065      */
3066     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3067     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getDataNetworkType()3068     public @NetworkType int getDataNetworkType() {
3069         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3070     }
3071 
3072     /**
3073      * Returns a constant indicating the radio technology (network type)
3074      * currently in use on the device for data transmission for a subscription
3075      * @return the network type
3076      *
3077      * @param subId for which network type is returned
3078      * @hide
3079      */
3080     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3081     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)3082     public int getDataNetworkType(int subId) {
3083         try{
3084             ITelephony telephony = getITelephony();
3085             if (telephony != null) {
3086                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
3087                         getAttributionTag());
3088             } else {
3089                 // This can happen when the ITelephony interface is not up yet.
3090                 return NETWORK_TYPE_UNKNOWN;
3091             }
3092         } catch(RemoteException ex) {
3093             // This shouldn't happen in the normal case
3094             return NETWORK_TYPE_UNKNOWN;
3095         } catch (NullPointerException ex) {
3096             // This could happen before phone restarts due to crashing
3097             return NETWORK_TYPE_UNKNOWN;
3098         }
3099     }
3100 
3101     /**
3102      * Returns the NETWORK_TYPE_xxxx for voice
3103      *
3104      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3105      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3106      */
3107     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3108     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceNetworkType()3109     public @NetworkType int getVoiceNetworkType() {
3110         return getVoiceNetworkType(getSubId());
3111     }
3112 
3113     /**
3114      * Returns the NETWORK_TYPE_xxxx for voice for a subId
3115      * @hide
3116      */
3117     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3118     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)3119     public int getVoiceNetworkType(int subId) {
3120         try{
3121             ITelephony telephony = getITelephony();
3122             if (telephony != null) {
3123                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
3124                         getAttributionTag());
3125             } else {
3126                 // This can happen when the ITelephony interface is not up yet.
3127                 return NETWORK_TYPE_UNKNOWN;
3128             }
3129         } catch(RemoteException ex) {
3130             // This shouldn't happen in the normal case
3131             return NETWORK_TYPE_UNKNOWN;
3132         } catch (NullPointerException ex) {
3133             // This could happen before phone restarts due to crashing
3134             return NETWORK_TYPE_UNKNOWN;
3135         }
3136     }
3137 
3138     /**
3139      * Returns a string representation of the radio technology (network type)
3140      * currently in use on the device.
3141      * @return the name of the radio technology
3142      *
3143      * @hide pending API council review
3144      */
3145     @UnsupportedAppUsage
getNetworkTypeName()3146     public String getNetworkTypeName() {
3147         return getNetworkTypeName(getNetworkType());
3148     }
3149 
3150     /**
3151      * Returns a string representation of the radio technology (network type)
3152      * currently in use on the device.
3153      * @param subId for which network type is returned
3154      * @return the name of the radio technology
3155      *
3156      */
3157     /** {@hide} */
3158     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)3159     public static String getNetworkTypeName(@NetworkType int type) {
3160         switch (type) {
3161             case NETWORK_TYPE_GPRS:
3162                 return "GPRS";
3163             case NETWORK_TYPE_EDGE:
3164                 return "EDGE";
3165             case NETWORK_TYPE_UMTS:
3166                 return "UMTS";
3167             case NETWORK_TYPE_HSDPA:
3168                 return "HSDPA";
3169             case NETWORK_TYPE_HSUPA:
3170                 return "HSUPA";
3171             case NETWORK_TYPE_HSPA:
3172                 return "HSPA";
3173             case NETWORK_TYPE_CDMA:
3174                 return "CDMA";
3175             case NETWORK_TYPE_EVDO_0:
3176                 return "CDMA - EvDo rev. 0";
3177             case NETWORK_TYPE_EVDO_A:
3178                 return "CDMA - EvDo rev. A";
3179             case NETWORK_TYPE_EVDO_B:
3180                 return "CDMA - EvDo rev. B";
3181             case NETWORK_TYPE_1xRTT:
3182                 return "CDMA - 1xRTT";
3183             case NETWORK_TYPE_LTE:
3184                 return "LTE";
3185             case NETWORK_TYPE_EHRPD:
3186                 return "CDMA - eHRPD";
3187             case NETWORK_TYPE_IDEN:
3188                 return "iDEN";
3189             case NETWORK_TYPE_HSPAP:
3190                 return "HSPA+";
3191             case NETWORK_TYPE_GSM:
3192                 return "GSM";
3193             case NETWORK_TYPE_TD_SCDMA:
3194                 return "TD_SCDMA";
3195             case NETWORK_TYPE_IWLAN:
3196                 return "IWLAN";
3197             case NETWORK_TYPE_LTE_CA:
3198                 return "LTE_CA";
3199             case NETWORK_TYPE_NR:
3200                 return "NR";
3201             default:
3202                 return "UNKNOWN";
3203         }
3204     }
3205 
3206     /**
3207      * Returns the bitmask for a given technology (network type)
3208      * @param networkType for which bitmask is returned
3209      * @return the network type bitmask
3210      * {@hide}
3211      */
getBitMaskForNetworkType(@etworkType int networkType)3212     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
3213         switch(networkType) {
3214             case NETWORK_TYPE_GSM:
3215                 return NETWORK_TYPE_BITMASK_GSM;
3216             case NETWORK_TYPE_GPRS:
3217                 return NETWORK_TYPE_BITMASK_GPRS;
3218             case NETWORK_TYPE_EDGE:
3219                 return NETWORK_TYPE_BITMASK_EDGE;
3220             case NETWORK_TYPE_CDMA:
3221                 return NETWORK_TYPE_BITMASK_CDMA;
3222             case NETWORK_TYPE_1xRTT:
3223                 return NETWORK_TYPE_BITMASK_1xRTT;
3224             case NETWORK_TYPE_EVDO_0:
3225                 return NETWORK_TYPE_BITMASK_EVDO_0;
3226             case NETWORK_TYPE_EVDO_A:
3227                 return NETWORK_TYPE_BITMASK_EVDO_A;
3228             case NETWORK_TYPE_EVDO_B:
3229                 return NETWORK_TYPE_BITMASK_EVDO_B;
3230             case NETWORK_TYPE_EHRPD:
3231                 return NETWORK_TYPE_BITMASK_EHRPD;
3232             case NETWORK_TYPE_HSUPA:
3233                 return NETWORK_TYPE_BITMASK_HSUPA;
3234             case NETWORK_TYPE_HSDPA:
3235                 return NETWORK_TYPE_BITMASK_HSDPA;
3236             case NETWORK_TYPE_HSPA:
3237                 return NETWORK_TYPE_BITMASK_HSPA;
3238             case NETWORK_TYPE_HSPAP:
3239                 return NETWORK_TYPE_BITMASK_HSPAP;
3240             case NETWORK_TYPE_UMTS:
3241                 return NETWORK_TYPE_BITMASK_UMTS;
3242             case NETWORK_TYPE_TD_SCDMA:
3243                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
3244             case NETWORK_TYPE_LTE:
3245                 return NETWORK_TYPE_BITMASK_LTE;
3246             case NETWORK_TYPE_LTE_CA:
3247                 return NETWORK_TYPE_BITMASK_LTE_CA;
3248             case NETWORK_TYPE_NR:
3249                 return NETWORK_TYPE_BITMASK_NR;
3250             default:
3251                 return NETWORK_TYPE_BITMASK_UNKNOWN;
3252         }
3253     }
3254 
3255     //
3256     //
3257     // SIM Card
3258     //
3259     //
3260 
3261     /** @hide */
3262     @IntDef(prefix = {"SIM_STATE_"},
3263             value = {
3264                     SIM_STATE_UNKNOWN,
3265                     SIM_STATE_ABSENT,
3266                     SIM_STATE_PIN_REQUIRED,
3267                     SIM_STATE_PUK_REQUIRED,
3268                     SIM_STATE_NETWORK_LOCKED,
3269                     SIM_STATE_READY,
3270                     SIM_STATE_NOT_READY,
3271                     SIM_STATE_PERM_DISABLED,
3272                     SIM_STATE_CARD_IO_ERROR,
3273                     SIM_STATE_CARD_RESTRICTED,
3274                     SIM_STATE_LOADED,
3275                     SIM_STATE_PRESENT,
3276             })
3277     public @interface SimState {}
3278 
3279     /**
3280      * SIM card state: Unknown. Signifies that the SIM is in transition
3281      * between states. For example, when the user inputs the SIM pin
3282      * under PIN_REQUIRED state, a query for sim status returns
3283      * this state before turning to SIM_STATE_READY.
3284      *
3285      * These are the ordinal value of IccCardConstants.State.
3286      */
3287 
3288     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
3289     /** SIM card state: no SIM card is available in the device */
3290     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3291     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3292     public static final int SIM_STATE_PIN_REQUIRED =
3293             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3294     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3295     public static final int SIM_STATE_PUK_REQUIRED =
3296             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3297     /** SIM card state: Locked: requires a network PIN to unlock */
3298     public static final int SIM_STATE_NETWORK_LOCKED =
3299             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3300     /** SIM card state: Ready */
3301     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3302     /** SIM card state: SIM Card is NOT READY */
3303     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3304     /** SIM card state: SIM Card Error, permanently disabled */
3305     public static final int SIM_STATE_PERM_DISABLED =
3306             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3307     /** SIM card state: SIM Card Error, present but faulty */
3308     public static final int SIM_STATE_CARD_IO_ERROR =
3309             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3310     /** SIM card state: SIM Card restricted, present but not usable due to
3311      * carrier restrictions.
3312      */
3313     public static final int SIM_STATE_CARD_RESTRICTED =
3314             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3315     /**
3316      * SIM card state: Loaded: SIM card applications have been loaded
3317      * @hide
3318      */
3319     @SystemApi
3320     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3321     /**
3322      * SIM card state: SIM Card is present
3323      * @hide
3324      */
3325     @SystemApi
3326     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3327 
3328     /**
3329      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3330      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3331      *
3332      * @hide
3333      */
3334     @SystemApi
3335     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3336 
3337     /**
3338      * Broadcast Action: The sim card state has changed.
3339      * The intent will have the following extra values:</p>
3340      * <dl>
3341      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3342      *   <dd>The sim card state. One of:
3343      *     <dl>
3344      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3345      *       <dd>SIM card not found</dd>
3346      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3347      *       <dd>SIM card IO error</dd>
3348      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3349      *       <dd>SIM card is restricted</dd>
3350      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3351      *       <dd>SIM card is present</dd>
3352      *     </dl>
3353      *   </dd>
3354      * </dl>
3355      *
3356      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3357      *
3358      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3359      *
3360      * <p class="note">This is a protected intent that can only be sent by the system.
3361      * @hide
3362      */
3363     @SystemApi
3364     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3365     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3366             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3367 
3368     /**
3369      * Broadcast Action: The sim application state has changed.
3370      * The intent will have the following extra values:</p>
3371      * <dl>
3372      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3373      *   <dd>The sim application state. One of:
3374      *     <dl>
3375      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3376      *       <dd>SIM card applications not ready</dd>
3377      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3378      *       <dd>SIM card PIN locked</dd>
3379      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3380      *       <dd>SIM card PUK locked</dd>
3381      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3382      *       <dd>SIM card network locked</dd>
3383      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3384      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3385      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3386      *       <dd>SIM card data loaded</dd>
3387      *     </dl>
3388      *   </dd>
3389      * </dl>
3390      *
3391      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3392      *
3393      * <p class="note">The current state can also be queried using
3394      * {@link #getSimApplicationState()}.
3395      *
3396      * <p class="note">This is a protected intent that can only be sent by the system.
3397      * @hide
3398      */
3399     @SystemApi
3400     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3401     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3402             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3403 
3404     /**
3405      * Broadcast Action: Status of the SIM slots on the device has changed.
3406      *
3407      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3408      *
3409      * <p class="note">The status can be queried using
3410      * {@link #getUiccSlotsInfo()}
3411      *
3412      * <p class="note">This is a protected intent that can only be sent by the system.
3413      * @hide
3414      */
3415     @SystemApi
3416     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3417     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3418             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3419 
3420     /**
3421      * Broadcast Action: A debug code has been entered in the dialer.
3422      * <p>
3423      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3424      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3425      * (see {@link #hasCarrierPrivileges}).
3426      * <p>
3427      * These "secret codes" are used to activate developer menus by dialing certain codes.
3428      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3429      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3430      * receiver would be woken up even if it is not currently running.
3431      * <p>
3432      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3433      * in the next Android version.
3434      * Before that both of these two actions will be broadcast.
3435      */
3436     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3437     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3438 
3439     /**
3440      * @return true if a ICC card is present
3441      */
hasIccCard()3442     public boolean hasIccCard() {
3443         return hasIccCard(getSlotIndex());
3444     }
3445 
3446     /**
3447      * @return true if a ICC card is present for a subscription
3448      *
3449      * @param slotIndex for which icc card presence is checked
3450      */
3451     /** {@hide} */
3452     // FIXME Input argument slotIndex should be of type int
3453     @UnsupportedAppUsage
hasIccCard(int slotIndex)3454     public boolean hasIccCard(int slotIndex) {
3455 
3456         try {
3457             ITelephony telephony = getITelephony();
3458             if (telephony == null)
3459                 return false;
3460             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3461         } catch (RemoteException ex) {
3462             // Assume no ICC card if remote exception which shouldn't happen
3463             return false;
3464         } catch (NullPointerException ex) {
3465             // This could happen before phone restarts due to crashing
3466             return false;
3467         }
3468     }
3469 
3470     /**
3471      * Returns a constant indicating the state of the default SIM card.
3472      *
3473      * @see #SIM_STATE_UNKNOWN
3474      * @see #SIM_STATE_ABSENT
3475      * @see #SIM_STATE_PIN_REQUIRED
3476      * @see #SIM_STATE_PUK_REQUIRED
3477      * @see #SIM_STATE_NETWORK_LOCKED
3478      * @see #SIM_STATE_READY
3479      * @see #SIM_STATE_NOT_READY
3480      * @see #SIM_STATE_PERM_DISABLED
3481      * @see #SIM_STATE_CARD_IO_ERROR
3482      * @see #SIM_STATE_CARD_RESTRICTED
3483      */
getSimState()3484     public @SimState int getSimState() {
3485         int simState = getSimStateIncludingLoaded();
3486         if (simState == SIM_STATE_LOADED) {
3487             simState = SIM_STATE_READY;
3488         }
3489         return simState;
3490     }
3491 
getSimStateIncludingLoaded()3492     private @SimState int getSimStateIncludingLoaded() {
3493         int slotIndex = getSlotIndex();
3494         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3495         // sim state
3496         if (slotIndex < 0) {
3497             // query for all slots and return absent if all sim states are absent, otherwise
3498             // return unknown
3499             for (int i = 0; i < getPhoneCount(); i++) {
3500                 int simState = getSimState(i);
3501                 if (simState != SIM_STATE_ABSENT) {
3502                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3503                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3504                     return SIM_STATE_UNKNOWN;
3505                 }
3506             }
3507             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3508                     "state as absent");
3509             return SIM_STATE_ABSENT;
3510         }
3511         return SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3512     }
3513 
3514     /**
3515      * Returns a constant indicating the state of the default SIM card.
3516      *
3517      * @see #SIM_STATE_UNKNOWN
3518      * @see #SIM_STATE_ABSENT
3519      * @see #SIM_STATE_CARD_IO_ERROR
3520      * @see #SIM_STATE_CARD_RESTRICTED
3521      * @see #SIM_STATE_PRESENT
3522      *
3523      * @hide
3524      */
3525     @SystemApi
getSimCardState()3526     public @SimState int getSimCardState() {
3527         int simState = getSimState();
3528         return getSimCardStateFromSimState(simState);
3529     }
3530 
3531     /**
3532      * Returns a constant indicating the state of the device SIM card in a physical slot.
3533      *
3534      * @param physicalSlotIndex physical slot index
3535      *
3536      * @see #SIM_STATE_UNKNOWN
3537      * @see #SIM_STATE_ABSENT
3538      * @see #SIM_STATE_CARD_IO_ERROR
3539      * @see #SIM_STATE_CARD_RESTRICTED
3540      * @see #SIM_STATE_PRESENT
3541      *
3542      * @hide
3543      */
3544     @SystemApi
3545     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimCardState(int physicalSlotIndex)3546     public @SimState int getSimCardState(int physicalSlotIndex) {
3547         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex));
3548         return getSimCardStateFromSimState(simState);
3549     }
3550 
3551     /**
3552      * Converts SIM state to SIM card state.
3553      * @param simState
3554      * @return SIM card state
3555      */
getSimCardStateFromSimState(int simState)3556     private @SimState int getSimCardStateFromSimState(int simState) {
3557         switch (simState) {
3558             case SIM_STATE_UNKNOWN:
3559             case SIM_STATE_ABSENT:
3560             case SIM_STATE_CARD_IO_ERROR:
3561             case SIM_STATE_CARD_RESTRICTED:
3562                 return simState;
3563             default:
3564                 return SIM_STATE_PRESENT;
3565         }
3566     }
3567 
3568     /**
3569      * Converts a physical slot index to logical slot index.
3570      * @param physicalSlotIndex physical slot index
3571      * @return logical slot index
3572      */
getLogicalSlotIndex(int physicalSlotIndex)3573     private int getLogicalSlotIndex(int physicalSlotIndex) {
3574         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3575         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length) {
3576             return slotInfos[physicalSlotIndex].getLogicalSlotIdx();
3577         }
3578 
3579         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3580     }
3581 
3582     /**
3583      * Returns a constant indicating the state of the card applications on the default SIM card.
3584      *
3585      * @see #SIM_STATE_UNKNOWN
3586      * @see #SIM_STATE_PIN_REQUIRED
3587      * @see #SIM_STATE_PUK_REQUIRED
3588      * @see #SIM_STATE_NETWORK_LOCKED
3589      * @see #SIM_STATE_NOT_READY
3590      * @see #SIM_STATE_PERM_DISABLED
3591      * @see #SIM_STATE_LOADED
3592      *
3593      * @hide
3594      */
3595     @SystemApi
getSimApplicationState()3596     public @SimState int getSimApplicationState() {
3597         int simState = getSimStateIncludingLoaded();
3598         return getSimApplicationStateFromSimState(simState);
3599     }
3600 
3601     /**
3602      * Returns a constant indicating the state of the card applications on the device SIM card in
3603      * a physical slot.
3604      *
3605      * @param physicalSlotIndex physical slot index
3606      *
3607      * @see #SIM_STATE_UNKNOWN
3608      * @see #SIM_STATE_PIN_REQUIRED
3609      * @see #SIM_STATE_PUK_REQUIRED
3610      * @see #SIM_STATE_NETWORK_LOCKED
3611      * @see #SIM_STATE_NOT_READY
3612      * @see #SIM_STATE_PERM_DISABLED
3613      * @see #SIM_STATE_LOADED
3614      *
3615      * @hide
3616      */
3617     @SystemApi
3618     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimApplicationState(int physicalSlotIndex)3619     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3620         int simState =
3621                 SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex));
3622         return getSimApplicationStateFromSimState(simState);
3623     }
3624 
3625     /**
3626      * Converts SIM state to SIM application state.
3627      * @param simState
3628      * @return SIM application state
3629      */
getSimApplicationStateFromSimState(int simState)3630     private @SimState int getSimApplicationStateFromSimState(int simState) {
3631         switch (simState) {
3632             case SIM_STATE_UNKNOWN:
3633             case SIM_STATE_ABSENT:
3634             case SIM_STATE_CARD_IO_ERROR:
3635             case SIM_STATE_CARD_RESTRICTED:
3636                 return SIM_STATE_UNKNOWN;
3637             case SIM_STATE_READY:
3638                 // Ready is not a valid state anymore. The state that is broadcast goes from
3639                 // NOT_READY to either LOCKED or LOADED.
3640                 return SIM_STATE_NOT_READY;
3641             default:
3642                 return simState;
3643         }
3644     }
3645 
3646 
3647     /**
3648      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
3649      * on the UICC card.
3650      *
3651      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
3652      *
3653      * @param appType the uicc app type like {@link APPTYPE_CSIM}
3654      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
3655      * @hide
3656      */
3657     @SystemApi
3658     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApplicationOnUicc(@iccAppType int appType)3659     public boolean isApplicationOnUicc(@UiccAppType int appType) {
3660         try {
3661             ITelephony service = getITelephony();
3662             if (service != null) {
3663                 return service.isApplicationOnUicc(getSubId(), appType);
3664             }
3665         } catch (RemoteException e) {
3666             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
3667         }
3668         return false;
3669     }
3670 
3671     /**
3672      * Returns a constant indicating the state of the device SIM card in a logical slot.
3673      *
3674      * @param slotIndex logical slot index
3675      *
3676      * @see #SIM_STATE_UNKNOWN
3677      * @see #SIM_STATE_ABSENT
3678      * @see #SIM_STATE_PIN_REQUIRED
3679      * @see #SIM_STATE_PUK_REQUIRED
3680      * @see #SIM_STATE_NETWORK_LOCKED
3681      * @see #SIM_STATE_READY
3682      * @see #SIM_STATE_NOT_READY
3683      * @see #SIM_STATE_PERM_DISABLED
3684      * @see #SIM_STATE_CARD_IO_ERROR
3685      * @see #SIM_STATE_CARD_RESTRICTED
3686      */
getSimState(int slotIndex)3687     public @SimState int getSimState(int slotIndex) {
3688         int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3689         if (simState == SIM_STATE_LOADED) {
3690             simState = SIM_STATE_READY;
3691         }
3692         return simState;
3693     }
3694 
3695     /**
3696      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3697      * provider of the SIM. 5 or 6 decimal digits.
3698      * <p>
3699      * Availability: SIM state must be {@link #SIM_STATE_READY}
3700      *
3701      * @see #getSimState
3702      */
getSimOperator()3703     public String getSimOperator() {
3704         return getSimOperatorNumeric();
3705     }
3706 
3707     /**
3708      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3709      * provider of the SIM. 5 or 6 decimal digits.
3710      * <p>
3711      * Availability: SIM state must be {@link #SIM_STATE_READY}
3712      *
3713      * @see #getSimState
3714      *
3715      * @param subId for which SimOperator is returned
3716      * @hide
3717      */
3718     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)3719     public String getSimOperator(int subId) {
3720         return getSimOperatorNumeric(subId);
3721     }
3722 
3723     /**
3724      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3725      * provider of the SIM. 5 or 6 decimal digits.
3726      * <p>
3727      * Availability: SIM state must be {@link #SIM_STATE_READY}
3728      *
3729      * @see #getSimState
3730      * @hide
3731      */
3732     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()3733     public String getSimOperatorNumeric() {
3734         int subId = mSubId;
3735         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3736             subId = SubscriptionManager.getDefaultDataSubscriptionId();
3737             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3738                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
3739                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3740                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
3741                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3742                         subId = SubscriptionManager.getDefaultSubscriptionId();
3743                     }
3744                 }
3745             }
3746         }
3747         return getSimOperatorNumeric(subId);
3748     }
3749 
3750     /**
3751      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3752      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3753      * <p>
3754      * Availability: SIM state must be {@link #SIM_STATE_READY}
3755      *
3756      * @see #getSimState
3757      *
3758      * @param subId for which SimOperator is returned
3759      * @hide
3760      */
3761     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)3762     public String getSimOperatorNumeric(int subId) {
3763         int phoneId = SubscriptionManager.getPhoneId(subId);
3764         return getSimOperatorNumericForPhone(phoneId);
3765     }
3766 
3767     /**
3768      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3769      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3770      * <p>
3771      *
3772      * @param phoneId for which SimOperator is returned
3773      * @hide
3774      */
3775     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)3776     public String getSimOperatorNumericForPhone(int phoneId) {
3777         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
3778     }
3779 
3780     /**
3781      * Returns the Service Provider Name (SPN).
3782      * <p>
3783      * Availability: SIM state must be {@link #SIM_STATE_READY}
3784      *
3785      * @see #getSimState
3786      */
getSimOperatorName()3787     public String getSimOperatorName() {
3788         return getSimOperatorNameForPhone(getPhoneId());
3789     }
3790 
3791     /**
3792      * Returns the Service Provider Name (SPN).
3793      * <p>
3794      * Availability: SIM state must be {@link #SIM_STATE_READY}
3795      *
3796      * @see #getSimState
3797      *
3798      * @param subId for which SimOperatorName is returned
3799      * @hide
3800      */
3801     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)3802     public String getSimOperatorName(int subId) {
3803         int phoneId = SubscriptionManager.getPhoneId(subId);
3804         return getSimOperatorNameForPhone(phoneId);
3805     }
3806 
3807     /**
3808      * Returns the Service Provider Name (SPN).
3809      *
3810      * @hide
3811      */
3812     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)3813     public String getSimOperatorNameForPhone(int phoneId) {
3814         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
3815     }
3816 
3817     /**
3818      * Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
3819      * <p>
3820      * The ISO-3166-1 alpha-2 country code is provided in lowercase 2 character format.
3821      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string is not
3822      * available.
3823      */
getSimCountryIso()3824     public String getSimCountryIso() {
3825         return getSimCountryIsoForPhone(getPhoneId());
3826     }
3827 
3828     /**
3829      * Returns the ISO country code equivalent for the SIM provider's country code.
3830      *
3831      * @param subId for which SimCountryIso is returned
3832      * @hide
3833      */
3834     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)3835     public static String getSimCountryIso(int subId) {
3836         int phoneId = SubscriptionManager.getPhoneId(subId);
3837         return getSimCountryIsoForPhone(phoneId);
3838     }
3839 
3840     /**
3841      * Returns the ISO country code equivalent for the SIM provider's country code.
3842      *
3843      * @hide
3844      */
3845     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)3846     public static String getSimCountryIsoForPhone(int phoneId) {
3847         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
3848     }
3849 
3850     /**
3851      * Returns the serial number of the SIM, if applicable. Return null if it is
3852      * unavailable.
3853      *
3854      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
3855      * restrictions, and apps are recommended to use resettable identifiers (see <a
3856      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
3857      * the following requirements is met:
3858      * <ul>
3859      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
3860      *     is a privileged permission that can only be granted to apps preloaded on the device.
3861      *     <li>If the calling app is the device or profile owner and has been granted the
3862      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
3863      *     owns a managed profile on the device; for more details see <a
3864      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
3865      *     Profile owner access is deprecated and will be removed in a future release.
3866      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3867      *     <li>If the calling app is the default SMS role holder (see {@link
3868      *     RoleManager#isRoleHeld(String)}).
3869      * </ul>
3870      *
3871      * <p>If the calling app does not meet one of these requirements then this method will behave
3872      * as follows:
3873      *
3874      * <ul>
3875      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3876      *     READ_PHONE_STATE permission then null is returned.</li>
3877      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3878      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3879      *     higher, then a SecurityException is thrown.</li>
3880      * </ul>
3881      */
3882     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
3883     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimSerialNumber()3884     public String getSimSerialNumber() {
3885          return getSimSerialNumber(getSubId());
3886     }
3887 
3888     /**
3889      * Returns the serial number for the given subscription, if applicable. Return null if it is
3890      * unavailable.
3891      *
3892      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
3893      * restrictions, and apps are recommended to use resettable identifiers (see <a
3894      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
3895      * the following requirements is met:
3896      * <ul>
3897      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
3898      *     is a privileged permission that can only be granted to apps preloaded on the device.
3899      *     <li>If the calling app is the device or profile owner and has been granted the
3900      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
3901      *     owns a managed profile on the device; for more details see <a
3902      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
3903      *     Profile owner access is deprecated and will be removed in a future release.
3904      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3905      *     <li>If the calling app is the default SMS role holder (see {@link
3906      *     RoleManager#isRoleHeld(String)}).
3907      * </ul>
3908      *
3909      * <p>If the calling app does not meet one of these requirements then this method will behave
3910      * as follows:
3911      *
3912      * <ul>
3913      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3914      *     READ_PHONE_STATE permission then null is returned.</li>
3915      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3916      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3917      *     higher, then a SecurityException is thrown.</li>
3918      * </ul>
3919      *
3920      * @param subId for which Sim Serial number is returned
3921      * @hide
3922      */
3923     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3924     @UnsupportedAppUsage
getSimSerialNumber(int subId)3925     public String getSimSerialNumber(int subId) {
3926         try {
3927             IPhoneSubInfo info = getSubscriberInfoService();
3928             if (info == null)
3929                 return null;
3930             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
3931                     mContext.getAttributionTag());
3932         } catch (RemoteException ex) {
3933             return null;
3934         } catch (NullPointerException ex) {
3935             // This could happen before phone restarts due to crashing
3936             return null;
3937         }
3938     }
3939 
3940     /**
3941      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
3942      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
3943      *
3944      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
3945      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
3946      *
3947      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
3948      *         {@code false} if not supported or unknown
3949      * @hide
3950      */
3951     @SystemApi
3952     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isLteCdmaEvdoGsmWcdmaEnabled()3953     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
3954         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
3955     }
3956 
3957     /**
3958      * Return if the current radio is LTE on CDMA for Subscription. This
3959      * is a tri-state return value as for a period of time
3960      * the mode may be unknown.
3961      *
3962      * @param subId for which radio is LTE on CDMA is returned
3963      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
3964      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
3965      * @hide
3966      */
3967     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3968     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)3969     public int getLteOnCdmaMode(int subId) {
3970         try {
3971             ITelephony telephony = getITelephony();
3972             if (telephony == null)
3973                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3974             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
3975                     getAttributionTag());
3976         } catch (RemoteException ex) {
3977             // Assume no ICC card if remote exception which shouldn't happen
3978             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3979         } catch (NullPointerException ex) {
3980             // This could happen before phone restarts due to crashing
3981             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3982         }
3983     }
3984 
3985     /**
3986      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
3987      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
3988      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
3989      *
3990      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
3991      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
3992      * through a factory reset.
3993      *
3994      * @return card ID of the default eUICC card, if loaded.
3995      */
getCardIdForDefaultEuicc()3996     public int getCardIdForDefaultEuicc() {
3997         try {
3998             ITelephony telephony = getITelephony();
3999             if (telephony == null) {
4000                 return UNINITIALIZED_CARD_ID;
4001             }
4002             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
4003         } catch (RemoteException e) {
4004             return UNINITIALIZED_CARD_ID;
4005         }
4006     }
4007 
4008     /**
4009      * Gets information about currently inserted UICCs and eUICCs.
4010      * <p>
4011      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4012      * <p>
4013      * If the caller has carrier priviliges on any active subscription, then they have permission to
4014      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
4015      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the slot index where the card is inserted
4016      * ({@link UiccCardInfo#getSlotIndex()}).
4017      * <p>
4018      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
4019      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
4020      * UICC or eUICC card.
4021      * <p>
4022      * See {@link UiccCardInfo} for more details on the kind of information available.
4023      *
4024      * @return a list of UiccCardInfo objects, representing information on the currently inserted
4025      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
4026      * the caller does not have adequate permissions for that card.
4027      */
4028     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4029     @NonNull
getUiccCardsInfo()4030     public List<UiccCardInfo> getUiccCardsInfo() {
4031         try {
4032             ITelephony telephony = getITelephony();
4033             if (telephony == null) {
4034                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
4035                 return new ArrayList<UiccCardInfo>();
4036             }
4037             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
4038         } catch (RemoteException e) {
4039             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
4040             return new ArrayList<UiccCardInfo>();
4041         }
4042     }
4043 
4044     /**
4045      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
4046      * available, which is possible between phone process starting and getting slot info from modem.
4047      *
4048      * @return UiccSlotInfo array.
4049      *
4050      * @hide
4051      */
4052     @SystemApi
4053     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getUiccSlotsInfo()4054     public UiccSlotInfo[] getUiccSlotsInfo() {
4055         try {
4056             ITelephony telephony = getITelephony();
4057             if (telephony == null) {
4058                 return null;
4059             }
4060             return telephony.getUiccSlotsInfo();
4061         } catch (RemoteException e) {
4062             return null;
4063         }
4064     }
4065 
4066     /**
4067      * Test method to reload the UICC profile.
4068      *
4069      * @hide
4070      */
4071     @TestApi
4072     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()4073     public void refreshUiccProfile() {
4074         try {
4075             ITelephony telephony = getITelephony();
4076             telephony.refreshUiccProfile(mSubId);
4077         } catch (RemoteException ex) {
4078             Rlog.w(TAG, "RemoteException", ex);
4079         }
4080     }
4081 
4082     /**
4083      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
4084      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
4085      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
4086      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
4087      * logical slots.
4088      *
4089      * @param physicalSlots The content of the array represents the physical slot index. The array
4090      *        size should be same as {@link #getUiccSlotsInfo()}.
4091      * @return boolean Return true if the switch succeeds, false if the switch fails.
4092      * @hide
4093      */
4094     @SystemApi
4095     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchSlots(int[] physicalSlots)4096     public boolean switchSlots(int[] physicalSlots) {
4097         try {
4098             ITelephony telephony = getITelephony();
4099             if (telephony == null) {
4100                 return false;
4101             }
4102             return telephony.switchSlots(physicalSlots);
4103         } catch (RemoteException e) {
4104             return false;
4105         }
4106     }
4107 
4108     /**
4109      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
4110      * id and the value is the physical slots id mapped to this logical slot id.
4111      *
4112      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
4113      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
4114      *
4115      * @hide
4116      */
4117     @SystemApi
4118     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4119     @NonNull
getLogicalToPhysicalSlotMapping()4120     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
4121         Map<Integer, Integer> slotMapping = new HashMap<>();
4122         try {
4123             ITelephony telephony = getITelephony();
4124             if (telephony != null) {
4125                 int[] slotMappingArray = telephony.getSlotsMapping();
4126                 for (int i = 0; i < slotMappingArray.length; i++) {
4127                     slotMapping.put(i, slotMappingArray[i]);
4128                 }
4129             }
4130         } catch (RemoteException e) {
4131             Log.e(TAG, "getSlotsMapping RemoteException", e);
4132         }
4133         return slotMapping;
4134     }
4135 
4136     //
4137     //
4138     // Subscriber Info
4139     //
4140     //
4141 
4142     /**
4143      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
4144      * Return null if it is unavailable.
4145      *
4146      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4147      * restrictions, and apps are recommended to use resettable identifiers (see <a
4148      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
4149      * the following requirements is met:
4150      * <ul>
4151      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4152      *     is a privileged permission that can only be granted to apps preloaded on the device.
4153      *     <li>If the calling app is the device or profile owner and has been granted the
4154      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
4155      *     owns a managed profile on the device; for more details see <a
4156      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
4157      *     Profile owner access is deprecated and will be removed in a future release.
4158      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4159      *     <li>If the calling app is the default SMS role holder (see {@link
4160      *     RoleManager#isRoleHeld(String)}).
4161      * </ul>
4162      *
4163      * <p>If the calling app does not meet one of these requirements then this method will behave
4164      * as follows:
4165      *
4166      * <ul>
4167      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4168      *     READ_PHONE_STATE permission then null is returned.</li>
4169      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4170      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4171      *     higher, then a SecurityException is thrown.</li>
4172      * </ul>
4173      */
4174     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4175     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSubscriberId()4176     public String getSubscriberId() {
4177         return getSubscriberId(getSubId());
4178     }
4179 
4180     /**
4181      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
4182      * for a subscription.
4183      * Return null if it is unavailable.
4184      *
4185      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4186      * restrictions, and apps are recommended to use resettable identifiers (see <a
4187      * href="c"> Best practices for unique identifiers</a>). This method can be invoked if one of
4188      * the following requirements is met:
4189      * <ul>
4190      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4191      *     is a privileged permission that can only be granted to apps preloaded on the device.
4192      *     <li>If the calling app is the device or profile owner and has been granted the
4193      *     {@link Manifest.permission#READ_PHONE_STATE} permission. The profile owner is an app that
4194      *     owns a managed profile on the device; for more details see <a
4195      *     href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
4196      *     Profile owner access is deprecated and will be removed in a future release.
4197      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4198      *     <li>If the calling app is the default SMS role holder (see {@link
4199      *     RoleManager#isRoleHeld(String)}).
4200      * </ul>
4201      *
4202      * <p>If the calling app does not meet one of these requirements then this method will behave
4203      * as follows:
4204      *
4205      * <ul>
4206      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4207      *     READ_PHONE_STATE permission then null is returned.</li>
4208      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4209      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4210      *     higher, then a SecurityException is thrown.</li>
4211      * </ul>
4212      *
4213      * @param subId whose subscriber id is returned
4214      * @hide
4215      */
4216     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4217     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)4218     public String getSubscriberId(int subId) {
4219         try {
4220             IPhoneSubInfo info = getSubscriberInfoService();
4221             if (info == null)
4222                 return null;
4223             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
4224                     mContext.getAttributionTag());
4225         } catch (RemoteException ex) {
4226             return null;
4227         } catch (NullPointerException ex) {
4228             // This could happen before phone restarts due to crashing
4229             return null;
4230         }
4231     }
4232 
4233     /**
4234      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
4235      * including the public key and the key identifier; or {@code null} if not available.
4236      * <p>
4237      * For a multi-sim device, the dafault data sim is used if not specified.
4238      * <p>
4239      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
4240      *
4241      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
4242      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
4243      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
4244      *         IMSI and IMPI. This includes the public key and the key identifier. This information
4245      *         will be stored in the device keystore. {@code null} will be returned when no key is
4246      *         found, and the carrier does not require a key.
4247      * @throws IllegalArgumentException when an invalid key is found or when key is required but
4248      *         not found.
4249      * @hide
4250      */
4251     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4252     @SystemApi
4253     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)4254     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
4255         try {
4256             IPhoneSubInfo info = getSubscriberInfoService();
4257             if (info == null) {
4258                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
4259                 return null;
4260             }
4261             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4262             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
4263                 throw new IllegalArgumentException("IMSI error: Invalid key type");
4264             }
4265             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
4266                     subId, keyType, mContext.getOpPackageName());
4267             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
4268                 Rlog.e(TAG, "IMSI error: key is required but not found");
4269                 throw new IllegalArgumentException("IMSI error: key is required but not found");
4270             }
4271             return imsiEncryptionInfo;
4272         } catch (RemoteException ex) {
4273             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4274         } catch (NullPointerException ex) {
4275             // This could happen before phone restarts due to crashing
4276             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
4277         }
4278         return null;
4279     }
4280 
4281     /**
4282      * Resets the carrier keys used to encrypt the IMSI and IMPI.
4283      * <p>
4284      * This involves 2 steps:
4285      *  1. Delete the keys from the database.
4286      *  2. Send an intent to download new Certificates.
4287      * <p>
4288      * For a multi-sim device, the dafault data sim is used if not specified.
4289      * <p>
4290      * Requires Permission: MODIFY_PHONE_STATE.
4291      *
4292      * @see #getCarrierInfoForImsiEncryption
4293      * @hide
4294      */
4295     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4296     @SystemApi
resetCarrierKeysForImsiEncryption()4297     public void resetCarrierKeysForImsiEncryption() {
4298         try {
4299             IPhoneSubInfo info = getSubscriberInfoService();
4300             if (info == null) {
4301                 Rlog.e(TAG, "IMSI error: Subscriber Info is null");
4302                 if (!isSystemProcess()) {
4303                     throw new RuntimeException("IMSI error: Subscriber Info is null");
4304                 }
4305                 return;
4306             }
4307             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4308             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
4309         } catch (RemoteException ex) {
4310             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4311             if (!isSystemProcess()) {
4312                 ex.rethrowAsRuntimeException();
4313             }
4314         }
4315     }
4316 
4317    /**
4318      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
4319      * @param keyType the key type which is being checked. (WLAN, EPDG)
4320      * @return true if the digit at position keyType is 1, else false.
4321      * @hide
4322      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)4323     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
4324         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
4325         return (returnValue == 1) ? true : false;
4326     }
4327 
4328     /**
4329      * If Carrier requires Imsi to be encrypted.
4330      * @hide
4331      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4332     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4333         CarrierConfigManager configManager =
4334                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4335         if (configManager == null) {
4336             return false;
4337         }
4338         PersistableBundle pb = configManager.getConfigForSubId(subId);
4339         if (pb == null) {
4340             return false;
4341         }
4342         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4343         return isKeyEnabled(keyAvailability, keyType);
4344     }
4345 
4346     /**
4347      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4348      * This includes the public key and the key identifier. This information will be stored in the
4349      * device keystore.
4350      * <p>
4351      * Requires Permission:
4352      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4353      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4354      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4355      *        The keyIdentifier Attribute value pair that helps a server locate
4356      *        the private key to decrypt the permanent identity. This field is
4357      *        optional and if it is present then it’s always separated from encrypted
4358      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4359      *        with “name=value” format.
4360      * @hide
4361      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4362     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4363         try {
4364             IPhoneSubInfo info = getSubscriberInfoService();
4365             if (info == null) return;
4366             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4367                     imsiEncryptionInfo);
4368         } catch (NullPointerException ex) {
4369             // This could happen before phone restarts due to crashing
4370             return;
4371         } catch (RemoteException ex) {
4372             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4373             return;
4374         }
4375     }
4376 
4377     /**
4378      * Returns the Group Identifier Level1 for a GSM phone.
4379      * Return null if it is unavailable.
4380      *
4381      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4382      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4383      */
4384     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4385     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getGroupIdLevel1()4386     public String getGroupIdLevel1() {
4387         try {
4388             IPhoneSubInfo info = getSubscriberInfoService();
4389             if (info == null)
4390                 return null;
4391             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
4392                     mContext.getAttributionTag());
4393         } catch (RemoteException ex) {
4394             return null;
4395         } catch (NullPointerException ex) {
4396             // This could happen before phone restarts due to crashing
4397             return null;
4398         }
4399     }
4400 
4401     /**
4402      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
4403      * Return null if it is unavailable.
4404      *
4405      * @param subId whose subscriber id is returned
4406      * @hide
4407      */
4408     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4409     @UnsupportedAppUsage
getGroupIdLevel1(int subId)4410     public String getGroupIdLevel1(int subId) {
4411         try {
4412             IPhoneSubInfo info = getSubscriberInfoService();
4413             if (info == null)
4414                 return null;
4415             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
4416                     mContext.getAttributionTag());
4417         } catch (RemoteException ex) {
4418             return null;
4419         } catch (NullPointerException ex) {
4420             // This could happen before phone restarts due to crashing
4421             return null;
4422         }
4423     }
4424 
4425     /**
4426      * Returns the phone number string for line 1, for example, the MSISDN
4427      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4428      * <p>
4429      * The default SMS app can also use this.
4430      *
4431      * <p>Requires Permission:
4432      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4433      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4434      *     that the caller is the default SMS app,
4435      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4436      *     for any API level.
4437      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4438      *     for apps targeting SDK API level 29 and below.
4439      */
4440     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
4441     @RequiresPermission(anyOf = {
4442             android.Manifest.permission.READ_PHONE_STATE,
4443             android.Manifest.permission.READ_SMS,
4444             android.Manifest.permission.READ_PHONE_NUMBERS
4445     })
getLine1Number()4446     public String getLine1Number() {
4447         return getLine1Number(getSubId());
4448     }
4449 
4450     /**
4451      * Returns the phone number string for line 1, for example, the MSISDN
4452      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4453      * <p>
4454      * The default SMS app can also use this.
4455      *
4456      * <p>Requires Permission:
4457      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4458      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4459      *     that the caller is the default SMS app,
4460      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4461      *     for any API level.
4462      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4463      *     for apps targeting SDK API level 29 and below.
4464      *
4465      * @param subId whose phone number for line 1 is returned
4466      * @hide
4467      */
4468     @RequiresPermission(anyOf = {
4469             android.Manifest.permission.READ_PHONE_STATE,
4470             android.Manifest.permission.READ_SMS,
4471             android.Manifest.permission.READ_PHONE_NUMBERS
4472     })
4473     @UnsupportedAppUsage
getLine1Number(int subId)4474     public String getLine1Number(int subId) {
4475         String number = null;
4476         try {
4477             ITelephony telephony = getITelephony();
4478             if (telephony != null)
4479                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
4480                          mContext.getAttributionTag());
4481         } catch (RemoteException ex) {
4482         } catch (NullPointerException ex) {
4483         }
4484         if (number != null) {
4485             return number;
4486         }
4487         try {
4488             IPhoneSubInfo info = getSubscriberInfoService();
4489             if (info == null)
4490                 return null;
4491             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
4492                     mContext.getAttributionTag());
4493         } catch (RemoteException ex) {
4494             return null;
4495         } catch (NullPointerException ex) {
4496             // This could happen before phone restarts due to crashing
4497             return null;
4498         }
4499     }
4500 
4501     /**
4502      * Set the line 1 phone number string and its alphatag for the current ICCID
4503      * for display purpose only, for example, displayed in Phone Status. It won't
4504      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4505      * value.
4506      *
4507      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4508      *
4509      * @param alphaTag alpha-tagging of the dailing nubmer
4510      * @param number The dialing number
4511      * @return true if the operation was executed correctly.
4512      */
setLine1NumberForDisplay(String alphaTag, String number)4513     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
4514         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
4515     }
4516 
4517     /**
4518      * Set the line 1 phone number string and its alphatag for the current ICCID
4519      * for display purpose only, for example, displayed in Phone Status. It won't
4520      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4521      * value.
4522      *
4523      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4524      *
4525      * @param subId the subscriber that the alphatag and dialing number belongs to.
4526      * @param alphaTag alpha-tagging of the dailing nubmer
4527      * @param number The dialing number
4528      * @return true if the operation was executed correctly.
4529      * @hide
4530      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)4531     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
4532         try {
4533             ITelephony telephony = getITelephony();
4534             if (telephony != null)
4535                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
4536         } catch (RemoteException ex) {
4537         } catch (NullPointerException ex) {
4538         }
4539         return false;
4540     }
4541 
4542     /**
4543      * Returns the alphabetic identifier associated with the line 1 number.
4544      * Return null if it is unavailable.
4545      * @hide
4546      * nobody seems to call this.
4547      */
4548     @UnsupportedAppUsage
4549     @TestApi
4550     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()4551     public String getLine1AlphaTag() {
4552         return getLine1AlphaTag(getSubId());
4553     }
4554 
4555     /**
4556      * Returns the alphabetic identifier associated with the line 1 number
4557      * for a subscription.
4558      * Return null if it is unavailable.
4559      * @param subId whose alphabetic identifier associated with line 1 is returned
4560      * nobody seems to call this.
4561      * @hide
4562      */
4563     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4564     @UnsupportedAppUsage
getLine1AlphaTag(int subId)4565     public String getLine1AlphaTag(int subId) {
4566         String alphaTag = null;
4567         try {
4568             ITelephony telephony = getITelephony();
4569             if (telephony != null)
4570                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
4571                         getOpPackageName(), getAttributionTag());
4572         } catch (RemoteException ex) {
4573         } catch (NullPointerException ex) {
4574         }
4575         if (alphaTag != null) {
4576             return alphaTag;
4577         }
4578         try {
4579             IPhoneSubInfo info = getSubscriberInfoService();
4580             if (info == null)
4581                 return null;
4582             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
4583                     getAttributionTag());
4584         } catch (RemoteException ex) {
4585             return null;
4586         } catch (NullPointerException ex) {
4587             // This could happen before phone restarts due to crashing
4588             return null;
4589         }
4590     }
4591 
4592     /**
4593      * Return the set of subscriber IDs that should be considered "merged together" for data usage
4594      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
4595      * subscribers are sorted in a deterministic order.
4596      * <p>
4597      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
4598      * TelephonyManager's subId.
4599      *
4600      * This is deprecated and {@link #getMergedImsisFromGroup()} should be used for data
4601      * usage merging purpose.
4602      * TODO: remove this API.
4603      *
4604      * @hide
4605      */
4606     @UnsupportedAppUsage
4607     @Deprecated
getMergedSubscriberIds()4608     public @Nullable String[] getMergedSubscriberIds() {
4609         try {
4610             ITelephony telephony = getITelephony();
4611             if (telephony != null)
4612                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
4613                         getAttributionTag());
4614         } catch (RemoteException ex) {
4615         } catch (NullPointerException ex) {
4616         }
4617         return null;
4618     }
4619 
4620     /**
4621      * Return the set of IMSIs that should be considered "merged together" for data usage
4622      * purposes. Unlike {@link #getMergedSubscriberIds()} this API merge IMSIs based on
4623      * subscription grouping: IMSI of those in the same group will all be returned.
4624      * Return the current IMSI if there is no subscription group.
4625      *
4626      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
4627      *
4628      * @hide
4629      */
4630     @SystemApi
4631     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMergedImsisFromGroup()4632     public @NonNull String[] getMergedImsisFromGroup() {
4633         try {
4634             ITelephony telephony = getITelephony();
4635             if (telephony != null) {
4636                 return telephony.getMergedImsisFromGroup(getSubId(), getOpPackageName());
4637             }
4638         } catch (RemoteException ex) {
4639         } catch (NullPointerException ex) {
4640         }
4641         return new String[0];
4642     }
4643 
4644     /**
4645      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4646      *
4647      * <p>Requires Permission:
4648      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4649      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4650      *     that the caller is the default SMS app,
4651      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4652      *     for any API level.
4653      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4654      *     for apps targeting SDK API level 29 and below.
4655      *
4656      * @hide
4657      */
4658     @RequiresPermission(anyOf = {
4659             android.Manifest.permission.READ_PHONE_STATE,
4660             android.Manifest.permission.READ_SMS,
4661             android.Manifest.permission.READ_PHONE_NUMBERS
4662     })
4663     @UnsupportedAppUsage
getMsisdn()4664     public String getMsisdn() {
4665         return getMsisdn(getSubId());
4666     }
4667 
4668     /**
4669      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4670      *
4671      * @param subId for which msisdn is returned
4672      *
4673      * <p>Requires Permission:
4674      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4675      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4676      *     that the caller is the default SMS app,
4677      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4678      *     for any API level.
4679      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4680      *     for apps targeting SDK API level 29 and below.
4681      *
4682      * @hide
4683      */
4684     @RequiresPermission(anyOf = {
4685             android.Manifest.permission.READ_PHONE_STATE,
4686             android.Manifest.permission.READ_SMS,
4687             android.Manifest.permission.READ_PHONE_NUMBERS
4688     })
4689     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)4690     public String getMsisdn(int subId) {
4691         try {
4692             IPhoneSubInfo info = getSubscriberInfoService();
4693             if (info == null)
4694                 return null;
4695             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
4696         } catch (RemoteException ex) {
4697             return null;
4698         } catch (NullPointerException ex) {
4699             // This could happen before phone restarts due to crashing
4700             return null;
4701         }
4702     }
4703 
4704     /**
4705      * Returns the voice mail number. Return null if it is unavailable.
4706      *
4707      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4708      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4709      */
4710     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4711     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailNumber()4712     public String getVoiceMailNumber() {
4713         return getVoiceMailNumber(getSubId());
4714     }
4715 
4716     /**
4717      * Returns the voice mail number for a subscription.
4718      * Return null if it is unavailable.
4719      * @param subId whose voice mail number is returned
4720      * @hide
4721      */
4722     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4723     @UnsupportedAppUsage
getVoiceMailNumber(int subId)4724     public String getVoiceMailNumber(int subId) {
4725         try {
4726             IPhoneSubInfo info = getSubscriberInfoService();
4727             if (info == null)
4728                 return null;
4729             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
4730                     getAttributionTag());
4731         } catch (RemoteException ex) {
4732             return null;
4733         } catch (NullPointerException ex) {
4734             // This could happen before phone restarts due to crashing
4735             return null;
4736         }
4737     }
4738 
4739     /**
4740      * Sets the voice mail number.
4741      *
4742      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4743      *
4744      * @param alphaTag The alpha tag to display.
4745      * @param number The voicemail number.
4746      */
setVoiceMailNumber(String alphaTag, String number)4747     public boolean setVoiceMailNumber(String alphaTag, String number) {
4748         return setVoiceMailNumber(getSubId(), alphaTag, number);
4749     }
4750 
4751     /**
4752      * Sets the voicemail number for the given subscriber.
4753      *
4754      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4755      *
4756      * @param subId The subscription id.
4757      * @param alphaTag The alpha tag to display.
4758      * @param number The voicemail number.
4759      * @hide
4760      */
setVoiceMailNumber(int subId, String alphaTag, String number)4761     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
4762         try {
4763             ITelephony telephony = getITelephony();
4764             if (telephony != null)
4765                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
4766         } catch (RemoteException ex) {
4767         } catch (NullPointerException ex) {
4768         }
4769         return false;
4770     }
4771 
4772     /**
4773      * Enables or disables the visual voicemail client for a phone account.
4774      *
4775      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
4776      * {@link #hasCarrierPrivileges}), or has permission
4777      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
4778      *
4779      * @param phoneAccountHandle the phone account to change the client state
4780      * @param enabled the new state of the client
4781      * @hide
4782      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
4783      * be implemented instead.
4784      */
4785     @SystemApi
4786     @SuppressLint("Doclava125")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)4787     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
4788     }
4789 
4790     /**
4791      * Returns whether the visual voicemail client is enabled.
4792      *
4793      * @param phoneAccountHandle the phone account to check for.
4794      * @return {@code true} when the visual voicemail client is enabled for this client
4795      * @hide
4796      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
4797      * be implemented instead.
4798      */
4799     @SystemApi
4800     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4801     @SuppressLint("Doclava125")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)4802     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
4803         return false;
4804     }
4805 
4806     /**
4807      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
4808      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
4809      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
4810      * voicemail client in telephony.
4811      *
4812      * <p>Requires the caller to be the system dialer.
4813      *
4814      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
4815      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
4816      *
4817      * @hide
4818      */
4819     @SystemApi
4820     @SuppressLint("Doclava125")
4821     @Nullable
getVisualVoicemailSettings()4822     public Bundle getVisualVoicemailSettings(){
4823         try {
4824             ITelephony telephony = getITelephony();
4825             if (telephony != null) {
4826                 return telephony
4827                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
4828             }
4829         } catch (RemoteException ex) {
4830         } catch (NullPointerException ex) {
4831         }
4832         return null;
4833     }
4834 
4835     /**
4836      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
4837      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
4838      * processing visual voicemail for the subscription.
4839      *
4840      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4841      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4842      *
4843      * @see #createForSubscriptionId(int)
4844      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
4845      * @see VisualVoicemailService
4846      */
4847     @Nullable
4848     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4849     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVisualVoicemailPackageName()4850     public String getVisualVoicemailPackageName() {
4851         try {
4852             ITelephony telephony = getITelephony();
4853             if (telephony != null) {
4854                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
4855                         getAttributionTag(), getSubId());
4856             }
4857         } catch (RemoteException ex) {
4858         } catch (NullPointerException ex) {
4859         }
4860         return null;
4861     }
4862 
4863     /**
4864      * Set the visual voicemail SMS filter settings for the subscription ID pinned
4865      * to the TelephonyManager.
4866      * When the filter is enabled, {@link
4867      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
4868      * called when a SMS matching the settings is received. Caller must be the default dialer,
4869      * system dialer, or carrier visual voicemail app.
4870      *
4871      * @param settings The settings for the filter, or {@code null} to disable the filter.
4872      *
4873      * @see TelecomManager#getDefaultDialerPackage()
4874      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
4875      */
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)4876     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
4877         if (settings == null) {
4878             disableVisualVoicemailSmsFilter(mSubId);
4879         } else {
4880             enableVisualVoicemailSmsFilter(mSubId, settings);
4881         }
4882     }
4883 
4884     /**
4885      * Send a visual voicemail SMS. The caller must be the current default dialer.
4886      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
4887      * visual voicemail server.  Some examples for carriers using the OMTP standard include
4888      * activating and deactivating visual voicemail, or requesting the current visual voicemail
4889      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
4890      * format of these SMS messages.
4891      *
4892      * <p>Requires Permission:
4893      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
4894      *
4895      * @param number The destination number.
4896      * @param port The destination port for data SMS, or 0 for text SMS.
4897      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
4898      * @param sentIntent The sent intent passed to the {@link SmsManager}
4899      *
4900      * @throws SecurityException if the caller is not the current default dialer
4901      *
4902      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
4903      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
4904      */
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)4905     public void sendVisualVoicemailSms(String number, int port, String text,
4906             PendingIntent sentIntent) {
4907         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
4908     }
4909 
4910     /**
4911      * Enables the visual voicemail SMS filter for a phone account. When the filter is
4912      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
4913      * visual voicemail client with
4914      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
4915      *
4916      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4917      * settings persist through default dialer changes, but the filter will only honor the setting
4918      * set by the current default dialer.
4919      *
4920      *
4921      * @param subId The subscription id of the phone account.
4922      * @param settings The settings for the filter.
4923      */
4924     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)4925     public void enableVisualVoicemailSmsFilter(int subId,
4926             VisualVoicemailSmsFilterSettings settings) {
4927         if(settings == null){
4928             throw new IllegalArgumentException("Settings cannot be null");
4929         }
4930         try {
4931             ITelephony telephony = getITelephony();
4932             if (telephony != null) {
4933                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
4934                         settings);
4935             }
4936         } catch (RemoteException ex) {
4937         } catch (NullPointerException ex) {
4938         }
4939     }
4940 
4941     /**
4942      * Disables the visual voicemail SMS filter for a phone account.
4943      *
4944      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4945      * settings persist through default dialer changes, but the filter will only honor the setting
4946      * set by the current default dialer.
4947      */
4948     /** @hide */
disableVisualVoicemailSmsFilter(int subId)4949     public void disableVisualVoicemailSmsFilter(int subId) {
4950         try {
4951             ITelephony telephony = getITelephony();
4952             if (telephony != null) {
4953                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
4954             }
4955         } catch (RemoteException ex) {
4956         } catch (NullPointerException ex) {
4957         }
4958     }
4959 
4960     /**
4961      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
4962      * if the filter is disabled.
4963      *
4964      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4965      * settings persist through default dialer changes, but the filter will only honor the setting
4966      * set by the current default dialer.
4967      */
4968     /** @hide */
4969     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)4970     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
4971         try {
4972             ITelephony telephony = getITelephony();
4973             if (telephony != null) {
4974                 return telephony
4975                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
4976             }
4977         } catch (RemoteException ex) {
4978         } catch (NullPointerException ex) {
4979         }
4980 
4981         return null;
4982     }
4983 
4984     /**
4985      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
4986      * current active visual voicemail client, or {@code null} if the filter is disabled.
4987      *
4988      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
4989      */
4990     /** @hide */
4991     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)4992     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
4993         try {
4994             ITelephony telephony = getITelephony();
4995             if (telephony != null) {
4996                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
4997             }
4998         } catch (RemoteException ex) {
4999         } catch (NullPointerException ex) {
5000         }
5001 
5002         return null;
5003     }
5004 
5005     /**
5006      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
5007      *
5008      * @param phoneAccountHandle The account to send the SMS with.
5009      * @param number The destination number.
5010      * @param port The destination port for data SMS, or 0 for text SMS.
5011      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5012      * @param sentIntent The sent intent passed to the {@link SmsManager}
5013      *
5014      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5015      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5016      *
5017      * @hide
5018      */
5019     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)5020     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
5021             String text, PendingIntent sentIntent) {
5022         try {
5023             ITelephony telephony = getITelephony();
5024             if (telephony != null) {
5025                 telephony.sendVisualVoicemailSmsForSubscriber(
5026                         mContext.getOpPackageName(), mContext.getAttributionTag(), subId, number,
5027                         port, text, sentIntent);
5028             }
5029         } catch (RemoteException ex) {
5030         }
5031     }
5032 
5033     /**
5034      * Initial SIM activation state, unknown. Not set by any carrier apps.
5035      * @hide
5036      */
5037     @SystemApi
5038     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
5039 
5040     /**
5041      * indicate SIM is under activation procedure now.
5042      * intermediate state followed by another state update with activation procedure result:
5043      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5044      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5045      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5046      * @hide
5047      */
5048     @SystemApi
5049     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
5050 
5051     /**
5052      * Indicate SIM has been successfully activated with full service
5053      * @hide
5054      */
5055     @SystemApi
5056     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
5057 
5058     /**
5059      * Indicate SIM has been deactivated by the carrier so that service is not available
5060      * and requires activation service to enable services.
5061      * Carrier apps could be signalled to set activation state to deactivated if detected
5062      * deactivated sim state and set it back to activated after successfully run activation service.
5063      * @hide
5064      */
5065     @SystemApi
5066     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
5067 
5068     /**
5069      * Restricted state indicate SIM has been activated but service are restricted.
5070      * note this is currently available for data activation state. For example out of byte sim.
5071      * @hide
5072      */
5073     @SystemApi
5074     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
5075 
5076      /**
5077       * Sets the voice activation state
5078       *
5079       * <p>Requires Permission:
5080       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5081       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5082       *
5083       * @param activationState The voice activation state
5084       * @see #SIM_ACTIVATION_STATE_UNKNOWN
5085       * @see #SIM_ACTIVATION_STATE_ACTIVATING
5086       * @see #SIM_ACTIVATION_STATE_ACTIVATED
5087       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5088       * @hide
5089       */
5090     @SystemApi
5091     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(@imActivationState int activationState)5092     public void setVoiceActivationState(@SimActivationState int activationState) {
5093         setVoiceActivationState(getSubId(), activationState);
5094     }
5095 
5096     /**
5097      * Sets the voice activation state for the given subscriber.
5098      *
5099      * <p>Requires Permission:
5100      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5101      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5102      *
5103      * @param subId The subscription id.
5104      * @param activationState The voice activation state of the given subscriber.
5105      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5106      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5107      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5108      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5109      * @hide
5110      */
5111     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)5112     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
5113         try {
5114            ITelephony telephony = getITelephony();
5115            if (telephony != null)
5116                telephony.setVoiceActivationState(subId, activationState);
5117        } catch (RemoteException ex) {
5118        } catch (NullPointerException ex) {
5119        }
5120     }
5121 
5122     /**
5123      * Sets the data activation state
5124      *
5125      * <p>Requires Permission:
5126      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5127      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5128      *
5129      * @param activationState The data activation state
5130      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5131      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5132      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5133      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5134      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5135      * @hide
5136      */
5137     @SystemApi
5138     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(@imActivationState int activationState)5139     public void setDataActivationState(@SimActivationState int activationState) {
5140         setDataActivationState(getSubId(), activationState);
5141     }
5142 
5143     /**
5144      * Sets the data activation state for the given subscriber.
5145      *
5146      * <p>Requires Permission:
5147      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5148      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5149      *
5150      * @param subId The subscription id.
5151      * @param activationState The data activation state of the given subscriber.
5152      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5153      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5154      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5155      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5156      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5157      * @hide
5158      */
5159     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)5160     public void setDataActivationState(int subId, @SimActivationState int activationState) {
5161         try {
5162             ITelephony telephony = getITelephony();
5163             if (telephony != null)
5164                 telephony.setDataActivationState(subId, activationState);
5165         } catch (RemoteException ex) {
5166         } catch (NullPointerException ex) {
5167         }
5168     }
5169 
5170     /**
5171      * Returns the voice activation state
5172      *
5173      * <p>Requires Permission:
5174      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5175      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5176      *
5177      * @return voiceActivationState
5178      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5179      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5180      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5181      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5182      * @hide
5183      */
5184     @SystemApi
5185     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState()5186     public @SimActivationState int getVoiceActivationState() {
5187         return getVoiceActivationState(getSubId());
5188     }
5189 
5190     /**
5191      * Returns the voice activation state for the given subscriber.
5192      *
5193      * <p>Requires Permission:
5194      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5195      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5196      *
5197      * @param subId The subscription id.
5198      *
5199      * @return voiceActivationState for the given subscriber
5200      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5201      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5202      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5203      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5204      * @hide
5205      */
5206     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)5207     public @SimActivationState int getVoiceActivationState(int subId) {
5208         try {
5209             ITelephony telephony = getITelephony();
5210             if (telephony != null)
5211                 return telephony.getVoiceActivationState(subId, getOpPackageName());
5212         } catch (RemoteException ex) {
5213         } catch (NullPointerException ex) {
5214         }
5215         return SIM_ACTIVATION_STATE_UNKNOWN;
5216     }
5217 
5218     /**
5219      * Returns the data activation state
5220      *
5221      * <p>Requires Permission:
5222      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5223      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5224      *
5225      * @return dataActivationState for the given subscriber
5226      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5227      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5228      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5229      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5230      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5231      * @hide
5232      */
5233     @SystemApi
5234     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState()5235     public @SimActivationState int getDataActivationState() {
5236         return getDataActivationState(getSubId());
5237     }
5238 
5239     /**
5240      * Returns the data activation state for the given subscriber.
5241      *
5242      * <p>Requires Permission:
5243      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5244      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5245      *
5246      * @param subId The subscription id.
5247      *
5248      * @return dataActivationState for the given subscriber
5249      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5250      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5251      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5252      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5253      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5254      * @hide
5255      */
5256     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)5257     public @SimActivationState int getDataActivationState(int subId) {
5258         try {
5259             ITelephony telephony = getITelephony();
5260             if (telephony != null)
5261                 return telephony.getDataActivationState(subId, getOpPackageName());
5262         } catch (RemoteException ex) {
5263         } catch (NullPointerException ex) {
5264         }
5265         return SIM_ACTIVATION_STATE_UNKNOWN;
5266     }
5267 
5268     /**
5269      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
5270      * but the count is unknown.
5271      * @hide
5272      */
5273     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5274     @UnsupportedAppUsage
getVoiceMessageCount()5275     public int getVoiceMessageCount() {
5276         return getVoiceMessageCount(getSubId());
5277     }
5278 
5279     /**
5280      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
5281      * not have the READ_PHONE_STATE permission.
5282      * @param subId whose voice message count is returned
5283      * @hide
5284      */
5285     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5286     @UnsupportedAppUsage
getVoiceMessageCount(int subId)5287     public int getVoiceMessageCount(int subId) {
5288         try {
5289             ITelephony telephony = getITelephony();
5290             if (telephony == null)
5291                 return 0;
5292             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
5293                     getAttributionTag());
5294         } catch (RemoteException ex) {
5295             return 0;
5296         } catch (NullPointerException ex) {
5297             // This could happen before phone restarts due to crashing
5298             return 0;
5299         }
5300     }
5301 
5302     /**
5303      * Retrieves the alphabetic identifier associated with the voice
5304      * mail number.
5305      *
5306      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5307      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5308      */
5309     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5310     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailAlphaTag()5311     public String getVoiceMailAlphaTag() {
5312         return getVoiceMailAlphaTag(getSubId());
5313     }
5314 
5315     /**
5316      * Retrieves the alphabetic identifier associated with the voice
5317      * mail number for a subscription.
5318      * @param subId whose alphabetic identifier associated with the
5319      * voice mail number is returned
5320      * @hide
5321      */
5322     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5323     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)5324     public String getVoiceMailAlphaTag(int subId) {
5325         try {
5326             IPhoneSubInfo info = getSubscriberInfoService();
5327             if (info == null)
5328                 return null;
5329             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
5330                     getAttributionTag());
5331         } catch (RemoteException ex) {
5332             return null;
5333         } catch (NullPointerException ex) {
5334             // This could happen before phone restarts due to crashing
5335             return null;
5336         }
5337     }
5338 
5339     /**
5340      * Send the special dialer code. The IPC caller must be the current default dialer or have
5341      * carrier privileges (see {@link #hasCarrierPrivileges}).
5342      *
5343      * @param inputCode The special dialer code to send
5344      *
5345      * @throws SecurityException if the caller does not have carrier privileges or is not the
5346      *         current default dialer
5347      */
sendDialerSpecialCode(String inputCode)5348     public void sendDialerSpecialCode(String inputCode) {
5349         try {
5350             final ITelephony telephony = getITelephony();
5351             if (telephony == null) {
5352                 if (!isSystemProcess()) {
5353                     throw new RuntimeException("Telephony service unavailable");
5354                 }
5355                 return;
5356             }
5357             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
5358         } catch (RemoteException ex) {
5359             // This could happen if binder process crashes.
5360             if (!isSystemProcess()) {
5361                 ex.rethrowAsRuntimeException();
5362             }
5363         }
5364     }
5365 
5366     /**
5367      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
5368      * @return the IMPI, or null if not present or not loaded
5369      * @hide
5370      */
5371     @UnsupportedAppUsage
getIsimImpi()5372     public String getIsimImpi() {
5373         try {
5374             IPhoneSubInfo info = getSubscriberInfoService();
5375             if (info == null)
5376                 return null;
5377             //get the Isim Impi based on subId
5378             return info.getIsimImpi(getSubId());
5379         } catch (RemoteException ex) {
5380             return null;
5381         } catch (NullPointerException ex) {
5382             // This could happen before phone restarts due to crashing
5383             return null;
5384         }
5385     }
5386 
5387     /**
5388      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
5389      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
5390      * hasn't been loaded or isn't present on the ISIM.
5391      *
5392      * <p>Requires Permission:
5393      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5394      * @hide
5395      */
5396     @Nullable
5397     @SystemApi
5398     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimDomain()5399     public String getIsimDomain() {
5400         try {
5401             IPhoneSubInfo info = getSubscriberInfoService();
5402             if (info == null)
5403                 return null;
5404             //get the Isim Domain based on subId
5405             return info.getIsimDomain(getSubId());
5406         } catch (RemoteException ex) {
5407             return null;
5408         } catch (NullPointerException ex) {
5409             // This could happen before phone restarts due to crashing
5410             return null;
5411         }
5412     }
5413 
5414     /**
5415      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
5416      * @return an array of IMPU strings, with one IMPU per string, or null if
5417      *      not present or not loaded
5418      * @hide
5419      */
5420     @UnsupportedAppUsage
5421     @Nullable
5422     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()5423     public String[] getIsimImpu() {
5424         try {
5425             IPhoneSubInfo info = getSubscriberInfoService();
5426             if (info == null)
5427                 return null;
5428             //get the Isim Impu based on subId
5429             return info.getIsimImpu(getSubId());
5430         } catch (RemoteException ex) {
5431             return null;
5432         } catch (NullPointerException ex) {
5433             // This could happen before phone restarts due to crashing
5434             return null;
5435         }
5436     }
5437 
5438     /**
5439      * Device call state: No activity.
5440      */
5441     public static final int CALL_STATE_IDLE = 0;
5442     /**
5443      * Device call state: Ringing. A new call arrived and is
5444      *  ringing or waiting. In the latter case, another call is
5445      *  already active.
5446      */
5447     public static final int CALL_STATE_RINGING = 1;
5448     /**
5449      * Device call state: Off-hook. At least one call exists
5450      * that is dialing, active, or on hold, and no calls are ringing
5451      * or waiting.
5452      */
5453     public static final int CALL_STATE_OFFHOOK = 2;
5454 
5455     /**
5456      * Returns the state of all calls on the device.
5457      * <p>
5458      * This method considers not only calls in the Telephony stack, but also calls via other
5459      * {@link android.telecom.ConnectionService} implementations.
5460      * <p>
5461      * Note: The call state returned via this method may differ from what is reported by
5462      * {@link PhoneStateListener#onCallStateChanged(int, String)}, as that callback only considers
5463      * Telephony (mobile) calls.
5464      *
5465      * @return the current call state.
5466      */
getCallState()5467     public @CallState int getCallState() {
5468         if (mContext != null) {
5469             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
5470             if (telecomManager != null) {
5471                 return telecomManager.getCallState();
5472             }
5473         }
5474         return CALL_STATE_IDLE;
5475     }
5476 
5477     /**
5478      * Returns the Telephony call state for calls on a specific subscription.
5479      * <p>
5480      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5481      * considers the state of calls from other {@link android.telecom.ConnectionService}
5482      * implementations.
5483      *
5484      * @param subId the subscription to check call state for.
5485      * @hide
5486      */
5487     @UnsupportedAppUsage
getCallState(int subId)5488     public @CallState int getCallState(int subId) {
5489         int phoneId = SubscriptionManager.getPhoneId(subId);
5490         return getCallStateForSlot(phoneId);
5491     }
5492 
5493     /**
5494     * @hide
5495     */
5496     @UnsupportedAppUsage
getSubscriberInfo()5497     private IPhoneSubInfo getSubscriberInfo() {
5498         return getSubscriberInfoService();
5499     }
5500 
5501     /**
5502      * Returns the Telephony call state for calls on a specific SIM slot.
5503      * <p>
5504      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5505      * considers the state of calls from other {@link android.telecom.ConnectionService}
5506      * implementations.
5507      *
5508      * @param slotIndex the SIM slot index to check call state for.
5509      * @hide
5510      */
getCallStateForSlot(int slotIndex)5511     public @CallState int getCallStateForSlot(int slotIndex) {
5512         try {
5513             ITelephony telephony = getITelephony();
5514             if (telephony == null)
5515                 return CALL_STATE_IDLE;
5516             return telephony.getCallStateForSlot(slotIndex);
5517         } catch (RemoteException ex) {
5518             // the phone process is restarting.
5519             return CALL_STATE_IDLE;
5520         } catch (NullPointerException ex) {
5521           // the phone process is restarting.
5522           return CALL_STATE_IDLE;
5523         }
5524     }
5525 
5526 
5527     /** Data connection activity: No traffic. */
5528     public static final int DATA_ACTIVITY_NONE = 0x00000000;
5529     /** Data connection activity: Currently receiving IP PPP traffic. */
5530     public static final int DATA_ACTIVITY_IN = 0x00000001;
5531     /** Data connection activity: Currently sending IP PPP traffic. */
5532     public static final int DATA_ACTIVITY_OUT = 0x00000002;
5533     /** Data connection activity: Currently both sending and receiving
5534      *  IP PPP traffic. */
5535     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
5536     /**
5537      * Data connection is active, but physical link is down
5538      */
5539     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
5540 
5541     /**
5542      * Returns a constant indicating the type of activity on a data connection
5543      * (cellular).
5544      *
5545      * @see #DATA_ACTIVITY_NONE
5546      * @see #DATA_ACTIVITY_IN
5547      * @see #DATA_ACTIVITY_OUT
5548      * @see #DATA_ACTIVITY_INOUT
5549      * @see #DATA_ACTIVITY_DORMANT
5550      */
getDataActivity()5551     public int getDataActivity() {
5552         try {
5553             ITelephony telephony = getITelephony();
5554             if (telephony == null)
5555                 return DATA_ACTIVITY_NONE;
5556             return telephony.getDataActivityForSubId(
5557                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5558         } catch (RemoteException ex) {
5559             // the phone process is restarting.
5560             return DATA_ACTIVITY_NONE;
5561         } catch (NullPointerException ex) {
5562           // the phone process is restarting.
5563           return DATA_ACTIVITY_NONE;
5564       }
5565     }
5566 
5567     /** @hide */
5568     @IntDef(prefix = {"DATA_"}, value = {
5569             DATA_UNKNOWN,
5570             DATA_DISCONNECTED,
5571             DATA_CONNECTING,
5572             DATA_CONNECTED,
5573             DATA_SUSPENDED,
5574             DATA_DISCONNECTING,
5575     })
5576     @Retention(RetentionPolicy.SOURCE)
5577     public @interface DataState{}
5578 
5579     /** Data connection state: Unknown.  Used before we know the state. */
5580     public static final int DATA_UNKNOWN        = -1;
5581     /** Data connection state: Disconnected. IP traffic not available. */
5582     public static final int DATA_DISCONNECTED   = 0;
5583     /** Data connection state: Currently setting up a data connection. */
5584     public static final int DATA_CONNECTING     = 1;
5585     /** Data connection state: Connected. IP traffic should be available. */
5586     public static final int DATA_CONNECTED      = 2;
5587     /** Data connection state: Suspended. The connection is up, but IP
5588      * traffic is temporarily unavailable. For example, in a 2G network,
5589      * data activity may be suspended when a voice call arrives. */
5590     public static final int DATA_SUSPENDED      = 3;
5591     /**
5592      * Data connection state: Disconnecting.
5593      *
5594      * IP traffic may be available but will cease working imminently.
5595      */
5596     public static final int DATA_DISCONNECTING = 4;
5597 
5598     /**
5599      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
5600      */
5601     @ChangeId
5602     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
5603     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
5604 
5605     /**
5606      * Returns a constant indicating the current data connection state
5607      * (cellular).
5608      *
5609      * @see #DATA_DISCONNECTED
5610      * @see #DATA_CONNECTING
5611      * @see #DATA_CONNECTED
5612      * @see #DATA_SUSPENDED
5613      * @see #DATA_DISCONNECTING
5614      */
getDataState()5615     public int getDataState() {
5616         try {
5617             ITelephony telephony = getITelephony();
5618             if (telephony == null)
5619                 return DATA_DISCONNECTED;
5620             int state = telephony.getDataStateForSubId(
5621                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5622             if (state == TelephonyManager.DATA_DISCONNECTING
5623                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
5624                 return TelephonyManager.DATA_CONNECTED;
5625             }
5626 
5627             return state;
5628         } catch (RemoteException ex) {
5629             // the phone process is restarting.
5630             return DATA_DISCONNECTED;
5631         } catch (NullPointerException ex) {
5632             return DATA_DISCONNECTED;
5633         }
5634     }
5635 
5636     /**
5637      * Convert data state to string
5638      *
5639      * @return The data state in string format.
5640      * @hide
5641      */
dataStateToString(@ataState int state)5642     public static String dataStateToString(@DataState int state) {
5643         switch (state) {
5644             case DATA_DISCONNECTED: return "DISCONNECTED";
5645             case DATA_CONNECTING: return "CONNECTING";
5646             case DATA_CONNECTED: return "CONNECTED";
5647             case DATA_SUSPENDED: return "SUSPENDED";
5648             case DATA_DISCONNECTING: return "DISCONNECTING";
5649         }
5650         return "UNKNOWN(" + state + ")";
5651     }
5652 
5653    /**
5654     * @hide
5655     */
5656     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getITelephony()5657     private ITelephony getITelephony() {
5658         return ITelephony.Stub.asInterface(TelephonyFrameworkInitializer
5659                 .getTelephonyServiceManager().getTelephonyServiceRegisterer().get());
5660     }
5661 
getIOns()5662     private IOns getIOns() {
5663         return IOns.Stub.asInterface(
5664                 TelephonyFrameworkInitializer
5665                         .getTelephonyServiceManager()
5666                         .getOpportunisticNetworkServiceRegisterer()
5667                         .get());
5668     }
5669 
5670     //
5671     //
5672     // PhoneStateListener
5673     //
5674     //
5675 
5676     /**
5677      * Registers a listener object to receive notification of changes
5678      * in specified telephony states.
5679      * <p>
5680      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
5681      * state of interest in the events argument.
5682      *
5683      * At registration, and when a specified telephony state changes, the telephony manager invokes
5684      * the appropriate callback method on the listener object and passes the current (updated)
5685      * values.
5686      * <p>
5687      * To un-register a listener, pass the listener object and set the events argument to
5688      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
5689      *
5690      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
5691      * applies to the given subId. Otherwise, applies to
5692      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
5693      * pass a separate listener object to each TelephonyManager object created with
5694      * {@link #createForSubscriptionId}.
5695      *
5696      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
5697      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
5698      * {@link SecurityException} will be thrown otherwise.
5699      *
5700      * This API should be used sparingly -- large numbers of listeners will cause system
5701      * instability. If a process has registered too many listeners without unregistering them, it
5702      * may encounter an {@link IllegalStateException} when trying to register more listeners.
5703      *
5704      * @param listener The {@link PhoneStateListener} object to register
5705      *                 (or unregister)
5706      * @param events The telephony state(s) of interest to the listener,
5707      *               as a bitwise-OR combination of {@link PhoneStateListener}
5708      *               LISTEN_ flags.
5709      */
listen(PhoneStateListener listener, int events)5710     public void listen(PhoneStateListener listener, int events) {
5711         if (mContext == null) return;
5712         boolean notifyNow = (getITelephony() != null);
5713         TelephonyRegistryManager telephonyRegistry =
5714                 (TelephonyRegistryManager)
5715                         mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
5716         if (telephonyRegistry != null) {
5717             telephonyRegistry.listenForSubscriber(mSubId, getOpPackageName(), getAttributionTag(),
5718                     listener, events, notifyNow);
5719         } else {
5720             Rlog.w(TAG, "telephony registry not ready.");
5721         }
5722     }
5723 
5724     /**
5725      * Get the CDMA ERI (Enhanced Roaming Indicator) information
5726      *
5727      * Returns {@link android.telephony#CdmaEriInformation}
5728      *
5729      * @hide
5730      */
5731     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5732     @NonNull
getCdmaEriInformation()5733     public CdmaEriInformation getCdmaEriInformation() {
5734         return new CdmaEriInformation(
5735                getCdmaEriIconIndex(getSubId()), getCdmaEriIconMode(getSubId()));
5736     }
5737 
5738     /**
5739      * Returns the CDMA ERI icon index to display for a subscription
5740      * @hide
5741      */
5742     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5743     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)5744     public int getCdmaEriIconIndex(int subId) {
5745         try {
5746             ITelephony telephony = getITelephony();
5747             if (telephony == null)
5748                 return -1;
5749             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
5750                     getAttributionTag());
5751         } catch (RemoteException ex) {
5752             // the phone process is restarting.
5753             return -1;
5754         } catch (NullPointerException ex) {
5755             return -1;
5756         }
5757     }
5758 
5759     /**
5760      * Returns the CDMA ERI icon mode for a subscription.
5761      * 0 - ON
5762      * 1 - FLASHING
5763      *
5764      * @hide
5765      */
5766     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5767     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)5768     public int getCdmaEriIconMode(int subId) {
5769         try {
5770             ITelephony telephony = getITelephony();
5771             if (telephony == null)
5772                 return -1;
5773             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
5774                     getAttributionTag());
5775         } catch (RemoteException ex) {
5776             // the phone process is restarting.
5777             return -1;
5778         } catch (NullPointerException ex) {
5779             return -1;
5780         }
5781     }
5782 
5783     /**
5784      * Returns the CDMA ERI text,
5785      *
5786      * @hide
5787      */
5788     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()5789     public String getCdmaEriText() {
5790         return getCdmaEriText(getSubId());
5791     }
5792 
5793     /**
5794      * Returns the CDMA ERI text, of a subscription
5795      *
5796      * @hide
5797      */
5798     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5799     @UnsupportedAppUsage
getCdmaEriText(int subId)5800     public String getCdmaEriText(int subId) {
5801         try {
5802             ITelephony telephony = getITelephony();
5803             if (telephony == null)
5804                 return null;
5805             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
5806                     getAttributionTag());
5807         } catch (RemoteException ex) {
5808             // the phone process is restarting.
5809             return null;
5810         } catch (NullPointerException ex) {
5811             return null;
5812         }
5813     }
5814 
5815     /**
5816      * @return true if the current device is "voice capable".
5817      * <p>
5818      * "Voice capable" means that this device supports circuit-switched
5819      * (i.e. voice) phone calls over the telephony network, and is allowed
5820      * to display the in-call UI while a cellular voice call is active.
5821      * This will be false on "data only" devices which can't make voice
5822      * calls and don't support any in-call UI.
5823      * <p>
5824      * Note: the meaning of this flag is subtly different from the
5825      * PackageManager.FEATURE_TELEPHONY system feature, which is available
5826      * on any device with a telephony radio, even if the device is
5827      * data-only.
5828      */
isVoiceCapable()5829     public boolean isVoiceCapable() {
5830         if (mContext == null) return true;
5831         return mContext.getResources().getBoolean(
5832                 com.android.internal.R.bool.config_voice_capable);
5833     }
5834 
5835     /**
5836      * @return true if the current device supports sms service.
5837      * <p>
5838      * If true, this means that the device supports both sending and
5839      * receiving sms via the telephony network.
5840      * <p>
5841      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
5842      *       disabled when device doesn't support sms.
5843      */
isSmsCapable()5844     public boolean isSmsCapable() {
5845         if (mContext == null) return true;
5846         return mContext.getResources().getBoolean(
5847                 com.android.internal.R.bool.config_sms_capable);
5848     }
5849 
5850     /**
5851      * Requests all available cell information from all radios on the device including the
5852      * camped/registered, serving, and neighboring cells.
5853      *
5854      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
5855      * {@link android.telephony.CellInfoCdma CellInfoCdma},
5856      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
5857      * {@link android.telephony.CellInfoLte CellInfoLte}, and
5858      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
5859      * It is typical to see instances of one or more of any these in the list. In addition, zero
5860      * or more of the returned objects may be considered registered; that is, their
5861      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
5862      * methods may return true, indicating that the cell is being used or would be used for
5863      * signaling communication if necessary.
5864      *
5865      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
5866      * if this API results in a change of the cached CellInfo, that change will be reported via
5867      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}.
5868      *
5869      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
5870      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
5871      * will receive the latest cached results, which may not be current. Apps targeting
5872      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
5873      * CellInfo should call
5874      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
5875      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
5876      * recency of CellInfo data, callers should check
5877      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
5878      *
5879      * <p>This method returns valid data for devices with
5880      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
5881      * where only partial information is available for a particular CellInfo entry, unavailable
5882      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
5883      * cells will include at least a valid set of technology-specific identification info and a
5884      * power level measurement.
5885      *
5886      * <p>This method is preferred over using {@link
5887      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
5888      *
5889      * @return List of {@link android.telephony.CellInfo}; null if cell
5890      * information is unavailable.
5891      */
5892     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getAllCellInfo()5893     public List<CellInfo> getAllCellInfo() {
5894         try {
5895             ITelephony telephony = getITelephony();
5896             if (telephony == null)
5897                 return null;
5898             return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
5899         } catch (RemoteException ex) {
5900         } catch (NullPointerException ex) {
5901         }
5902         return null;
5903     }
5904 
5905     /** Callback for providing asynchronous {@link CellInfo} on request */
5906     public abstract static class CellInfoCallback {
5907         /**
5908          * Success response to
5909          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
5910          *
5911          * Invoked when there is a response to
5912          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
5913          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
5914          * list will be provided. If an error occurs, null will be provided unless the onError
5915          * callback is overridden.
5916          *
5917          * @param cellInfo a list of {@link CellInfo}, an empty list, or null.
5918          *
5919          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
5920          */
onCellInfo(@onNull List<CellInfo> cellInfo)5921         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
5922 
5923         /** @hide */
5924         @Retention(RetentionPolicy.SOURCE)
5925         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
5926         public @interface CellInfoCallbackError {}
5927 
5928         /**
5929          * The system timed out waiting for a response from the Radio.
5930          */
5931         public static final int ERROR_TIMEOUT = 1;
5932 
5933         /**
5934          * The modem returned a failure.
5935          */
5936         public static final int ERROR_MODEM_ERROR = 2;
5937 
5938         /**
5939          * Error response to
5940          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
5941          *
5942          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
5943          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
5944          * function to receive detailed status information in the event of an error. By default,
5945          * this function will invoke onCellInfo() with null.
5946          *
5947          * @param errorCode an error code indicating the type of failure.
5948          * @param detail a Throwable object with additional detail regarding the failure if
5949          *     available, otherwise null.
5950          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)5951         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
5952             // By default, simply invoke the success callback with an empty list.
5953             onCellInfo(new ArrayList<CellInfo>());
5954         }
5955     };
5956 
5957     /**
5958      * Requests all available cell information from the current subscription for observed
5959      * camped/registered, serving, and neighboring cells.
5960      *
5961      * <p>Any available results from this request will be provided by calls to
5962      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
5963      * for each active subscription.
5964      *
5965      * <p>This method returns valid data for devices with
5966      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
5967      * that do not implement this feature, the behavior is not reliable.
5968      *
5969      * @param executor the executor on which callback will be invoked.
5970      * @param callback a callback to receive CellInfo.
5971      */
5972     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)5973     public void requestCellInfoUpdate(
5974             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
5975         try {
5976             ITelephony telephony = getITelephony();
5977             if (telephony == null) return;
5978             telephony.requestCellInfoUpdate(
5979                     getSubId(),
5980                     new ICellInfoCallback.Stub() {
5981                         @Override
5982                         public void onCellInfo(List<CellInfo> cellInfo) {
5983                             final long identity = Binder.clearCallingIdentity();
5984                             try {
5985                                 executor.execute(() -> callback.onCellInfo(cellInfo));
5986                             } finally {
5987                                 Binder.restoreCallingIdentity(identity);
5988                             }
5989                         }
5990 
5991                         @Override
5992                         public void onError(int errorCode, String exceptionName, String message) {
5993                             final long identity = Binder.clearCallingIdentity();
5994                             try {
5995                                 executor.execute(() -> callback.onError(
5996                                         errorCode,
5997                                         createThrowableByClassName(exceptionName, message)));
5998                             } finally {
5999                                 Binder.restoreCallingIdentity(identity);
6000                             }
6001                         }
6002                     }, getOpPackageName(), getAttributionTag());
6003         } catch (RemoteException ex) {
6004         }
6005     }
6006 
6007     /**
6008      * Requests all available cell information from the current subscription for observed
6009      * camped/registered, serving, and neighboring cells.
6010      *
6011      * <p>Any available results from this request will be provided by calls to
6012      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
6013      * for each active subscription.
6014      *
6015      * <p>This method returns valid data for devices with
6016      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
6017      * that do not implement this feature, the behavior is not reliable.
6018      *
6019      * @param workSource the requestor to whom the power consumption for this should be attributed.
6020      * @param executor the executor on which callback will be invoked.
6021      * @param callback a callback to receive CellInfo.
6022      * @hide
6023      */
6024     @SystemApi
6025     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
6026             android.Manifest.permission.MODIFY_PHONE_STATE})
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)6027     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
6028             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
6029         try {
6030             ITelephony telephony = getITelephony();
6031             if (telephony == null) return;
6032             telephony.requestCellInfoUpdateWithWorkSource(
6033                     getSubId(),
6034                     new ICellInfoCallback.Stub() {
6035                         @Override
6036                         public void onCellInfo(List<CellInfo> cellInfo) {
6037                             final long identity = Binder.clearCallingIdentity();
6038                             try {
6039                                 executor.execute(() -> callback.onCellInfo(cellInfo));
6040                             } finally {
6041                                 Binder.restoreCallingIdentity(identity);
6042                             }
6043 
6044                         }
6045 
6046                         @Override
6047                         public void onError(int errorCode, String exceptionName, String message) {
6048                             final long identity = Binder.clearCallingIdentity();
6049                             try {
6050                                 executor.execute(() -> callback.onError(
6051                                         errorCode,
6052                                         createThrowableByClassName(exceptionName, message)));
6053                             } finally {
6054                                 Binder.restoreCallingIdentity(identity);
6055                             }
6056                         }
6057                     }, getOpPackageName(), getAttributionTag(), workSource);
6058         } catch (RemoteException ex) {
6059         }
6060     }
6061 
createThrowableByClassName(String className, String message)6062     private static Throwable createThrowableByClassName(String className, String message) {
6063         if (className == null) {
6064             return null;
6065         }
6066         try {
6067             Class<?> c = Class.forName(className);
6068             return (Throwable) c.getConstructor(String.class).newInstance(message);
6069         } catch (ReflectiveOperationException | ClassCastException e) {
6070         }
6071         return new RuntimeException(className + ": " + message);
6072     }
6073 
6074     /**
6075      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
6076      * PhoneStateListener.onCellInfoChanged} will be invoked.
6077      *<p>
6078      * The default, 0, means invoke onCellInfoChanged when any of the reported
6079      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
6080      * A onCellInfoChanged.
6081      *<p>
6082      * @param rateInMillis the rate
6083      *
6084      * @hide
6085      */
setCellInfoListRate(int rateInMillis)6086     public void setCellInfoListRate(int rateInMillis) {
6087         try {
6088             ITelephony telephony = getITelephony();
6089             if (telephony != null)
6090                 telephony.setCellInfoListRate(rateInMillis);
6091         } catch (RemoteException ex) {
6092         } catch (NullPointerException ex) {
6093         }
6094     }
6095 
6096     /**
6097      * Returns the MMS user agent.
6098      */
getMmsUserAgent()6099     public String getMmsUserAgent() {
6100         try {
6101             ITelephony telephony = getITelephony();
6102             if (telephony != null) {
6103                 return telephony.getMmsUserAgent(getSubId());
6104             }
6105         } catch (RemoteException ex) {
6106         } catch (NullPointerException ex) {
6107         }
6108         return null;
6109     }
6110 
6111     /**
6112      * Returns the MMS user agent profile URL.
6113      */
getMmsUAProfUrl()6114     public String getMmsUAProfUrl() {
6115         try {
6116             ITelephony telephony = getITelephony();
6117             if (telephony != null) {
6118                 return telephony.getMmsUAProfUrl(getSubId());
6119             }
6120         } catch (RemoteException ex) {
6121         } catch (NullPointerException ex) {
6122         }
6123         return null;
6124     }
6125 
6126     /**
6127      * Opens a logical channel to the ICC card.
6128      *
6129      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6130      *
6131      * <p>Requires Permission:
6132      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6133      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6134      *
6135      * @param AID Application id. See ETSI 102.221 and 101.220.
6136      * @return an IccOpenLogicalChannelResponse object.
6137      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
6138      */
6139     @Deprecated
iccOpenLogicalChannel(String AID)6140     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
6141         return iccOpenLogicalChannel(getSubId(), AID, -1);
6142     }
6143 
6144     /**
6145      * Opens a logical channel to the ICC card using the physical slot index.
6146      *
6147      * Use this method when no subscriptions are available on the SIM and the operation must be
6148      * performed using the physical slot index.
6149      *
6150      * This operation wraps two APDU instructions:
6151      * <ul>
6152      *     <li>MANAGE CHANNEL to open a logical channel</li>
6153      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6154      * </ul>
6155      *
6156      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6157      * and 0x0C are guaranteed to be supported.
6158      *
6159      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6160      * considered an error and the channel shall not be opened.
6161      *
6162      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6163      *
6164      * <p>Requires Permission:
6165      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6166      *
6167      * @param slotIndex the physical slot index of the ICC card
6168      * @param aid Application id. See ETSI 102.221 and 101.220.
6169      * @param p2 P2 parameter (described in ISO 7816-4).
6170      * @return an IccOpenLogicalChannelResponse object.
6171      * @hide
6172      */
6173     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6174     @SystemApi
6175     @Nullable
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)6176     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
6177             @Nullable String aid, int p2) {
6178         try {
6179             ITelephony telephony = getITelephony();
6180             if (telephony != null) {
6181                 return telephony.iccOpenLogicalChannelBySlot(slotIndex, getOpPackageName(), aid,
6182                         p2);
6183             }
6184         } catch (RemoteException ex) {
6185         } catch (NullPointerException ex) {
6186         }
6187         return null;
6188     }
6189 
6190     /**
6191      * Opens a logical channel to the ICC card.
6192      *
6193      * This operation wraps two APDU instructions:
6194      * <ul>
6195      *     <li>MANAGE CHANNEL to open a logical channel</li>
6196      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6197      * </ul>
6198      *
6199      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6200      * and 0x0C are guaranteed to be supported.
6201      *
6202      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6203      * considered an error and the channel shall not be opened.
6204      *
6205      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6206      *
6207      * <p>Requires Permission:
6208      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6209      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6210      *
6211      * @param AID Application id. See ETSI 102.221 and 101.220.
6212      * @param p2 P2 parameter (described in ISO 7816-4).
6213      * @return an IccOpenLogicalChannelResponse object.
6214      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6215      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6216      *             {@link android.se.omapi.Reader#openSession()},
6217      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
6218      */
6219     @Deprecated
iccOpenLogicalChannel(String AID, int p2)6220     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
6221         return iccOpenLogicalChannel(getSubId(), AID, p2);
6222     }
6223 
6224     /**
6225      * Opens a logical channel to the ICC card.
6226      *
6227      * This operation wraps two APDU instructions:
6228      * <ul>
6229      *     <li>MANAGE CHANNEL to open a logical channel</li>
6230      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6231      * </ul>
6232      *
6233      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6234      * and 0x0C are guaranteed to be supported.
6235      *
6236      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6237      * considered an error and the channel shall not be opened.
6238      *
6239      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6240      *
6241      * <p>Requires Permission:
6242      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6243      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6244      *
6245      * @param subId The subscription to use.
6246      * @param AID Application id. See ETSI 102.221 and 101.220.
6247      * @param p2 P2 parameter (described in ISO 7816-4).
6248      * @return an IccOpenLogicalChannelResponse object.
6249      * @hide
6250      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6251      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6252      *             {@link android.se.omapi.Reader#openSession()},
6253      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
6254      */
6255     @Deprecated
iccOpenLogicalChannel(int subId, String AID, int p2)6256     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
6257         try {
6258             ITelephony telephony = getITelephony();
6259             if (telephony != null)
6260                 return telephony.iccOpenLogicalChannel(subId, getOpPackageName(), AID, p2);
6261         } catch (RemoteException ex) {
6262         } catch (NullPointerException ex) {
6263         }
6264         return null;
6265     }
6266 
6267     /**
6268      * Closes a previously opened logical channel to the ICC card using the physical slot index.
6269      *
6270      * Use this method when no subscriptions are available on the SIM and the operation must be
6271      * performed using the physical slot index.
6272      *
6273      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6274      *
6275      * <p>Requires Permission:
6276      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6277      *
6278      * @param slotIndex the physical slot index of the ICC card
6279      * @param channel is the channel id to be closed as returned by a successful
6280      *            iccOpenLogicalChannel.
6281      * @return true if the channel was closed successfully.
6282      * @hide
6283      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6284      *             {@link android.se.omapi.Channel#close()}.
6285      */
6286     @Deprecated
6287     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6288     @SystemApi
iccCloseLogicalChannelBySlot(int slotIndex, int channel)6289     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
6290         try {
6291             ITelephony telephony = getITelephony();
6292             if (telephony != null) {
6293                 return telephony.iccCloseLogicalChannelBySlot(slotIndex, channel);
6294             }
6295         } catch (RemoteException ex) {
6296         } catch (NullPointerException ex) {
6297         }
6298         return false;
6299     }
6300 
6301     /**
6302      * Closes a previously opened logical channel to the ICC card.
6303      *
6304      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6305      *
6306      * <p>Requires Permission:
6307      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6308      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6309      *
6310      * @param channel is the channel id to be closed as returned by a successful
6311      *            iccOpenLogicalChannel.
6312      * @return true if the channel was closed successfully.
6313      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6314      *             {@link android.se.omapi.Channel#close()}.
6315      */
6316     @Deprecated
iccCloseLogicalChannel(int channel)6317     public boolean iccCloseLogicalChannel(int channel) {
6318         return iccCloseLogicalChannel(getSubId(), channel);
6319     }
6320 
6321     /**
6322      * Closes a previously opened logical channel to the ICC card.
6323      *
6324      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6325      *
6326      * <p>Requires Permission:
6327      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6328      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6329      *
6330      * @param subId The subscription to use.
6331      * @param channel is the channel id to be closed as returned by a successful
6332      *            iccOpenLogicalChannel.
6333      * @return true if the channel was closed successfully.
6334      * @hide
6335      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6336      *             {@link android.se.omapi.Channel#close()}.
6337      */
6338     @Deprecated
iccCloseLogicalChannel(int subId, int channel)6339     public boolean iccCloseLogicalChannel(int subId, int channel) {
6340         try {
6341             ITelephony telephony = getITelephony();
6342             if (telephony != null)
6343                 return telephony.iccCloseLogicalChannel(subId, channel);
6344         } catch (RemoteException ex) {
6345         } catch (NullPointerException ex) {
6346         }
6347         return false;
6348     }
6349 
6350     /**
6351      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
6352      *
6353      * Use this method when no subscriptions are available on the SIM and the operation must be
6354      * performed using the physical slot index.
6355      *
6356      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6357      *
6358      * <p>Requires Permission:
6359      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6360      *
6361      * @param slotIndex the physical slot index of the ICC card
6362      * @param channel is the channel id to be closed as returned by a successful
6363      *            iccOpenLogicalChannel.
6364      * @param cla Class of the APDU command.
6365      * @param instruction Instruction of the APDU command.
6366      * @param p1 P1 value of the APDU command.
6367      * @param p2 P2 value of the APDU command.
6368      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6369      *            is sent to the SIM.
6370      * @param data Data to be sent with the APDU.
6371      * @return The APDU response from the ICC card with the status appended at the end, or null if
6372      * there is an issue connecting to the Telephony service.
6373      * @hide
6374      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6375      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6376      */
6377     @Deprecated
6378     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6379     @SystemApi
6380     @Nullable
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6381     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
6382             int instruction, int p1, int p2, int p3, @Nullable String data) {
6383         try {
6384             ITelephony telephony = getITelephony();
6385             if (telephony != null) {
6386                 return telephony.iccTransmitApduLogicalChannelBySlot(slotIndex, channel, cla,
6387                         instruction, p1, p2, p3, data);
6388             }
6389         } catch (RemoteException ex) {
6390         } catch (NullPointerException ex) {
6391         }
6392         return null;
6393     }
6394 
6395     /**
6396      * Transmit an APDU to the ICC card over a logical channel.
6397      *
6398      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6399      *
6400      * <p>Requires Permission:
6401      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6402      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6403      *
6404      * @param channel is the channel id to be closed as returned by a successful
6405      *            iccOpenLogicalChannel.
6406      * @param cla Class of the APDU command.
6407      * @param instruction Instruction of the APDU command.
6408      * @param p1 P1 value of the APDU command.
6409      * @param p2 P2 value of the APDU command.
6410      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6411      *            is sent to the SIM.
6412      * @param data Data to be sent with the APDU.
6413      * @return The APDU response from the ICC card with the status appended at
6414      *            the end.
6415      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6416      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6417      */
6418     @Deprecated
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)6419     public String iccTransmitApduLogicalChannel(int channel, int cla,
6420             int instruction, int p1, int p2, int p3, String data) {
6421         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
6422                     instruction, p1, p2, p3, data);
6423     }
6424 
6425     /**
6426      * Transmit an APDU to the ICC card over a logical channel.
6427      *
6428      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6429      *
6430      * <p>Requires Permission:
6431      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6432      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6433      *
6434      * @param subId The subscription to use.
6435      * @param channel is the channel id to be closed as returned by a successful
6436      *            iccOpenLogicalChannel.
6437      * @param cla Class of the APDU command.
6438      * @param instruction Instruction of the APDU command.
6439      * @param p1 P1 value of the APDU command.
6440      * @param p2 P2 value of the APDU command.
6441      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6442      *            is sent to the SIM.
6443      * @param data Data to be sent with the APDU.
6444      * @return The APDU response from the ICC card with the status appended at
6445      *            the end.
6446      * @hide
6447      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6448      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6449      */
6450     @Deprecated
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)6451     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
6452             int instruction, int p1, int p2, int p3, String data) {
6453         try {
6454             ITelephony telephony = getITelephony();
6455             if (telephony != null)
6456                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
6457                     instruction, p1, p2, p3, data);
6458         } catch (RemoteException ex) {
6459         } catch (NullPointerException ex) {
6460         }
6461         return "";
6462     }
6463 
6464     /**
6465      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
6466      *
6467      * Use this method when no subscriptions are available on the SIM and the operation must be
6468      * performed using the physical slot index.
6469      *
6470      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6471      *
6472      * <p>Requires Permission:
6473      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6474      *
6475      * @param slotIndex the physical slot index of the ICC card to target
6476      * @param cla Class of the APDU command.
6477      * @param instruction Instruction of the APDU command.
6478      * @param p1 P1 value of the APDU command.
6479      * @param p2 P2 value of the APDU command.
6480      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6481      *            is sent to the SIM.
6482      * @param data Data to be sent with the APDU.
6483      * @return The APDU response from the ICC card with the status appended at
6484      *            the end.
6485      * @hide
6486      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6487      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6488      *             {@link android.se.omapi.Reader#openSession()},
6489      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6490      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6491      */
6492     @Deprecated
6493     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6494     @SystemApi
6495     @NonNull
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6496     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
6497             int p2, int p3, @Nullable String data) {
6498         try {
6499             ITelephony telephony = getITelephony();
6500             if (telephony != null) {
6501                 return telephony.iccTransmitApduBasicChannelBySlot(slotIndex, getOpPackageName(),
6502                         cla, instruction, p1, p2, p3, data);
6503             }
6504         } catch (RemoteException ex) {
6505         } catch (NullPointerException ex) {
6506         }
6507         return null;
6508     }
6509 
6510     /**
6511      * Transmit an APDU to the ICC card over the basic channel.
6512      *
6513      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6514      *
6515      * <p>Requires Permission:
6516      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6517      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6518      *
6519      * @param cla Class of the APDU command.
6520      * @param instruction Instruction of the APDU command.
6521      * @param p1 P1 value of the APDU command.
6522      * @param p2 P2 value of the APDU command.
6523      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6524      *            is sent to the SIM.
6525      * @param data Data to be sent with the APDU.
6526      * @return The APDU response from the ICC card with the status appended at
6527      *            the end.
6528      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6529      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6530      *             {@link android.se.omapi.Reader#openSession()},
6531      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6532      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6533      */
6534     @Deprecated
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)6535     public String iccTransmitApduBasicChannel(int cla,
6536             int instruction, int p1, int p2, int p3, String data) {
6537         return iccTransmitApduBasicChannel(getSubId(), cla,
6538                     instruction, p1, p2, p3, data);
6539     }
6540 
6541     /**
6542      * Transmit an APDU to the ICC card over the basic channel.
6543      *
6544      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6545      *
6546      * <p>Requires Permission:
6547      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6548      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6549      *
6550      * @param subId The subscription to use.
6551      * @param cla Class of the APDU command.
6552      * @param instruction Instruction of the APDU command.
6553      * @param p1 P1 value of the APDU command.
6554      * @param p2 P2 value of the APDU command.
6555      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6556      *            is sent to the SIM.
6557      * @param data Data to be sent with the APDU.
6558      * @return The APDU response from the ICC card with the status appended at
6559      *            the end.
6560      * @hide
6561      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6562      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6563      *             {@link android.se.omapi.Reader#openSession()},
6564      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6565      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6566      */
6567     @Deprecated
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)6568     public String iccTransmitApduBasicChannel(int subId, int cla,
6569             int instruction, int p1, int p2, int p3, String data) {
6570         try {
6571             ITelephony telephony = getITelephony();
6572             if (telephony != null)
6573                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
6574                     instruction, p1, p2, p3, data);
6575         } catch (RemoteException ex) {
6576         } catch (NullPointerException ex) {
6577         }
6578         return "";
6579     }
6580 
6581     /**
6582      * Returns the response APDU for a command APDU sent through SIM_IO.
6583      *
6584      * <p>Requires Permission:
6585      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6586      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6587      *
6588      * @param fileID
6589      * @param command
6590      * @param p1 P1 value of the APDU command.
6591      * @param p2 P2 value of the APDU command.
6592      * @param p3 P3 value of the APDU command.
6593      * @param filePath
6594      * @return The APDU response.
6595      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6596      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6597      *             {@link android.se.omapi.Reader#openSession()},
6598      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6599      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6600      */
6601     @Deprecated
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)6602     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
6603             String filePath) {
6604         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
6605     }
6606 
6607     /**
6608      * Returns the response APDU for a command APDU sent through SIM_IO.
6609      *
6610      * <p>Requires Permission:
6611      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6612      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6613      *
6614      * @param subId The subscription to use.
6615      * @param fileID
6616      * @param command
6617      * @param p1 P1 value of the APDU command.
6618      * @param p2 P2 value of the APDU command.
6619      * @param p3 P3 value of the APDU command.
6620      * @param filePath
6621      * @return The APDU response.
6622      * @hide
6623      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6624      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6625      *             {@link android.se.omapi.Reader#openSession()},
6626      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6627      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6628      */
6629     @Deprecated
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)6630     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
6631             int p3, String filePath) {
6632         try {
6633             ITelephony telephony = getITelephony();
6634             if (telephony != null)
6635                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
6636         } catch (RemoteException ex) {
6637         } catch (NullPointerException ex) {
6638         }
6639         return null;
6640     }
6641 
6642     /**
6643      * Send ENVELOPE to the SIM and return the response.
6644      *
6645      * <p>Requires Permission:
6646      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6647      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6648      *
6649      * @param content String containing SAT/USAT response in hexadecimal
6650      *                format starting with command tag. See TS 102 223 for
6651      *                details.
6652      * @return The APDU response from the ICC card in hexadecimal format
6653      *         with the last 4 bytes being the status word. If the command fails,
6654      *         returns an empty string.
6655      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6656      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6657      *             {@link android.se.omapi.Reader#openSession()},
6658      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6659      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6660      */
6661     @Deprecated
sendEnvelopeWithStatus(String content)6662     public String sendEnvelopeWithStatus(String content) {
6663         return sendEnvelopeWithStatus(getSubId(), content);
6664     }
6665 
6666     /**
6667      * Send ENVELOPE to the SIM and return the response.
6668      *
6669      * <p>Requires Permission:
6670      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6671      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6672      *
6673      * @param subId The subscription to use.
6674      * @param content String containing SAT/USAT response in hexadecimal
6675      *                format starting with command tag. See TS 102 223 for
6676      *                details.
6677      * @return The APDU response from the ICC card in hexadecimal format
6678      *         with the last 4 bytes being the status word. If the command fails,
6679      *         returns an empty string.
6680      * @hide
6681      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6682      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6683      *             {@link android.se.omapi.Reader#openSession()},
6684      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6685      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6686      */
6687     @Deprecated
sendEnvelopeWithStatus(int subId, String content)6688     public String sendEnvelopeWithStatus(int subId, String content) {
6689         try {
6690             ITelephony telephony = getITelephony();
6691             if (telephony != null)
6692                 return telephony.sendEnvelopeWithStatus(subId, content);
6693         } catch (RemoteException ex) {
6694         } catch (NullPointerException ex) {
6695         }
6696         return "";
6697     }
6698 
6699     /**
6700      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
6701      * Used for device configuration by some CDMA operators.
6702      *
6703      * <p>Requires Permission:
6704      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6705      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6706      *
6707      * @param itemID the ID of the item to read.
6708      * @return the NV item as a String, or null on any failure.
6709      *
6710      * @hide
6711      */
6712     @UnsupportedAppUsage
nvReadItem(int itemID)6713     public String nvReadItem(int itemID) {
6714         try {
6715             ITelephony telephony = getITelephony();
6716             if (telephony != null)
6717                 return telephony.nvReadItem(itemID);
6718         } catch (RemoteException ex) {
6719             Rlog.e(TAG, "nvReadItem RemoteException", ex);
6720         } catch (NullPointerException ex) {
6721             Rlog.e(TAG, "nvReadItem NPE", ex);
6722         }
6723         return "";
6724     }
6725 
6726     /**
6727      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
6728      * Used for device configuration by some CDMA operators.
6729      *
6730      * <p>Requires Permission:
6731      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6732      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6733      *
6734      * @param itemID the ID of the item to read.
6735      * @param itemValue the value to write, as a String.
6736      * @return true on success; false on any failure.
6737      *
6738      * @hide
6739      */
nvWriteItem(int itemID, String itemValue)6740     public boolean nvWriteItem(int itemID, String itemValue) {
6741         try {
6742             ITelephony telephony = getITelephony();
6743             if (telephony != null)
6744                 return telephony.nvWriteItem(itemID, itemValue);
6745         } catch (RemoteException ex) {
6746             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
6747         } catch (NullPointerException ex) {
6748             Rlog.e(TAG, "nvWriteItem NPE", ex);
6749         }
6750         return false;
6751     }
6752 
6753     /**
6754      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
6755      * Used for device configuration by some CDMA operators.
6756      *
6757      * <p>Requires Permission:
6758      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6759      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6760      *
6761      * @param preferredRoamingList byte array containing the new PRL.
6762      * @return true on success; false on any failure.
6763      *
6764      * @hide
6765      */
nvWriteCdmaPrl(byte[] preferredRoamingList)6766     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
6767         try {
6768             ITelephony telephony = getITelephony();
6769             if (telephony != null)
6770                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
6771         } catch (RemoteException ex) {
6772             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
6773         } catch (NullPointerException ex) {
6774             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
6775         }
6776         return false;
6777     }
6778 
6779     /**
6780      * Perform the specified type of NV config reset. The radio will be taken offline
6781      * and the device must be rebooted after the operation. Used for device
6782      * configuration by some CDMA operators.
6783      *
6784      * <p>Requires Permission:
6785      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6786      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6787      *
6788      * TODO: remove this one. use {@link #rebootRadio()} for reset type 1 and
6789      * {@link #resetRadioConfig()} for reset type 3
6790      *
6791      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
6792      * @return true on success; false on any failure.
6793      *
6794      * @hide
6795      */
6796     @UnsupportedAppUsage
nvResetConfig(int resetType)6797     public boolean nvResetConfig(int resetType) {
6798         try {
6799             ITelephony telephony = getITelephony();
6800             if (telephony != null) {
6801                 if (resetType == 1 /*1: reload NV reset */) {
6802                     return telephony.rebootModem(getSlotIndex());
6803                 } else if (resetType == 3 /*3: factory NV reset */) {
6804                     return telephony.resetModemConfig(getSlotIndex());
6805                 } else {
6806                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
6807                 }
6808             }
6809         } catch (RemoteException ex) {
6810             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
6811         } catch (NullPointerException ex) {
6812             Rlog.e(TAG, "nvResetConfig NPE", ex);
6813         }
6814         return false;
6815     }
6816 
6817     /**
6818      * Rollback modem configurations to factory default except some config which are in whitelist.
6819      * Used for device configuration by some carriers.
6820      *
6821      * <p>Requires Permission:
6822      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6823      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6824      *
6825      * @return {@code true} on success; {@code false} on any failure.
6826      *
6827      * @hide
6828      */
6829     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6830     @SystemApi
resetRadioConfig()6831     public boolean resetRadioConfig() {
6832         try {
6833             ITelephony telephony = getITelephony();
6834             if (telephony != null) {
6835                 return telephony.resetModemConfig(getSlotIndex());
6836             }
6837         } catch (RemoteException ex) {
6838             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
6839         } catch (NullPointerException ex) {
6840             Rlog.e(TAG, "resetRadioConfig NPE", ex);
6841         }
6842         return false;
6843     }
6844 
6845     /**
6846      * Generate a radio modem reset. Used for device configuration by some carriers.
6847      *
6848      * <p>Requires Permission:
6849      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6850      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6851      *
6852      * @return {@code true} on success; {@code false} on any failure.
6853      *
6854      * @hide
6855      */
6856     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6857     @SystemApi
rebootRadio()6858     public boolean rebootRadio() {
6859         try {
6860             ITelephony telephony = getITelephony();
6861             if (telephony != null) {
6862                 return telephony.rebootModem(getSlotIndex());
6863             }
6864         } catch (RemoteException ex) {
6865             Rlog.e(TAG, "rebootRadio RemoteException", ex);
6866         } catch (NullPointerException ex) {
6867             Rlog.e(TAG, "rebootRadio NPE", ex);
6868         }
6869         return false;
6870     }
6871 
6872     /**
6873      * Return an appropriate subscription ID for any situation.
6874      *
6875      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6876      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
6877      *
6878      */
getSubscriptionId()6879     public int getSubscriptionId() {
6880         return getSubId();
6881     }
6882 
6883     /**
6884      * Return an appropriate subscription ID for any situation.
6885      *
6886      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6887      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
6888      *
6889      */
getSubId()6890     private int getSubId() {
6891       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
6892         return mSubId;
6893       }
6894       return SubscriptionManager.getDefaultSubscriptionId();
6895     }
6896 
6897     /**
6898      * Return an appropriate subscription ID for any situation.
6899      *
6900      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6901      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
6902      * returned.
6903      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
6904      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
6905      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
6906      */
6907     @UnsupportedAppUsage
getSubId(int preferredSubId)6908     private int getSubId(int preferredSubId) {
6909         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
6910             return mSubId;
6911         }
6912         return preferredSubId;
6913     }
6914 
6915     /**
6916      * Return an appropriate phone ID for any situation.
6917      *
6918      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
6919      * associated with the provided subId is returned. Otherwise, the default phoneId associated
6920      * with the default subId will be returned.
6921      */
getPhoneId()6922     private int getPhoneId() {
6923         return SubscriptionManager.getPhoneId(getSubId());
6924     }
6925 
6926     /**
6927      * Return an appropriate phone ID for any situation.
6928      *
6929      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
6930      * associated with the provided subId is returned. Otherwise, return the phoneId associated
6931      * with the preferred subId based on caller's context.
6932      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
6933      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
6934      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
6935      */
6936     @UnsupportedAppUsage
getPhoneId(int preferredSubId)6937     private int getPhoneId(int preferredSubId) {
6938         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
6939     }
6940 
6941     /**
6942      * Return an appropriate slot index for any situation.
6943      *
6944      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
6945      * associated with the provided subId is returned. Otherwise, return the slot index associated
6946      * with the default subId.
6947      * If SIM is not inserted, return default SIM slot index.
6948      *
6949      * {@hide}
6950      */
6951     @VisibleForTesting
6952     @UnsupportedAppUsage
getSlotIndex()6953     public int getSlotIndex() {
6954         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
6955         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
6956             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
6957         }
6958         return slotIndex;
6959     }
6960 
6961     /**
6962      * Request that the next incoming call from a number matching {@code range} be intercepted.
6963      *
6964      * This API is intended for OEMs to provide a service for apps to verify the device's phone
6965      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
6966      * intercept the next incoming call from a number that lies within the range, within a timeout
6967      * specified by {@code timeoutMillis}.
6968      *
6969      * If such a phone call is received, the caller will be notified via
6970      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
6971      * If verification fails for any reason, the caller will be notified via
6972      * {@link NumberVerificationCallback#onVerificationFailed(int)}
6973      * on the provided {@link Executor}.
6974      *
6975      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
6976      * API must also be listed in the device configuration as an authorized app in
6977      * {@code packages/services/Telephony/res/values/config.xml} under the
6978      * {@code config_number_verification_package_name} key.
6979      *
6980      * @hide
6981      * @param range The range of phone numbers the caller expects a phone call from.
6982      * @param timeoutMillis The amount of time to wait for such a call, or the value of
6983      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
6984      * @param executor The {@link Executor} that callbacks should be executed on.
6985      * @param callback The callback to use for delivering results.
6986      */
6987     @SystemApi
6988     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)6989     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
6990             @NonNull @CallbackExecutor Executor executor,
6991             @NonNull NumberVerificationCallback callback) {
6992         if (executor == null) {
6993             throw new NullPointerException("Executor must be non-null");
6994         }
6995         if (callback == null) {
6996             throw new NullPointerException("Callback must be non-null");
6997         }
6998 
6999         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
7000             @Override
7001             public void onCallReceived(String phoneNumber) {
7002                 final long identity = Binder.clearCallingIdentity();
7003                 try {
7004                     executor.execute(() ->
7005                             callback.onCallReceived(phoneNumber));
7006                 } finally {
7007                     Binder.restoreCallingIdentity(identity);
7008                 }
7009             }
7010 
7011             @Override
7012             public void onVerificationFailed(int reason) {
7013                 final long identity = Binder.clearCallingIdentity();
7014                 try {
7015                     executor.execute(() ->
7016                             callback.onVerificationFailed(reason));
7017                 } finally {
7018                     Binder.restoreCallingIdentity(identity);
7019                 }
7020             }
7021         };
7022 
7023         try {
7024             ITelephony telephony = getITelephony();
7025             if (telephony != null) {
7026                 telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
7027                         getOpPackageName());
7028             }
7029         } catch (RemoteException ex) {
7030             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
7031             executor.execute(() ->
7032                     callback.onVerificationFailed(NumberVerificationCallback.REASON_UNSPECIFIED));
7033         }
7034     }
7035 
7036     /**
7037      * Inserts or updates a list property. Expands the list if its length is not enough.
7038      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)7039     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
7040         List<T> ret = new ArrayList<>(prop);
7041         while (ret.size() <= phoneId) ret.add(null);
7042         ret.set(phoneId, value);
7043         return ret;
7044     }
7045     /**
7046      * Convenience function for retrieving a value from the secure settings
7047      * value list as an integer.  Note that internally setting values are
7048      * always stored as strings; this function converts the string to an
7049      * integer for you.
7050      * <p>
7051      * This version does not take a default value.  If the setting has not
7052      * been set, or the string value is not a number,
7053      * it throws {@link SettingNotFoundException}.
7054      *
7055      * @param cr The ContentResolver to access.
7056      * @param name The name of the setting to retrieve.
7057      * @param index The index of the list
7058      *
7059      * @throws SettingNotFoundException Thrown if a setting by the given
7060      * name can't be found or the setting value is not an integer.
7061      *
7062      * @return The value at the given index of settings.
7063      * @hide
7064      */
7065     @UnsupportedAppUsage
getIntAtIndex(android.content.ContentResolver cr, String name, int index)7066     public static int getIntAtIndex(android.content.ContentResolver cr,
7067             String name, int index)
7068             throws android.provider.Settings.SettingNotFoundException {
7069         String v = android.provider.Settings.Global.getString(cr, name);
7070         if (v != null) {
7071             String valArray[] = v.split(",");
7072             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
7073                 try {
7074                     return Integer.parseInt(valArray[index]);
7075                 } catch (NumberFormatException e) {
7076                     //Log.e(TAG, "Exception while parsing Integer: ", e);
7077                 }
7078             }
7079         }
7080         throw new android.provider.Settings.SettingNotFoundException(name);
7081     }
7082 
7083     /**
7084      * Convenience function for updating settings value as coma separated
7085      * integer values. This will either create a new entry in the table if the
7086      * given name does not exist, or modify the value of the existing row
7087      * with that name.  Note that internally setting values are always
7088      * stored as strings, so this function converts the given value to a
7089      * string before storing it.
7090      *
7091      * @param cr The ContentResolver to access.
7092      * @param name The name of the setting to modify.
7093      * @param index The index of the list
7094      * @param value The new value for the setting to be added to the list.
7095      * @return true if the value was set, false on database errors
7096      * @hide
7097      */
7098     @UnsupportedAppUsage
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)7099     public static boolean putIntAtIndex(android.content.ContentResolver cr,
7100             String name, int index, int value) {
7101         String data = "";
7102         String valArray[] = null;
7103         String v = android.provider.Settings.Global.getString(cr, name);
7104 
7105         if (index == Integer.MAX_VALUE) {
7106             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
7107         }
7108         if (index < 0) {
7109             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
7110         }
7111         if (v != null) {
7112             valArray = v.split(",");
7113         }
7114 
7115         // Copy the elements from valArray till index
7116         for (int i = 0; i < index; i++) {
7117             String str = "";
7118             if ((valArray != null) && (i < valArray.length)) {
7119                 str = valArray[i];
7120             }
7121             data = data + str + ",";
7122         }
7123 
7124         data = data + value;
7125 
7126         // Copy the remaining elements from valArray if any.
7127         if (valArray != null) {
7128             for (int i = index+1; i < valArray.length; i++) {
7129                 data = data + "," + valArray[i];
7130             }
7131         }
7132         return android.provider.Settings.Global.putString(cr, name, data);
7133     }
7134 
7135     /**
7136      * Gets a per-phone telephony property from a property name.
7137      *
7138      * @hide
7139      */
7140     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)7141     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
7142         String propVal = null;
7143         String prop = SystemProperties.get(property);
7144         if ((prop != null) && (prop.length() > 0)) {
7145             String values[] = prop.split(",");
7146             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
7147                 propVal = values[phoneId];
7148             }
7149         }
7150         return propVal == null ? defaultVal : propVal;
7151     }
7152 
7153     /**
7154      * Gets a typed per-phone telephony property from a schematized list property.
7155      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)7156     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
7157         T ret = null;
7158         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
7159         return ret != null ? ret : defaultValue;
7160     }
7161 
7162     /**
7163      * Gets a global telephony property.
7164      *
7165      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
7166      * per-phone.
7167      *
7168      * @hide
7169      */
7170     @UnsupportedAppUsage
getTelephonyProperty(String property, String defaultVal)7171     public static String getTelephonyProperty(String property, String defaultVal) {
7172         String propVal = SystemProperties.get(property);
7173         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
7174     }
7175 
7176     /** @hide */
7177     @UnsupportedAppUsage
getSimCount()7178     public int getSimCount() {
7179         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
7180         // and then this method shouldn't be used at all!
7181         return getPhoneCount();
7182     }
7183 
7184     /**
7185      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
7186      *
7187      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
7188      *
7189      * @return IMS Service Table or null if not present or not loaded
7190      * @hide
7191      */
7192     @Nullable
7193     @SystemApi
7194     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimIst()7195     public String getIsimIst() {
7196         try {
7197             IPhoneSubInfo info = getSubscriberInfoService();
7198             if (info == null)
7199                 return null;
7200             //get the Isim Ist based on subId
7201             return info.getIsimIst(getSubId());
7202         } catch (RemoteException ex) {
7203             return null;
7204         } catch (NullPointerException ex) {
7205             // This could happen before phone restarts due to crashing
7206             return null;
7207         }
7208     }
7209 
7210     /**
7211      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
7212      * @return an array of PCSCF strings with one PCSCF per string, or null if
7213      *         not present or not loaded
7214      * @hide
7215      */
7216     @UnsupportedAppUsage
getIsimPcscf()7217     public String[] getIsimPcscf() {
7218         try {
7219             IPhoneSubInfo info = getSubscriberInfoService();
7220             if (info == null)
7221                 return null;
7222             //get the Isim Pcscf based on subId
7223             return info.getIsimPcscf(getSubId());
7224         } catch (RemoteException ex) {
7225             return null;
7226         } catch (NullPointerException ex) {
7227             // This could happen before phone restarts due to crashing
7228             return null;
7229         }
7230     }
7231 
7232     /** UICC application type is SIM */
7233     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
7234     /** UICC application type is USIM */
7235     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
7236     /** UICC application type is RUIM */
7237     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
7238     /** UICC application type is CSIM */
7239     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
7240     /** UICC application type is ISIM */
7241     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
7242 
7243     // authContext (parameter P2) when doing UICC challenge,
7244     // per 3GPP TS 31.102 (Section 7.1.2)
7245     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
7246     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
7247     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
7248     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
7249 
7250     /**
7251      * Returns the response of authentication for the default subscription.
7252      * Returns null if the authentication hasn't been successful
7253      *
7254      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE or that the calling
7255      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7256      *
7257      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7258      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
7259      * {@link #AUTHTYPE_EAP_SIM}
7260      * @param data authentication challenge data, base64 encoded.
7261      * See 3GPP TS 31.102 7.1.2 for more details.
7262      * @return the response of authentication. This value will be null in the following cases:
7263      *   Authentication error, incorrect MAC
7264      *   Authentication error, security context not supported
7265      *   Key freshness failure
7266      *   Authentication error, no memory space available
7267      *   Authentication error, no memory space available in EFMUK
7268      */
7269     // TODO(b/73660190): This should probably require MODIFY_PHONE_STATE, not
7270     // READ_PRIVILEGED_PHONE_STATE. It certainly shouldn't reference the permission in Javadoc since
7271     // it's not public API.
getIccAuthentication(int appType, int authType, String data)7272     public String getIccAuthentication(int appType, int authType, String data) {
7273         return getIccAuthentication(getSubId(), appType, authType, data);
7274     }
7275 
7276     /**
7277      * Returns the response of USIM Authentication for specified subId.
7278      * Returns null if the authentication hasn't been successful
7279      *
7280      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7281      *
7282      * @param subId subscription ID used for authentication
7283      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7284      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
7285      * {@link #AUTHTYPE_EAP_SIM}
7286      * @param data authentication challenge data, base64 encoded.
7287      * See 3GPP TS 31.102 7.1.2 for more details.
7288      * @return the response of authentication. This value will be null in the following cases only
7289      * (see 3GPP TS 31.102 7.3.1):
7290      *   Authentication error, incorrect MAC
7291      *   Authentication error, security context not supported
7292      *   Key freshness failure
7293      *   Authentication error, no memory space available
7294      *   Authentication error, no memory space available in EFMUK
7295      * @hide
7296      */
7297     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType, int authType, String data)7298     public String getIccAuthentication(int subId, int appType, int authType, String data) {
7299         try {
7300             IPhoneSubInfo info = getSubscriberInfoService();
7301             if (info == null)
7302                 return null;
7303             return info.getIccSimChallengeResponse(subId, appType, authType, data);
7304         } catch (RemoteException ex) {
7305             return null;
7306         } catch (NullPointerException ex) {
7307             // This could happen before phone starts
7308             return null;
7309         }
7310     }
7311 
7312     /**
7313      * Returns an array of Forbidden PLMNs from the USIM App
7314      * Returns null if the query fails.
7315      *
7316      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
7317      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7318      *
7319      * @return an array of forbidden PLMNs or null if not available
7320      */
7321     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7322     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns()7323     public String[] getForbiddenPlmns() {
7324       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
7325     }
7326 
7327     /**
7328      * Returns an array of Forbidden PLMNs from the specified SIM App
7329      * Returns null if the query fails.
7330      *
7331      * @param subId subscription ID used for authentication
7332      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7333      * @return fplmns an array of forbidden PLMNs
7334      * @hide
7335      */
7336     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)7337     public String[] getForbiddenPlmns(int subId, int appType) {
7338         try {
7339             ITelephony telephony = getITelephony();
7340             if (telephony == null)
7341                 return null;
7342             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
7343                     getAttributionTag());
7344         } catch (RemoteException ex) {
7345             return null;
7346         } catch (NullPointerException ex) {
7347             // This could happen before phone starts
7348             return null;
7349         }
7350     }
7351 
7352     /**
7353      * Replace the contents of the forbidden PLMN SIM file with the provided values.
7354      * Passing an empty list will clear the contents of the EFfplmn file.
7355      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
7356      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
7357      * If the list is longer than the size of EFfplmn, then the file will be written from the
7358      * beginning of the list up to the file size.
7359      *
7360      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
7361      * MODIFY_PHONE_STATE}
7362      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7363      *
7364      * @param fplmns a list of PLMNs to be forbidden.
7365      *
7366      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
7367      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
7368      * room for all of the values passed in. Return -1 in the event of an unexpected failure
7369      */
7370     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7371     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setForbiddenPlmns(@onNull List<String> fplmns)7372     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
7373         try {
7374             ITelephony telephony = getITelephony();
7375             if (telephony == null) return -1;
7376             return telephony.setForbiddenPlmns(
7377                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
7378         } catch (RemoteException ex) {
7379             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
7380         } catch (NullPointerException ex) {
7381             // This could happen before phone starts
7382             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
7383         }
7384         return -1;
7385     }
7386 
7387     /**
7388      * Get P-CSCF address from PCO after data connection is established or modified.
7389      * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN
7390      * @return array of P-CSCF address
7391      * @hide
7392      */
getPcscfAddress(String apnType)7393     public String[] getPcscfAddress(String apnType) {
7394         try {
7395             ITelephony telephony = getITelephony();
7396             if (telephony == null)
7397                 return new String[0];
7398             return telephony.getPcscfAddress(apnType, getOpPackageName(), getAttributionTag());
7399         } catch (RemoteException e) {
7400             return new String[0];
7401         }
7402     }
7403 
7404 
7405     /**
7406      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
7407      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
7408      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
7409      * state.
7410      *
7411      * @param slotIndex the sim slot to reset the IMS stack on.
7412      * @hide */
7413     @SystemApi
7414     @WorkerThread
7415     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetIms(int slotIndex)7416     public void resetIms(int slotIndex) {
7417         try {
7418             ITelephony telephony = getITelephony();
7419             if (telephony != null) {
7420                 telephony.resetIms(slotIndex);
7421             }
7422         } catch (RemoteException e) {
7423             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
7424                     + e.getMessage());
7425         }
7426     }
7427 
7428     /**
7429      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
7430      * status updates, if not already enabled.
7431      * @hide
7432      */
enableIms(int slotId)7433     public void enableIms(int slotId) {
7434         try {
7435             ITelephony telephony = getITelephony();
7436             if (telephony != null) {
7437                 telephony.enableIms(slotId);
7438             }
7439         } catch (RemoteException e) {
7440             Rlog.e(TAG, "enableIms, RemoteException: "
7441                     + e.getMessage());
7442         }
7443     }
7444 
7445     /**
7446      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
7447      * status updates to disabled.
7448      * @hide
7449      */
disableIms(int slotId)7450     public void disableIms(int slotId) {
7451         try {
7452             ITelephony telephony = getITelephony();
7453             if (telephony != null) {
7454                 telephony.disableIms(slotId);
7455             }
7456         } catch (RemoteException e) {
7457             Rlog.e(TAG, "disableIms, RemoteException: "
7458                     + e.getMessage());
7459         }
7460     }
7461 
7462     /**
7463      * Returns the {@link IImsMmTelFeature} that corresponds to the given slot Id and MMTel
7464      * feature or {@link null} if the service is not available. If an MMTelFeature is available, the
7465      * {@link IImsServiceFeatureCallback} callback is registered as a listener for feature updates.
7466      * @param slotIndex The SIM slot that we are requesting the {@link IImsMmTelFeature} for.
7467      * @param callback Listener that will send updates to ImsManager when there are updates to
7468      * ImsServiceController.
7469      * @return {@link IImsMmTelFeature} interface for the feature specified or {@code null} if
7470      * it is unavailable.
7471      * @hide
7472      */
getImsMmTelFeatureAndListen(int slotIndex, IImsServiceFeatureCallback callback)7473     public @Nullable IImsMmTelFeature getImsMmTelFeatureAndListen(int slotIndex,
7474             IImsServiceFeatureCallback callback) {
7475         try {
7476             ITelephony telephony = getITelephony();
7477             if (telephony != null) {
7478                 return telephony.getMmTelFeatureAndListen(slotIndex, callback);
7479             }
7480         } catch (RemoteException e) {
7481             Rlog.e(TAG, "getImsMmTelFeatureAndListen, RemoteException: "
7482                     + e.getMessage());
7483         }
7484         return null;
7485     }
7486 
7487     /**
7488      * Returns the {@link IImsRcsFeature} that corresponds to the given slot Id and RCS
7489      * feature for emergency calling or {@link null} if the service is not available. If an
7490      * RcsFeature is available, the {@link IImsServiceFeatureCallback} callback is registered as a
7491      * listener for feature updates.
7492      * @param slotIndex The SIM slot that we are requesting the {@link IImsRcsFeature} for.
7493      * @param callback Listener that will send updates to ImsManager when there are updates to
7494      * ImsServiceController.
7495      * @return {@link IImsRcsFeature} interface for the feature specified or {@code null} if
7496      * it is unavailable.
7497      * @hide
7498      */
getImsRcsFeatureAndListen(int slotIndex, IImsServiceFeatureCallback callback)7499     public @Nullable IImsRcsFeature getImsRcsFeatureAndListen(int slotIndex,
7500             IImsServiceFeatureCallback callback) {
7501         try {
7502             ITelephony telephony = getITelephony();
7503             if (telephony != null) {
7504                 return telephony.getRcsFeatureAndListen(slotIndex, callback);
7505             }
7506         } catch (RemoteException e) {
7507             Rlog.e(TAG, "getImsRcsFeatureAndListen, RemoteException: "
7508                     + e.getMessage());
7509         }
7510         return null;
7511     }
7512 
7513     /**
7514      * Unregister a IImsServiceFeatureCallback previously associated with an ImsFeature through
7515      * {@link #getImsMmTelFeatureAndListen(int, IImsServiceFeatureCallback)} or
7516      * {@link #getImsRcsFeatureAndListen(int, IImsServiceFeatureCallback)}.
7517      * @param slotIndex The SIM slot associated with the callback.
7518      * @param featureType The {@link android.telephony.ims.feature.ImsFeature.FeatureType}
7519      *                    associated with the callback.
7520      * @param callback The callback to be unregistered.
7521      * @hide
7522      */
unregisterImsFeatureCallback(int slotIndex, int featureType, IImsServiceFeatureCallback callback)7523     public void unregisterImsFeatureCallback(int slotIndex, int featureType,
7524             IImsServiceFeatureCallback callback) {
7525         try {
7526             ITelephony telephony = getITelephony();
7527             if (telephony != null) {
7528                 telephony.unregisterImsFeatureCallback(slotIndex, featureType, callback);
7529             }
7530         } catch (RemoteException e) {
7531             Rlog.e(TAG, "unregisterImsFeatureCallback, RemoteException: "
7532                     + e.getMessage());
7533         }
7534     }
7535 
7536     /**
7537      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
7538      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
7539      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
7540      * Corresponds to features defined in ImsFeature.
7541      * @hide
7542      */
7543     @UnsupportedAppUsage
getImsRegistration(int slotIndex, int feature)7544     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
7545         try {
7546             ITelephony telephony = getITelephony();
7547             if (telephony != null) {
7548                 return telephony.getImsRegistration(slotIndex, feature);
7549             }
7550         } catch (RemoteException e) {
7551             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7552         }
7553         return null;
7554     }
7555 
7556     /**
7557      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
7558      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
7559      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
7560      * Corresponds to features defined in ImsFeature.
7561      * @hide
7562      */
7563     @UnsupportedAppUsage
getImsConfig(int slotIndex, int feature)7564     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
7565         try {
7566             ITelephony telephony = getITelephony();
7567             if (telephony != null) {
7568                 return telephony.getImsConfig(slotIndex, feature);
7569             }
7570         } catch (RemoteException e) {
7571             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7572         }
7573         return null;
7574     }
7575 
7576     /**
7577      * Set IMS registration state
7578      *
7579      * @param Registration state
7580      * @hide
7581      */
7582     @UnsupportedAppUsage
setImsRegistrationState(boolean registered)7583     public void setImsRegistrationState(boolean registered) {
7584         try {
7585             ITelephony telephony = getITelephony();
7586             if (telephony != null)
7587                 telephony.setImsRegistrationState(registered);
7588         } catch (RemoteException e) {
7589         }
7590     }
7591 
7592     /** @hide */
7593     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
7594             NETWORK_MODE_WCDMA_PREF,
7595             NETWORK_MODE_GSM_ONLY,
7596             NETWORK_MODE_WCDMA_ONLY,
7597             NETWORK_MODE_GSM_UMTS,
7598             NETWORK_MODE_CDMA_EVDO,
7599             NETWORK_MODE_CDMA_NO_EVDO,
7600             NETWORK_MODE_EVDO_NO_CDMA,
7601             NETWORK_MODE_GLOBAL,
7602             NETWORK_MODE_LTE_CDMA_EVDO,
7603             NETWORK_MODE_LTE_GSM_WCDMA,
7604             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
7605             NETWORK_MODE_LTE_ONLY,
7606             NETWORK_MODE_LTE_WCDMA,
7607             NETWORK_MODE_TDSCDMA_ONLY,
7608             NETWORK_MODE_TDSCDMA_WCDMA,
7609             NETWORK_MODE_LTE_TDSCDMA,
7610             NETWORK_MODE_TDSCDMA_GSM,
7611             NETWORK_MODE_LTE_TDSCDMA_GSM,
7612             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
7613             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
7614             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
7615             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7616             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7617             NETWORK_MODE_NR_ONLY,
7618             NETWORK_MODE_NR_LTE,
7619             NETWORK_MODE_NR_LTE_CDMA_EVDO,
7620             NETWORK_MODE_NR_LTE_GSM_WCDMA,
7621             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
7622             NETWORK_MODE_NR_LTE_WCDMA,
7623             NETWORK_MODE_NR_LTE_TDSCDMA,
7624             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
7625             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
7626             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
7627             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
7628     })
7629     @Retention(RetentionPolicy.SOURCE)
7630     public @interface PrefNetworkMode{}
7631 
7632     /**
7633      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
7634      * @hide
7635      */
7636     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
7637 
7638     /**
7639      * Preferred network mode is GSM only.
7640      * @hide
7641      */
7642     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
7643 
7644     /**
7645      * Preferred network mode is WCDMA only.
7646      * @hide
7647      */
7648     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
7649 
7650     /**
7651      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
7652      * @hide
7653      */
7654     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
7655 
7656     /**
7657      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
7658      * @hide
7659      */
7660     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
7661 
7662     /**
7663      * Preferred network mode is CDMA only.
7664      * @hide
7665      */
7666     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
7667 
7668     /**
7669      * Preferred network mode is EvDo only.
7670      * @hide
7671      */
7672     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
7673 
7674     /**
7675      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
7676      * @hide
7677      */
7678     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
7679 
7680     /**
7681      * Preferred network mode is LTE, CDMA and EvDo.
7682      * @hide
7683      */
7684     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
7685 
7686     /**
7687      * Preferred network mode is LTE, GSM/WCDMA.
7688      * @hide
7689      */
7690     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
7691 
7692     /**
7693      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
7694      * @hide
7695      */
7696     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
7697             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
7698 
7699     /**
7700      * Preferred network mode is LTE Only.
7701      * @hide
7702      */
7703     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
7704 
7705     /**
7706      * Preferred network mode is LTE/WCDMA.
7707      * @hide
7708      */
7709     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
7710 
7711     /**
7712      * Preferred network mode is TD-SCDMA only.
7713      * @hide
7714      */
7715     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
7716 
7717     /**
7718      * Preferred network mode is TD-SCDMA and WCDMA.
7719      * @hide
7720      */
7721     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
7722 
7723     /**
7724      * Preferred network mode is TD-SCDMA and LTE.
7725      * @hide
7726      */
7727     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
7728 
7729     /**
7730      * Preferred network mode is TD-SCDMA and GSM.
7731      * @hide
7732      */
7733     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
7734 
7735     /**
7736      * Preferred network mode is TD-SCDMA,GSM and LTE.
7737      * @hide
7738      */
7739     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
7740             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
7741 
7742     /**
7743      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
7744      * @hide
7745      */
7746     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
7747             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
7748 
7749     /**
7750      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
7751      * @hide
7752      */
7753     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
7754             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
7755 
7756     /**
7757      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
7758      * @hide
7759      */
7760     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
7761             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
7762 
7763     /**
7764      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
7765      * @hide
7766      */
7767     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7768             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7769     /**
7770      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
7771      * @hide
7772      */
7773     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7774             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7775 
7776     /**
7777      * Preferred network mode is NR 5G only.
7778      * @hide
7779      */
7780     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
7781 
7782     /**
7783      * Preferred network mode is NR 5G, LTE.
7784      * @hide
7785      */
7786     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
7787 
7788     /**
7789      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
7790      * @hide
7791      */
7792     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
7793             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
7794 
7795     /**
7796      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
7797      * @hide
7798      */
7799     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
7800             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
7801 
7802     /**
7803      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
7804      * @hide
7805      */
7806     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
7807             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
7808 
7809     /**
7810      * Preferred network mode is NR 5G, LTE and WCDMA.
7811      * @hide
7812      */
7813     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
7814 
7815     /**
7816      * Preferred network mode is NR 5G, LTE and TDSCDMA.
7817      * @hide
7818      */
7819     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
7820 
7821     /**
7822      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
7823      * @hide
7824      */
7825     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
7826             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
7827 
7828     /**
7829      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
7830      * @hide
7831      */
7832     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
7833             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
7834 
7835     /**
7836      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
7837      * @hide
7838      */
7839     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
7840             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
7841 
7842     /**
7843      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
7844      * @hide
7845      */
7846     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7847             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7848 
7849     /**
7850      * The default preferred network mode constant.
7851      *
7852      * <p> This constant is used in case of nothing is set in
7853      * TelephonyProperties#default_network().
7854      *
7855      * @hide
7856      */
7857     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
7858             RILConstants.PREFERRED_NETWORK_MODE;
7859 
7860     /**
7861      * Get the preferred network type.
7862      * Used for device configuration by some CDMA operators.
7863      *
7864      * <p>Requires Permission:
7865      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7866      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7867      *
7868      * @return the preferred network type.
7869      * @hide
7870      * @deprecated Use {@link #getPreferredNetworkTypeBitmask} instead.
7871      */
7872     @Deprecated
7873     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
7874     @UnsupportedAppUsage
getPreferredNetworkType(int subId)7875     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
7876         try {
7877             ITelephony telephony = getITelephony();
7878             if (telephony != null) {
7879                 return telephony.getPreferredNetworkType(subId);
7880             }
7881         } catch (RemoteException ex) {
7882             Rlog.e(TAG, "getPreferredNetworkType RemoteException", ex);
7883         }
7884         return -1;
7885     }
7886 
7887     /**
7888      * Get the preferred network type bitmask.
7889      *
7890      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7891      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7892      *
7893      * <p>Requires Permission:
7894      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7895      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7896      *
7897      * @return The bitmask of preferred network types.
7898      *
7899      * @hide
7900      */
7901     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
7902     @SystemApi
getPreferredNetworkTypeBitmask()7903     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
7904         try {
7905             ITelephony telephony = getITelephony();
7906             if (telephony != null) {
7907                 return (long) RadioAccessFamily.getRafFromNetworkType(
7908                         telephony.getPreferredNetworkType(getSubId()));
7909             }
7910         } catch (RemoteException ex) {
7911             Rlog.e(TAG, "getPreferredNetworkTypeBitmask RemoteException", ex);
7912         }
7913         return 0;
7914     }
7915 
7916     /**
7917      * Get the allowed network types.
7918      *
7919      * <p>Requires Permission:
7920      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7921      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7922      *
7923      * @return the allowed network type bitmask
7924      * @hide
7925      */
7926     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
7927     @SystemApi
getAllowedNetworkTypes()7928     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
7929         try {
7930             ITelephony telephony = getITelephony();
7931             if (telephony != null) {
7932                 return telephony.getAllowedNetworkTypes(getSubId());
7933             }
7934         } catch (RemoteException ex) {
7935             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
7936         }
7937         return -1;
7938     }
7939 
7940     /**
7941      * Sets the network selection mode to automatic.
7942      *
7943      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7944      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7945      *
7946      * <p>Requires Permission:
7947      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7948      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7949      */
7950     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7951     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeAutomatic()7952     public void setNetworkSelectionModeAutomatic() {
7953         try {
7954             ITelephony telephony = getITelephony();
7955             if (telephony != null) {
7956                 telephony.setNetworkSelectionModeAutomatic(getSubId());
7957             }
7958         } catch (RemoteException ex) {
7959             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
7960         } catch (NullPointerException ex) {
7961             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
7962         }
7963     }
7964 
7965     /**
7966      * Perform a radio scan and return the list of available networks.
7967      *
7968      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7969      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7970      *
7971      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
7972      *
7973      * <p>Requires Permissions:
7974      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
7975      * privileges (see {@link #hasCarrierPrivileges})
7976      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
7977      *
7978      * @return {@link CellNetworkScanResult} with the status
7979      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
7980      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
7981      * caused will be included in the result.
7982      *
7983      * @hide
7984      */
7985     @RequiresPermission(allOf = {
7986             android.Manifest.permission.MODIFY_PHONE_STATE,
7987             Manifest.permission.ACCESS_COARSE_LOCATION
7988     })
getAvailableNetworks()7989     public CellNetworkScanResult getAvailableNetworks() {
7990         try {
7991             ITelephony telephony = getITelephony();
7992             if (telephony != null) {
7993                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
7994                         getAttributionTag());
7995             }
7996         } catch (RemoteException ex) {
7997             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
7998         } catch (NullPointerException ex) {
7999             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
8000         }
8001         return new CellNetworkScanResult(
8002                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
8003     }
8004 
8005     /**
8006      * Request a network scan.
8007      *
8008      * This method is asynchronous, so the network scan results will be returned by callback.
8009      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
8010      *
8011      * <p>Requires Permission:
8012      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8013      * app has carrier privileges (see {@link #hasCarrierPrivileges})
8014      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
8015      *
8016      * If the system-wide location switch is off, apps may still call this API, with the
8017      * following constraints:
8018      * <ol>
8019      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
8020      *     <li>The app must not supply any specific bands or channels to scan.</li>
8021      *     <li>The app must only specify MCC/MNC pairs that are
8022      *     associated to a SIM in the device.</li>
8023      *     <li>Returned results will have no meaningful info other than signal strength
8024      *     and MCC/MNC info.</li>
8025      * </ol>
8026      *
8027      * @param request Contains all the RAT with bands/channels that need to be scanned.
8028      * @param executor The executor through which the callback should be invoked. Since the scan
8029      *        request may trigger multiple callbacks and they must be invoked in the same order as
8030      *        they are received by the platform, the user should provide an executor which executes
8031      *        tasks one at a time in serial order. For example AsyncTask.SERIAL_EXECUTOR.
8032      * @param callback Returns network scan results or errors.
8033      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
8034      */
8035     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8036     @RequiresPermission(allOf = {
8037             android.Manifest.permission.MODIFY_PHONE_STATE,
8038             Manifest.permission.ACCESS_FINE_LOCATION
8039     })
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)8040     public NetworkScan requestNetworkScan(
8041             NetworkScanRequest request, Executor executor,
8042             TelephonyScanManager.NetworkScanCallback callback) {
8043         synchronized (this) {
8044             if (mTelephonyScanManager == null) {
8045                 mTelephonyScanManager = new TelephonyScanManager();
8046             }
8047         }
8048         return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback,
8049                 getOpPackageName(), getAttributionTag());
8050     }
8051 
8052     /**
8053      * @deprecated
8054      * Use {@link
8055      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
8056      * @removed
8057      */
8058     @Deprecated
8059     @RequiresPermission(allOf = {
8060             android.Manifest.permission.MODIFY_PHONE_STATE,
8061             Manifest.permission.ACCESS_FINE_LOCATION
8062     })
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)8063     public NetworkScan requestNetworkScan(
8064         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
8065         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
8066     }
8067 
8068     /**
8069      * Ask the radio to connect to the input network and change selection mode to manual.
8070      *
8071      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8072      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8073      *
8074      * <p>Requires Permission:
8075      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8076      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8077      *
8078      * @param operatorNumeric the PLMN ID of the network to select.
8079      * @param persistSelection whether the selection will persist until reboot. If true, only allows
8080      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
8081      * normal network selection next time.
8082      * @return {@code true} on success; {@code false} on any failure.
8083      */
8084     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8085     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)8086     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
8087         return setNetworkSelectionModeManual(
8088                 new OperatorInfo(
8089                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
8090                 persistSelection);
8091     }
8092 
8093     /**
8094      * Ask the radio to connect to the input network and change selection mode to manual.
8095      *
8096      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8097      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8098      *
8099      * <p>Requires Permission:
8100      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8101      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8102      *
8103      * @param operatorNumeric the PLMN ID of the network to select.
8104      * @param persistSelection whether the selection will persist until reboot.
8105      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
8106      *         attach to the chosen PLMN and resume normal network selection next time.
8107      * @param ran the initial suggested radio access network type.
8108      *         If registration fails, the RAN is not available after, the RAN is not within the
8109      *         network types specified by the preferred network types, or the value is
8110      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
8111      *         the next best RAN for network registration.
8112      * @return {@code true} on success; {@code false} on any failure.
8113      */
8114     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)8115     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
8116             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
8117         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
8118                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
8119     }
8120 
8121     /**
8122      * Ask the radio to connect to the input network and change selection mode to manual.
8123      *
8124      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8125      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8126      *
8127      * <p>Requires Permission:
8128      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8129      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8130      *
8131      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
8132      * @param persistSelection whether the selection will persist until reboot. If true, only allows
8133      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
8134      * normal network selection next time.
8135      * @return {@code true} on success; {@code true} on any failure.
8136      *
8137      * @hide
8138      */
8139     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)8140     public boolean setNetworkSelectionModeManual(
8141             OperatorInfo operatorInfo, boolean persistSelection) {
8142         try {
8143             ITelephony telephony = getITelephony();
8144             if (telephony != null) {
8145                 return telephony.setNetworkSelectionModeManual(
8146                         getSubId(), operatorInfo, persistSelection);
8147             }
8148         } catch (RemoteException ex) {
8149             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
8150         }
8151         return false;
8152     }
8153 
8154    /**
8155      * Get the network selection mode.
8156      *
8157      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8158      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8159      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
8160      * READ_PRECISE_PHONE_STATE}
8161      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8162      *
8163      * @return the network selection mode.
8164      */
8165     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
8166     @RequiresPermission(anyOf = {
8167             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8168             android.Manifest.permission.READ_PRECISE_PHONE_STATE
8169     })
getNetworkSelectionMode()8170     public @NetworkSelectionMode int getNetworkSelectionMode() {
8171         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
8172         try {
8173             ITelephony telephony = getITelephony();
8174             if (telephony != null) {
8175                 mode = telephony.getNetworkSelectionMode(getSubId());
8176             }
8177         } catch (RemoteException ex) {
8178             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
8179         }
8180         return mode;
8181     }
8182 
8183     /**
8184      * Get the PLMN chosen for Manual Network Selection if active.
8185      * Return empty string if in automatic selection.
8186      *
8187      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
8188      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
8189      * (see {@link #hasCarrierPrivileges})
8190      *
8191      * @return manually selected network info on success or empty string on failure
8192      */
8193     @SuppressAutoDoc // No support carrier privileges (b/72967236).
8194     @RequiresPermission(android.Manifest.permission.READ_PRECISE_PHONE_STATE)
getManualNetworkSelectionPlmn()8195     public @NonNull String getManualNetworkSelectionPlmn() {
8196         try {
8197             ITelephony telephony = getITelephony();
8198             if (telephony != null && isManualNetworkSelectionAllowed()) {
8199                 return telephony.getManualNetworkSelectionPlmn(getSubId());
8200             }
8201         } catch (RemoteException ex) {
8202             Rlog.e(TAG, "getManualNetworkSelectionPlmn RemoteException", ex);
8203         }
8204         return "";
8205     }
8206 
8207     /**
8208      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
8209      * user and we are still within the time interval after the emergency SMS was sent that we are
8210      * considered in Emergency SMS mode.
8211      *
8212      * <p>This mode is used by other applications to allow them to perform special functionality,
8213      * such as allow the GNSS service to provide user location to the carrier network for emergency
8214      * when an emergency SMS is sent. This interval is set by
8215      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
8216      * the carrier does not support this mode, this function will always return false.
8217      *
8218      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
8219      *
8220      * @hide
8221      */
8222     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isInEmergencySmsMode()8223     public boolean isInEmergencySmsMode() {
8224         try {
8225             ITelephony telephony = getITelephony();
8226             if (telephony != null) {
8227                 return telephony.isInEmergencySmsMode();
8228             }
8229         } catch (RemoteException ex) {
8230             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
8231         }
8232         return false;
8233     }
8234 
8235     /**
8236      * Set the preferred network type.
8237      *
8238      * <p>Requires Permission:
8239      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8240      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8241      *
8242      * @param subId the id of the subscription to set the preferred network type for.
8243      * @param networkType the preferred network type
8244      * @return true on success; false on any failure.
8245      * @hide
8246      * @deprecated Use {@link #setPreferredNetworkTypeBitmask} instead.
8247      */
8248     @Deprecated
8249     @UnsupportedAppUsage
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)8250     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
8251         try {
8252             ITelephony telephony = getITelephony();
8253             if (telephony != null) {
8254                 return telephony.setPreferredNetworkType(subId, networkType);
8255             }
8256         } catch (RemoteException ex) {
8257             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
8258         }
8259         return false;
8260     }
8261 
8262     /**
8263      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
8264      * only the allowed network type will set to the modem.
8265      *
8266      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8267      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8268      *
8269      * <p>Requires Permission:
8270      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8271      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8272      *
8273      * @param networkTypeBitmask The bitmask of preferred network types.
8274      * @return true on success; false on any failure.
8275      * @hide
8276      */
8277     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8278     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)8279     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
8280         try {
8281             ITelephony telephony = getITelephony();
8282             if (telephony != null) {
8283                 return telephony.setPreferredNetworkType(
8284                         getSubId(), RadioAccessFamily.getNetworkTypeFromRaf(
8285                                 (int) networkTypeBitmask));
8286             }
8287         } catch (RemoteException ex) {
8288             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
8289         }
8290         return false;
8291     }
8292 
8293     /**
8294      * Set the allowed network types of the device. This is for carrier or privileged apps to
8295      * enable/disable certain network types on the device. The user preferred network types should
8296      * be set through {@link #setPreferredNetworkTypeBitmask}.
8297      *
8298      * @param allowedNetworkTypes The bitmask of allowed network types.
8299      * @return true on success; false on any failure.
8300      * @hide
8301      */
8302     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8303     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)8304     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
8305         try {
8306             ITelephony telephony = getITelephony();
8307             if (telephony != null) {
8308                 return telephony.setAllowedNetworkTypes(getSubId(), allowedNetworkTypes);
8309             }
8310         } catch (RemoteException ex) {
8311             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
8312         }
8313         return false;
8314     }
8315 
8316     /** @hide */
8317     @IntDef({
8318             ALLOWED_NETWORK_TYPES_REASON_POWER
8319     })
8320     @Retention(RetentionPolicy.SOURCE)
8321     public @interface AllowedNetworkTypesReason{}
8322 
8323     /**
8324      * To indicate allowed network type change is requested by power manager.
8325      * Power Manger configuration won't affect the settings configured through
8326      * {@link setAllowedNetworkTypes} and will result in allowing network types that are in both
8327      * configurations (i.e intersection of both sets).
8328      * @hide
8329      */
8330     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 0;
8331 
8332     /**
8333      * Set the allowed network types of the device and
8334      * provide the reason triggering the allowed network change.
8335      * This can be called for following reasons
8336      * <ol>
8337      * <li>Allowed network types control by power manager
8338      * {@link #ALLOWED_NETWORK_TYPES_REASON_POWER}
8339      * </ol>
8340      * This API will result in allowing an intersection of allowed network types for all reasons,
8341      * including the configuration done through {@link setAllowedNetworkTypes}.
8342      * While this API and {@link setAllowedNetworkTypes} is controlling allowed network types
8343      * on device, user preference will still be set through {@link #setPreferredNetworkTypeBitmask}.
8344      * Thus resultant network type configured on modem will be an intersection of the network types
8345      * from setAllowedNetworkTypesForReason, {@link setAllowedNetworkTypes}
8346      * and {@link #setPreferredNetworkTypeBitmask}.
8347      *
8348      * @param reason the reason the allowed network type change is taking place
8349      * @param allowedNetworkTypes The bitmask of allowed network types.
8350      * @throws IllegalStateException if the Telephony process is not currently available.
8351      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8352      * @hide
8353      */
8354     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)8355     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
8356             @NetworkTypeBitMask long allowedNetworkTypes) {
8357         if (reason != ALLOWED_NETWORK_TYPES_REASON_POWER) {
8358             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8359         }
8360         try {
8361             ITelephony telephony = getITelephony();
8362             if (telephony != null) {
8363                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
8364                         allowedNetworkTypes);
8365             } else {
8366                 throw new IllegalStateException("telephony service is null.");
8367             }
8368         } catch (RemoteException ex) {
8369             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
8370             ex.rethrowFromSystemServer();
8371         }
8372     }
8373 
8374     /**
8375      * Get the allowed network types for certain reason.
8376      *
8377      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
8378      * specific reason. For effective allowed network types configured on device,
8379      * query {@link getEffectiveAllowedNetworkTypes}
8380      *
8381      * <p>Requires Permission:
8382      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8383      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8384      *s
8385      * @param reason the reason the allowed network type change is taking place
8386      * @return the allowed network type bitmask
8387      * @throws IllegalStateException if the Telephony process is not currently available.
8388      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8389      * @hide
8390      */
8391     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)8392     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
8393             @AllowedNetworkTypesReason int reason) {
8394         if (reason != ALLOWED_NETWORK_TYPES_REASON_POWER) {
8395             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8396         }
8397         try {
8398             ITelephony telephony = getITelephony();
8399             if (telephony != null) {
8400                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
8401             } else {
8402                 throw new IllegalStateException("telephony service is null.");
8403             }
8404         } catch (RemoteException ex) {
8405             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
8406             ex.rethrowFromSystemServer();
8407         }
8408         return -1;
8409     }
8410 
8411     /**
8412      * Get bit mask of all network types.
8413      *
8414      * @return bit mask of all network types
8415      * @hide
8416      */
getAllNetworkTypesBitmask()8417     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
8418         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
8419     }
8420 
8421     /**
8422      * Get the allowed network types configured on the device.
8423      * This API will return an intersection of allowed network types for all reasons,
8424      * including the configuration done through setAllowedNetworkTypes
8425      *
8426      * <p>Requires Permission:
8427      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8428      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8429      *
8430      * @return the allowed network type bitmask
8431      * @throws IllegalStateException if the Telephony process is not currently available.
8432      * @hide
8433      */
8434     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEffectiveAllowedNetworkTypes()8435     public @NetworkTypeBitMask long getEffectiveAllowedNetworkTypes() {
8436         try {
8437             ITelephony telephony = getITelephony();
8438             if (telephony != null) {
8439                 return telephony.getEffectiveAllowedNetworkTypes(getSubId());
8440             } else {
8441                 throw new IllegalStateException("telephony service is null.");
8442             }
8443         } catch (RemoteException ex) {
8444             Rlog.e(TAG, "getEffectiveAllowedNetworkTypes RemoteException", ex);
8445             ex.rethrowFromSystemServer();
8446         }
8447         return -1;
8448     }
8449 
8450     /**
8451      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8452      *
8453      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8454      *
8455      * @return true on success; false on any failure.
8456      */
setPreferredNetworkTypeToGlobal()8457     public boolean setPreferredNetworkTypeToGlobal() {
8458         return setPreferredNetworkTypeToGlobal(getSubId());
8459     }
8460 
8461     /**
8462      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8463      *
8464      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8465      *
8466      * @return true on success; false on any failure.
8467      * @hide
8468      */
setPreferredNetworkTypeToGlobal(int subId)8469     public boolean setPreferredNetworkTypeToGlobal(int subId) {
8470         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
8471     }
8472 
8473     /**
8474      * Check whether DUN APN is required for tethering.
8475      * <p>
8476      * Requires Permission: MODIFY_PHONE_STATE.
8477      *
8478      * @return {@code true} if DUN APN is required for tethering.
8479      * @hide
8480      */
8481     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8482     @SystemApi
isTetheringApnRequired()8483     public boolean isTetheringApnRequired() {
8484         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
8485     }
8486 
8487     /**
8488      * Check whether DUN APN is required for tethering with subId.
8489      *
8490      * @param subId the id of the subscription to require tethering.
8491      * @return {@code true} if DUN APN is required for tethering.
8492      * @hide
8493      */
isTetheringApnRequired(int subId)8494     public boolean isTetheringApnRequired(int subId) {
8495         try {
8496             ITelephony telephony = getITelephony();
8497             if (telephony != null)
8498                 return telephony.isTetheringApnRequiredForSubscriber(subId);
8499         } catch (RemoteException ex) {
8500             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
8501         } catch (NullPointerException ex) {
8502             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
8503         }
8504         return false;
8505     }
8506 
8507 
8508     /**
8509      * Values used to return status for hasCarrierPrivileges call.
8510      */
8511     /** @hide */ @SystemApi @TestApi
8512     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
8513     /** @hide */ @SystemApi @TestApi
8514     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
8515     /** @hide */ @SystemApi @TestApi
8516     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
8517     /** @hide */ @SystemApi @TestApi
8518     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
8519 
8520     /**
8521      * Has the calling application been granted carrier privileges by the carrier.
8522      *
8523      * If any of the packages in the calling UID has carrier privileges, the
8524      * call will return true. This access is granted by the owner of the UICC
8525      * card and does not depend on the registered carrier.
8526      *
8527      * @return true if the app has carrier privileges.
8528      */
hasCarrierPrivileges()8529     public boolean hasCarrierPrivileges() {
8530         return hasCarrierPrivileges(getSubId());
8531     }
8532 
8533     /**
8534      * Has the calling application been granted carrier privileges by the carrier.
8535      *
8536      * If any of the packages in the calling UID has carrier privileges, the
8537      * call will return true. This access is granted by the owner of the UICC
8538      * card and does not depend on the registered carrier.
8539      *
8540      * @param subId The subscription to use.
8541      * @return true if the app has carrier privileges.
8542      * @hide
8543      */
hasCarrierPrivileges(int subId)8544     public boolean hasCarrierPrivileges(int subId) {
8545         try {
8546             ITelephony telephony = getITelephony();
8547             if (telephony != null) {
8548                 return telephony.getCarrierPrivilegeStatus(subId)
8549                         == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
8550             }
8551         } catch (RemoteException ex) {
8552             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
8553         } catch (NullPointerException ex) {
8554             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
8555         }
8556         return false;
8557     }
8558 
8559     /**
8560      * Override the branding for the current ICCID.
8561      *
8562      * Once set, whenever the SIM is present in the device, the service
8563      * provider name (SPN) and the operator name will both be replaced by the
8564      * brand value input. To unset the value, the same function should be
8565      * called with a null brand value.
8566      *
8567      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8568      *
8569      * @param brand The brand name to display/set.
8570      * @return true if the operation was executed correctly.
8571      */
setOperatorBrandOverride(String brand)8572     public boolean setOperatorBrandOverride(String brand) {
8573         return setOperatorBrandOverride(getSubId(), brand);
8574     }
8575 
8576     /**
8577      * Override the branding for the current ICCID.
8578      *
8579      * Once set, whenever the SIM is present in the device, the service
8580      * provider name (SPN) and the operator name will both be replaced by the
8581      * brand value input. To unset the value, the same function should be
8582      * called with a null brand value.
8583      *
8584      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8585      *
8586      * @param subId The subscription to use.
8587      * @param brand The brand name to display/set.
8588      * @return true if the operation was executed correctly.
8589      * @hide
8590      */
setOperatorBrandOverride(int subId, String brand)8591     public boolean setOperatorBrandOverride(int subId, String brand) {
8592         try {
8593             ITelephony telephony = getITelephony();
8594             if (telephony != null)
8595                 return telephony.setOperatorBrandOverride(subId, brand);
8596         } catch (RemoteException ex) {
8597             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
8598         } catch (NullPointerException ex) {
8599             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
8600         }
8601         return false;
8602     }
8603 
8604     /**
8605      * Override the roaming preference for the current ICCID.
8606      *
8607      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
8608      * the platform's notion of a network operator being considered roaming or not.
8609      * The change only affects the ICCID that was active when this call was made.
8610      *
8611      * If null is passed as any of the input, the corresponding value is deleted.
8612      *
8613      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
8614      *
8615      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
8616      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
8617      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
8618      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
8619      * @return true if the operation was executed correctly.
8620      *
8621      * @hide
8622      */
8623     @UnsupportedAppUsage
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)8624     public boolean setRoamingOverride(List<String> gsmRoamingList,
8625             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
8626             List<String> cdmaNonRoamingList) {
8627         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
8628                 cdmaRoamingList, cdmaNonRoamingList);
8629     }
8630 
8631     /**
8632      * Override the roaming preference for the current ICCID.
8633      *
8634      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
8635      * the platform's notion of a network operator being considered roaming or not.
8636      * The change only affects the ICCID that was active when this call was made.
8637      *
8638      * If null is passed as any of the input, the corresponding value is deleted.
8639      *
8640      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
8641      *
8642      * @param subId for which the roaming overrides apply.
8643      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
8644      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
8645      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
8646      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
8647      * @return true if the operation was executed correctly.
8648      *
8649      * @hide
8650      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)8651     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
8652             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
8653             List<String> cdmaNonRoamingList) {
8654         try {
8655             ITelephony telephony = getITelephony();
8656             if (telephony != null)
8657                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
8658                         cdmaRoamingList, cdmaNonRoamingList);
8659         } catch (RemoteException ex) {
8660             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
8661         } catch (NullPointerException ex) {
8662             Rlog.e(TAG, "setRoamingOverride NPE", ex);
8663         }
8664         return false;
8665     }
8666 
8667     /**
8668      * Expose the rest of ITelephony to @SystemApi
8669      */
8670 
8671     /** @hide */
8672     @SystemApi
8673     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn()8674     public String getCdmaMdn() {
8675         return getCdmaMdn(getSubId());
8676     }
8677 
8678     /** @hide */
8679     @SystemApi
8680     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn(int subId)8681     public String getCdmaMdn(int subId) {
8682         try {
8683             ITelephony telephony = getITelephony();
8684             if (telephony == null)
8685                 return null;
8686             return telephony.getCdmaMdn(subId);
8687         } catch (RemoteException ex) {
8688             return null;
8689         } catch (NullPointerException ex) {
8690             return null;
8691         }
8692     }
8693 
8694     /** @hide */
8695     @SystemApi
8696     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin()8697     public String getCdmaMin() {
8698         return getCdmaMin(getSubId());
8699     }
8700 
8701     /** @hide */
8702     @SystemApi
8703     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin(int subId)8704     public String getCdmaMin(int subId) {
8705         try {
8706             ITelephony telephony = getITelephony();
8707             if (telephony == null)
8708                 return null;
8709             return telephony.getCdmaMin(subId);
8710         } catch (RemoteException ex) {
8711             return null;
8712         } catch (NullPointerException ex) {
8713             return null;
8714         }
8715     }
8716 
8717     /** @hide */
8718     @SystemApi
8719     @TestApi
8720     @SuppressLint("Doclava125")
checkCarrierPrivilegesForPackage(String pkgName)8721     public int checkCarrierPrivilegesForPackage(String pkgName) {
8722         try {
8723             ITelephony telephony = getITelephony();
8724             if (telephony != null)
8725                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
8726         } catch (RemoteException ex) {
8727             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
8728         } catch (NullPointerException ex) {
8729             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
8730         }
8731         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
8732     }
8733 
8734     /** @hide */
8735     @SystemApi
8736     @SuppressLint("Doclava125")
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)8737     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
8738         try {
8739             ITelephony telephony = getITelephony();
8740             if (telephony != null)
8741                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
8742         } catch (RemoteException ex) {
8743             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
8744         } catch (NullPointerException ex) {
8745             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
8746         }
8747         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
8748     }
8749 
8750     /** @hide */
8751     @SystemApi
8752     @TestApi
getCarrierPackageNamesForIntent(Intent intent)8753     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
8754         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
8755     }
8756 
8757     /** @hide */
8758     @SystemApi
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)8759     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
8760         try {
8761             ITelephony telephony = getITelephony();
8762             if (telephony != null)
8763                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
8764         } catch (RemoteException ex) {
8765             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
8766         } catch (NullPointerException ex) {
8767             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
8768         }
8769         return null;
8770     }
8771 
8772     /** @hide */
getPackagesWithCarrierPrivileges()8773     public List<String> getPackagesWithCarrierPrivileges() {
8774         try {
8775             ITelephony telephony = getITelephony();
8776             if (telephony != null) {
8777                 return telephony.getPackagesWithCarrierPrivileges(getPhoneId());
8778             }
8779         } catch (RemoteException ex) {
8780             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
8781         } catch (NullPointerException ex) {
8782             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
8783         }
8784         return Collections.EMPTY_LIST;
8785     }
8786 
8787     /**
8788      * Get the names of packages with carrier privileges for all the active subscriptions.
8789      *
8790      * @hide
8791      */
8792     @SystemApi
8793     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8794     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()8795     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
8796         try {
8797             ITelephony telephony = getITelephony();
8798             if (telephony != null) {
8799                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
8800             }
8801         } catch (RemoteException ex) {
8802             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
8803                     ex);
8804         } catch (NullPointerException ex) {
8805             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
8806         }
8807         return Collections.EMPTY_LIST;
8808     }
8809 
8810 
8811     /** @hide */
8812     @SystemApi
8813     @SuppressLint("Doclava125")
dial(String number)8814     public void dial(String number) {
8815         try {
8816             ITelephony telephony = getITelephony();
8817             if (telephony != null)
8818                 telephony.dial(number);
8819         } catch (RemoteException e) {
8820             Log.e(TAG, "Error calling ITelephony#dial", e);
8821         }
8822     }
8823 
8824     /**
8825      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
8826      * Bundle extras)} instead.
8827      * @hide
8828      */
8829     @Deprecated
8830     @SystemApi
8831     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
call(String callingPackage, String number)8832     public void call(String callingPackage, String number) {
8833         try {
8834             ITelephony telephony = getITelephony();
8835             if (telephony != null)
8836                 telephony.call(callingPackage, number);
8837         } catch (RemoteException e) {
8838             Log.e(TAG, "Error calling ITelephony#call", e);
8839         }
8840     }
8841 
8842     /**
8843      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
8844      * @hide
8845      * @removed
8846      */
8847     @Deprecated
8848     @SystemApi
8849     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()8850     public boolean endCall() {
8851         return false;
8852     }
8853 
8854     /**
8855      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
8856      * @hide
8857      * @removed
8858      */
8859     @Deprecated
8860     @SystemApi
8861     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()8862     public void answerRingingCall() {
8863         // No-op
8864     }
8865 
8866     /**
8867      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
8868      * @hide
8869      */
8870     @Deprecated
8871     @SystemApi
8872     @SuppressLint("Doclava125")
silenceRinger()8873     public void silenceRinger() {
8874         // No-op
8875     }
8876 
8877     /**
8878      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
8879      * @hide
8880      */
8881     @Deprecated
8882     @SystemApi
8883     @RequiresPermission(anyOf = {
8884             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8885             android.Manifest.permission.READ_PHONE_STATE
8886     })
isOffhook()8887     public boolean isOffhook() {
8888         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8889         return tm.isInCall();
8890     }
8891 
8892     /**
8893      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
8894      * @hide
8895      */
8896     @Deprecated
8897     @SystemApi
8898     @RequiresPermission(anyOf = {
8899             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8900             android.Manifest.permission.READ_PHONE_STATE
8901     })
isRinging()8902     public boolean isRinging() {
8903         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8904         return tm.isRinging();
8905     }
8906 
8907     /**
8908      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
8909      * @hide
8910      */
8911     @Deprecated
8912     @SystemApi
8913     @RequiresPermission(anyOf = {
8914             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8915             android.Manifest.permission.READ_PHONE_STATE
8916     })
isIdle()8917     public boolean isIdle() {
8918         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8919         return !tm.isInCall();
8920     }
8921 
8922     /**
8923      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
8924      * @hide
8925      */
8926     @Deprecated
8927     @SystemApi
8928     @RequiresPermission(anyOf = {
8929             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8930             android.Manifest.permission.READ_PHONE_STATE
8931     })
isRadioOn()8932     public boolean isRadioOn() {
8933         try {
8934             ITelephony telephony = getITelephony();
8935             if (telephony != null)
8936                 return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
8937         } catch (RemoteException e) {
8938             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
8939         }
8940         return false;
8941     }
8942 
8943     /** @hide */
8944     @SystemApi
8945     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPin(String pin)8946     public boolean supplyPin(String pin) {
8947         try {
8948             ITelephony telephony = getITelephony();
8949             if (telephony != null)
8950                 return telephony.supplyPinForSubscriber(getSubId(), pin);
8951         } catch (RemoteException e) {
8952             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
8953         }
8954         return false;
8955     }
8956 
8957     /** @hide */
8958     @SystemApi
8959     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPuk(String puk, String pin)8960     public boolean supplyPuk(String puk, String pin) {
8961         try {
8962             ITelephony telephony = getITelephony();
8963             if (telephony != null)
8964                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
8965         } catch (RemoteException e) {
8966             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
8967         }
8968         return false;
8969     }
8970 
8971     /** @hide */
8972     @SystemApi
8973     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPinReportResult(String pin)8974     public int[] supplyPinReportResult(String pin) {
8975         try {
8976             ITelephony telephony = getITelephony();
8977             if (telephony != null)
8978                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
8979         } catch (RemoteException e) {
8980             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
8981         }
8982         return new int[0];
8983     }
8984 
8985     /** @hide */
8986     @SystemApi
8987     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPukReportResult(String puk, String pin)8988     public int[] supplyPukReportResult(String puk, String pin) {
8989         try {
8990             ITelephony telephony = getITelephony();
8991             if (telephony != null)
8992                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
8993         } catch (RemoteException e) {
8994             Log.e(TAG, "Error calling ITelephony#]", e);
8995         }
8996         return new int[0];
8997     }
8998 
8999     /**
9000      * Used when the user attempts to enter their pin.
9001      *
9002      * @param pin The user entered pin.
9003      * @return The result of the pin.
9004      *
9005      * @hide
9006      */
9007     @Nullable
9008     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPinReportPinResult(@onNull String pin)9009     public PinResult supplyPinReportPinResult(@NonNull String pin) {
9010         try {
9011             ITelephony telephony = getITelephony();
9012             if (telephony != null) {
9013                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
9014                 return new PinResult(result[0], result[1]);
9015             }
9016         } catch (RemoteException e) {
9017             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
9018         }
9019         return null;
9020     }
9021 
9022     /**
9023      * Used when the user attempts to enter the puk or their pin.
9024      *
9025      * @param puk The product unblocking key.
9026      * @param pin The user entered pin.
9027      * @return The result of the pin.
9028      *
9029      * @hide
9030      */
9031     @Nullable
9032     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPukReportPinResult(@onNull String puk, @NonNull String pin)9033     public PinResult supplyPukReportPinResult(@NonNull String puk, @NonNull String pin) {
9034         try {
9035             ITelephony telephony = getITelephony();
9036             if (telephony != null) {
9037                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
9038                 return new PinResult(result[0], result[1]);
9039             }
9040         } catch (RemoteException e) {
9041             Log.e(TAG, "Error calling ITelephony#]", e);
9042         }
9043         return null;
9044     }
9045 
9046     /**
9047      * Used to notify callers of
9048      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
9049      * network either successfully executes a USSD request, or if there was a failure while
9050      * executing the request.
9051      * <p>
9052      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
9053      * USSD request has succeeded.
9054      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
9055      * USSD request has failed.
9056      */
9057     public static abstract class UssdResponseCallback {
9058        /**
9059         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
9060         * response received from the network.  The calling app can choose to either display the
9061         * response to the user or perform some operation based on the response.
9062         * <p>
9063         * USSD responses are unstructured text and their content is determined by the mobile network
9064         * operator.
9065         *
9066         * @param telephonyManager the TelephonyManager the callback is registered to.
9067         * @param request the USSD request sent to the mobile network.
9068         * @param response the response to the USSD request provided by the mobile network.
9069         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)9070        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
9071                                          String request, CharSequence response) {};
9072 
9073        /**
9074         * Called when a USSD request has failed to complete.
9075         *
9076         * @param telephonyManager the TelephonyManager the callback is registered to.
9077         * @param request the USSD request sent to the mobile network.
9078         * @param failureCode failure code indicating why the request failed.  Will be either
9079         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
9080         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
9081         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)9082        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
9083                                                String request, int failureCode) {};
9084     }
9085 
9086     /**
9087      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
9088      * informs the caller of the response via the supplied {@code callback}.
9089      * <p>Carriers define USSD codes which can be sent by the user to request information such as
9090      * the user's current data balance or minutes balance.
9091      * <p>Requires permission:
9092      * {@link android.Manifest.permission#CALL_PHONE}
9093      * @param ussdRequest the USSD command to be executed.
9094      * @param callback called by the framework to inform the caller of the result of executing the
9095      *                 USSD request (see {@link UssdResponseCallback}).
9096      * @param handler the {@link Handler} to run the request on.
9097      */
9098     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)9099     public void sendUssdRequest(String ussdRequest,
9100                                 final UssdResponseCallback callback, Handler handler) {
9101         checkNotNull(callback, "UssdResponseCallback cannot be null.");
9102         final TelephonyManager telephonyManager = this;
9103 
9104         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
9105             @Override
9106             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
9107                 Rlog.d(TAG, "USSD:" + resultCode);
9108                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
9109                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE);
9110 
9111                 if (resultCode == USSD_RETURN_SUCCESS) {
9112                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
9113                             response.getReturnMessage());
9114                 } else {
9115                     callback.onReceiveUssdResponseFailed(telephonyManager,
9116                             response.getUssdRequest(), resultCode);
9117                 }
9118             }
9119         };
9120 
9121         try {
9122             ITelephony telephony = getITelephony();
9123             if (telephony != null) {
9124                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
9125             }
9126         } catch (RemoteException e) {
9127             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
9128             UssdResponse response = new UssdResponse(ussdRequest, "");
9129             Bundle returnData = new Bundle();
9130             returnData.putParcelable(USSD_RESPONSE, response);
9131             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
9132         }
9133     }
9134 
9135     /**
9136      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
9137      * voice and data simultaneously. This can change based on location or network condition.
9138      *
9139      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
9140      */
isConcurrentVoiceAndDataSupported()9141     public boolean isConcurrentVoiceAndDataSupported() {
9142         try {
9143             ITelephony telephony = getITelephony();
9144             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
9145                     getSubId()));
9146         } catch (RemoteException e) {
9147             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
9148         }
9149         return false;
9150     }
9151 
9152     /** @hide */
9153     @SystemApi
9154     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmi(String dialString)9155     public boolean handlePinMmi(String dialString) {
9156         try {
9157             ITelephony telephony = getITelephony();
9158             if (telephony != null)
9159                 return telephony.handlePinMmi(dialString);
9160         } catch (RemoteException e) {
9161             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
9162         }
9163         return false;
9164     }
9165 
9166     /** @hide */
9167     @SystemApi
9168     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmiForSubscriber(int subId, String dialString)9169     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
9170         try {
9171             ITelephony telephony = getITelephony();
9172             if (telephony != null)
9173                 return telephony.handlePinMmiForSubscriber(subId, dialString);
9174         } catch (RemoteException e) {
9175             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
9176         }
9177         return false;
9178     }
9179 
9180     /** @hide */
9181     @SystemApi
9182     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
toggleRadioOnOff()9183     public void toggleRadioOnOff() {
9184         try {
9185             ITelephony telephony = getITelephony();
9186             if (telephony != null)
9187                 telephony.toggleRadioOnOff();
9188         } catch (RemoteException e) {
9189             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
9190         }
9191     }
9192 
9193     /** @hide */
9194     @SystemApi
9195     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadio(boolean turnOn)9196     public boolean setRadio(boolean turnOn) {
9197         try {
9198             ITelephony telephony = getITelephony();
9199             if (telephony != null)
9200                 return telephony.setRadio(turnOn);
9201         } catch (RemoteException e) {
9202             Log.e(TAG, "Error calling ITelephony#setRadio", e);
9203         }
9204         return false;
9205     }
9206 
9207     /** @hide */
9208     @SystemApi
9209     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioPower(boolean turnOn)9210     public boolean setRadioPower(boolean turnOn) {
9211         try {
9212             ITelephony telephony = getITelephony();
9213             if (telephony != null)
9214                 return telephony.setRadioPower(turnOn);
9215         } catch (RemoteException e) {
9216             Log.e(TAG, "Error calling ITelephony#setRadioPower", e);
9217         }
9218         return false;
9219     }
9220 
9221     /**
9222      * Shut down all the live radios over all the slot indexes.
9223      *
9224      * <p>To know when the radio has completed powering off, use
9225      * {@link PhoneStateListener#LISTEN_SERVICE_STATE LISTEN_SERVICE_STATE}.
9226      *
9227      * @hide
9228      */
9229     @SystemApi
9230     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
shutdownAllRadios()9231     public void shutdownAllRadios() {
9232         try {
9233             ITelephony telephony = getITelephony();
9234             if (telephony != null) {
9235                 telephony.shutdownMobileRadios();
9236             }
9237         } catch (RemoteException e) {
9238             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
9239             e.rethrowAsRuntimeException();
9240         }
9241     }
9242 
9243     /**
9244      * Check if any radio is on over all the slot indexes.
9245      *
9246      * @return {@code true} if any radio is on over any slot index.
9247      * @hide
9248      */
9249     @SystemApi
9250     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isAnyRadioPoweredOn()9251     public boolean isAnyRadioPoweredOn() {
9252         try {
9253             ITelephony telephony = getITelephony();
9254             if (telephony != null) {
9255                 return telephony.needMobileRadioShutdown();
9256             }
9257         } catch (RemoteException e) {
9258             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
9259             e.rethrowAsRuntimeException();
9260         }
9261         return false;
9262     }
9263 
9264     /**
9265      * Radio explicitly powered off (e.g, airplane mode).
9266      * @hide
9267      */
9268     @SystemApi
9269     public static final int RADIO_POWER_OFF = 0;
9270 
9271     /**
9272      * Radio power is on.
9273      * @hide
9274      */
9275     @SystemApi
9276     public static final int RADIO_POWER_ON = 1;
9277 
9278     /**
9279      * Radio power unavailable (eg, modem resetting or not booted).
9280      * @hide
9281      */
9282     @SystemApi
9283     public static final int RADIO_POWER_UNAVAILABLE = 2;
9284 
9285     /**
9286      * @return current modem radio state.
9287      *
9288      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
9289      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
9290      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9291      *
9292      * @hide
9293      */
9294     @SystemApi
9295     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9296             android.Manifest.permission.READ_PHONE_STATE})
getRadioPowerState()9297     public @RadioPowerState int getRadioPowerState() {
9298         try {
9299             ITelephony telephony = getITelephony();
9300             if (telephony != null) {
9301                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
9302                         mContext.getAttributionTag());
9303             }
9304         } catch (RemoteException ex) {
9305             // This could happen if binder process crashes.
9306         }
9307         return RADIO_POWER_UNAVAILABLE;
9308     }
9309 
9310     /** @hide */
9311     @SystemApi
9312     @SuppressLint("Doclava125")
updateServiceLocation()9313     public void updateServiceLocation() {
9314         try {
9315             ITelephony telephony = getITelephony();
9316             if (telephony != null)
9317                 telephony.updateServiceLocation();
9318         } catch (RemoteException e) {
9319             Log.e(TAG, "Error calling ITelephony#updateServiceLocation", e);
9320         }
9321     }
9322 
9323     /** @hide */
9324     @SystemApi
9325     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableDataConnectivity()9326     public boolean enableDataConnectivity() {
9327         try {
9328             ITelephony telephony = getITelephony();
9329             if (telephony != null)
9330                 return telephony.enableDataConnectivity();
9331         } catch (RemoteException e) {
9332             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
9333         }
9334         return false;
9335     }
9336 
9337     /** @hide */
9338     @SystemApi
9339     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
disableDataConnectivity()9340     public boolean disableDataConnectivity() {
9341         try {
9342             ITelephony telephony = getITelephony();
9343             if (telephony != null)
9344                 return telephony.disableDataConnectivity();
9345         } catch (RemoteException e) {
9346             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
9347         }
9348         return false;
9349     }
9350 
9351     /** @hide */
9352     @SystemApi
isDataConnectivityPossible()9353     public boolean isDataConnectivityPossible() {
9354         try {
9355             ITelephony telephony = getITelephony();
9356             if (telephony != null)
9357                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
9358                         .getActiveDataSubscriptionId()));
9359         } catch (RemoteException e) {
9360             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
9361         }
9362         return false;
9363     }
9364 
9365     /** @hide */
9366     @SystemApi
needsOtaServiceProvisioning()9367     public boolean needsOtaServiceProvisioning() {
9368         try {
9369             ITelephony telephony = getITelephony();
9370             if (telephony != null)
9371                 return telephony.needsOtaServiceProvisioning();
9372         } catch (RemoteException e) {
9373             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
9374         }
9375         return false;
9376     }
9377 
9378     /**
9379      * Turns mobile data on or off.
9380      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9381      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9382      *
9383      * <p>Requires Permission:
9384      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9385      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9386      *
9387      * @param enable Whether to enable mobile data.
9388      *
9389      */
9390     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9391     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(boolean enable)9392     public void setDataEnabled(boolean enable) {
9393         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
9394     }
9395 
9396     /**
9397      * @hide
9398      * @deprecated use {@link #setDataEnabled(boolean)} instead.
9399     */
9400     @SystemApi
9401     @Deprecated
9402     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(int subId, boolean enable)9403     public void setDataEnabled(int subId, boolean enable) {
9404         try {
9405             Log.d(TAG, "setDataEnabled: enabled=" + enable);
9406             ITelephony telephony = getITelephony();
9407             if (telephony != null)
9408                 telephony.setUserDataEnabled(subId, enable);
9409         } catch (RemoteException e) {
9410             Log.e(TAG, "Error calling ITelephony#setUserDataEnabled", e);
9411         }
9412     }
9413 
9414     /**
9415      * @deprecated use {@link #isDataEnabled()} instead.
9416      * @hide
9417      */
9418     @SystemApi
9419     @Deprecated
getDataEnabled()9420     public boolean getDataEnabled() {
9421         return isDataEnabled();
9422     }
9423 
9424     /**
9425      * Returns whether mobile data is enabled or not per user setting. There are other factors
9426      * that could disable mobile data, but they are not considered here.
9427      *
9428      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9429      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9430      *
9431      * <p>Requires one of the following permissions:
9432      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9433      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or that the calling app has carrier
9434      * privileges (see {@link #hasCarrierPrivileges}).
9435      *
9436      * <p>Note that this does not take into account any data restrictions that may be present on the
9437      * calling app. Such restrictions may be inspected with
9438      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
9439      *
9440      * @return true if mobile data is enabled.
9441      */
9442     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9443             android.Manifest.permission.MODIFY_PHONE_STATE})
isDataEnabled()9444     public boolean isDataEnabled() {
9445         return getDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
9446     }
9447 
9448     /**
9449      * Returns whether mobile data roaming is enabled on the subscription.
9450      *
9451      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9452      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9453      *
9454      * <p>Requires one of the following permissions:
9455      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9456      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling app
9457      * has carrier privileges (see {@link #hasCarrierPrivileges}).
9458      *
9459      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
9460      * {@code false}.
9461      */
9462     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9463             android.Manifest.permission.READ_PHONE_STATE})
isDataRoamingEnabled()9464     public boolean isDataRoamingEnabled() {
9465         boolean isDataRoamingEnabled = false;
9466         try {
9467             ITelephony telephony = getITelephony();
9468             if (telephony != null) {
9469                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
9470                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
9471             }
9472         } catch (RemoteException e) {
9473             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
9474         }
9475         return isDataRoamingEnabled;
9476     }
9477 
9478     /**
9479      * Gets the roaming mode for CDMA phone.
9480      *
9481      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9482      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9483      *
9484      * @return one of {@link #CDMA_ROAMING_MODE_RADIO_DEFAULT}, {@link #CDMA_ROAMING_MODE_HOME},
9485      * {@link #CDMA_ROAMING_MODE_AFFILIATED}, {@link #CDMA_ROAMING_MODE_ANY}.
9486      *
9487      * @hide
9488      */
9489     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaRoamingMode()9490     public @CdmaRoamingMode int getCdmaRoamingMode() {
9491         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
9492         try {
9493             ITelephony telephony = getITelephony();
9494             if (telephony != null) {
9495                 mode = telephony.getCdmaRoamingMode(getSubId());
9496             }
9497         } catch (RemoteException ex) {
9498             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
9499         }
9500         return mode;
9501     }
9502 
9503     /**
9504      * Sets the roaming mode for CDMA phone to the given mode {@code mode}.
9505      *
9506      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9507      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9508      *
9509      * @param mode should be one of {@link #CDMA_ROAMING_MODE_RADIO_DEFAULT},
9510      * {@link #CDMA_ROAMING_MODE_HOME}, {@link #CDMA_ROAMING_MODE_AFFILIATED},
9511      * {@link #CDMA_ROAMING_MODE_ANY}.
9512      *
9513      * @return {@code true} if successed.
9514      *
9515      * @hide
9516      */
9517     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaRoamingMode(@dmaRoamingMode int mode)9518     public boolean setCdmaRoamingMode(@CdmaRoamingMode int mode) {
9519         try {
9520             ITelephony telephony = getITelephony();
9521             if (telephony != null) {
9522                 return telephony.setCdmaRoamingMode(getSubId(), mode);
9523             }
9524         } catch (RemoteException ex) {
9525             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
9526         }
9527         return false;
9528     }
9529 
9530     /** @hide */
9531     @IntDef(flag = true, prefix = { "CDMA_SUBSCRIPTION_" }, value = {
9532             CDMA_SUBSCRIPTION_UNKNOWN,
9533             CDMA_SUBSCRIPTION_RUIM_SIM,
9534             CDMA_SUBSCRIPTION_NV
9535     })
9536     @Retention(RetentionPolicy.SOURCE)
9537     public @interface CdmaSubscription{}
9538 
9539     /** Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
9540      * @hide
9541      */
9542     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
9543 
9544     /** Used for CDMA subscription mode: RUIM/SIM (default)
9545      * @hide
9546      */
9547     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
9548 
9549     /** Used for CDMA subscription mode: NV -> non-volatile memory
9550      * @hide
9551      */
9552     public static final int CDMA_SUBSCRIPTION_NV       = 1;
9553 
9554     /** @hide */
9555     public static final int PREFERRED_CDMA_SUBSCRIPTION = CDMA_SUBSCRIPTION_RUIM_SIM;
9556 
9557     /**
9558      * Sets the subscription mode for CDMA phone to the given mode {@code mode}.
9559      *
9560      * @param mode CDMA subscription mode
9561      *
9562      * @return {@code true} if successed.
9563      *
9564      * @see #CDMA_SUBSCRIPTION_UNKNOWN
9565      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
9566      * @see #CDMA_SUBSCRIPTION_NV
9567      *
9568      * @hide
9569      */
9570     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaSubscriptionMode(@dmaSubscription int mode)9571     public boolean setCdmaSubscriptionMode(@CdmaSubscription int mode) {
9572         try {
9573             ITelephony telephony = getITelephony();
9574             if (telephony != null) {
9575                 return telephony.setCdmaSubscriptionMode(getSubId(), mode);
9576             }
9577         } catch (RemoteException ex) {
9578             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
9579         }
9580         return false;
9581     }
9582 
9583     /**
9584      * Enables/Disables the data roaming on the subscription.
9585      *
9586      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9587      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9588      *
9589      * <p> Requires permission:
9590      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
9591      * privileges (see {@link #hasCarrierPrivileges}).
9592      *
9593      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
9594      *
9595      * @hide
9596      */
9597     @SystemApi
9598     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataRoamingEnabled(boolean isEnabled)9599     public void setDataRoamingEnabled(boolean isEnabled) {
9600         try {
9601             ITelephony telephony = getITelephony();
9602             if (telephony != null) {
9603                 telephony.setDataRoamingEnabled(
9604                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
9605             }
9606         } catch (RemoteException e) {
9607             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
9608         }
9609     }
9610 
9611     /**
9612      * @deprecated use {@link #isDataEnabled()} instead.
9613      * @hide
9614      */
9615     @Deprecated
9616     @SystemApi
getDataEnabled(int subId)9617     public boolean getDataEnabled(int subId) {
9618         boolean retVal = false;
9619         try {
9620             ITelephony telephony = getITelephony();
9621             if (telephony != null)
9622                 retVal = telephony.isUserDataEnabled(subId);
9623         } catch (RemoteException | NullPointerException e) {
9624             Log.e(TAG, "Error calling ITelephony#isUserDataEnabled", e);
9625         }
9626         return retVal;
9627     }
9628 
9629     /**
9630      * Returns the result and response from RIL for oem request
9631      *
9632      * @param oemReq the data is sent to ril.
9633      * @param oemResp the respose data from RIL.
9634      * @return negative value request was not handled or get error
9635      *         0 request was handled succesfully, but no response data
9636      *         positive value success, data length of response
9637      * @hide
9638      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
9639      */
9640     @Deprecated
invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp)9641     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
9642         try {
9643             ITelephony telephony = getITelephony();
9644             if (telephony != null)
9645                 return telephony.invokeOemRilRequestRaw(oemReq, oemResp);
9646         } catch (RemoteException ex) {
9647         } catch (NullPointerException ex) {
9648         }
9649         return -1;
9650     }
9651 
9652     /**
9653      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
9654      * instead.
9655      * @hide
9656      */
9657     @Deprecated
9658     @SystemApi
9659     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableVideoCalling(boolean enable)9660     public void enableVideoCalling(boolean enable) {
9661         try {
9662             ITelephony telephony = getITelephony();
9663             if (telephony != null)
9664                 telephony.enableVideoCalling(enable);
9665         } catch (RemoteException e) {
9666             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
9667         }
9668     }
9669 
9670     /**
9671      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
9672      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
9673      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
9674      * determine if video calling is capable.
9675      * @hide
9676      */
9677     @Deprecated
9678     @SystemApi
9679     @RequiresPermission(anyOf = {
9680             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9681             android.Manifest.permission.READ_PHONE_STATE
9682     })
isVideoCallingEnabled()9683     public boolean isVideoCallingEnabled() {
9684         try {
9685             ITelephony telephony = getITelephony();
9686             if (telephony != null)
9687                 return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
9688         } catch (RemoteException e) {
9689             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
9690         }
9691         return false;
9692     }
9693 
9694     /**
9695      * Whether the device supports configuring the DTMF tone length.
9696      *
9697      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
9698      */
canChangeDtmfToneLength()9699     public boolean canChangeDtmfToneLength() {
9700         try {
9701             ITelephony telephony = getITelephony();
9702             if (telephony != null) {
9703                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
9704                         getAttributionTag());
9705             }
9706         } catch (RemoteException e) {
9707             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
9708         } catch (SecurityException e) {
9709             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
9710         }
9711         return false;
9712     }
9713 
9714     /**
9715      * Whether the device is a world phone.
9716      *
9717      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
9718      */
isWorldPhone()9719     public boolean isWorldPhone() {
9720         try {
9721             ITelephony telephony = getITelephony();
9722             if (telephony != null) {
9723                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
9724             }
9725         } catch (RemoteException e) {
9726             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
9727         } catch (SecurityException e) {
9728             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
9729         }
9730         return false;
9731     }
9732 
9733     /**
9734      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
9735      * Whether the phone supports TTY mode.
9736      *
9737      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
9738      *
9739      */
9740     @Deprecated
isTtyModeSupported()9741     public boolean isTtyModeSupported() {
9742         try {
9743             TelecomManager telecomManager = null;
9744             if (mContext != null) {
9745                 telecomManager = mContext.getSystemService(TelecomManager.class);
9746             }
9747             if (telecomManager != null) {
9748                 return telecomManager.isTtySupported();
9749             }
9750         } catch (SecurityException e) {
9751             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
9752         }
9753         return false;
9754     }
9755 
9756     /**
9757      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
9758      * support for the feature and device firmware support.
9759      *
9760      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
9761      */
isRttSupported()9762     public boolean isRttSupported() {
9763         try {
9764             ITelephony telephony = getITelephony();
9765             if (telephony != null) {
9766                 return telephony.isRttSupported(mSubId);
9767             }
9768         } catch (RemoteException e) {
9769             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
9770         } catch (SecurityException e) {
9771             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
9772         }
9773         return false;
9774     }
9775     /**
9776      * Whether the phone supports hearing aid compatibility.
9777      *
9778      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
9779      * otherwise.
9780      */
isHearingAidCompatibilitySupported()9781     public boolean isHearingAidCompatibilitySupported() {
9782         try {
9783             ITelephony telephony = getITelephony();
9784             if (telephony != null) {
9785                 return telephony.isHearingAidCompatibilitySupported();
9786             }
9787         } catch (RemoteException e) {
9788             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
9789         } catch (SecurityException e) {
9790             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
9791         }
9792         return false;
9793     }
9794 
9795     /**
9796      * Returns the IMS Registration Status for a particular Subscription ID.
9797      *
9798      * @param subId Subscription ID
9799      * @return true if IMS status is registered, false if the IMS status is not registered or a
9800      * RemoteException occurred.
9801      * Use {@link ImsMmTelManager.RegistrationCallback} instead.
9802      * @hide
9803      */
isImsRegistered(int subId)9804     public boolean isImsRegistered(int subId) {
9805         try {
9806             return getITelephony().isImsRegistered(subId);
9807         } catch (RemoteException | NullPointerException ex) {
9808             return false;
9809         }
9810     }
9811 
9812     /**
9813      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
9814      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
9815      * invalid subscription ID is used during creation, will the default subscription ID will be
9816      * used.
9817      *
9818      * @return true if IMS status is registered, false if the IMS status is not registered or a
9819      * RemoteException occurred.
9820      * @see SubscriptionManager#getDefaultSubscriptionId()
9821      * @hide
9822      */
9823     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()9824     public boolean isImsRegistered() {
9825        try {
9826            return getITelephony().isImsRegistered(getSubId());
9827        } catch (RemoteException | NullPointerException ex) {
9828            return false;
9829        }
9830     }
9831 
9832     /**
9833      * The current status of Voice over LTE for the subscription associated with this instance when
9834      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
9835      * used during creation, the default subscription ID will be used.
9836      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
9837      * @see SubscriptionManager#getDefaultSubscriptionId()
9838      * <p>
9839      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9840      * @hide
9841      */
9842     @UnsupportedAppUsage
isVolteAvailable()9843     public boolean isVolteAvailable() {
9844         try {
9845             return getITelephony().isAvailable(getSubId(),
9846                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
9847                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
9848         } catch (RemoteException | NullPointerException ex) {
9849             return false;
9850         }
9851     }
9852 
9853     /**
9854      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
9855      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
9856      * used during creation, the default subscription ID will be used. To query the
9857      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
9858      * @return true if VT is available, or false if it is unavailable or unknown.
9859      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9860      * @hide
9861      */
9862     @UnsupportedAppUsage
isVideoTelephonyAvailable()9863     public boolean isVideoTelephonyAvailable() {
9864         try {
9865             return getITelephony().isVideoTelephonyAvailable(getSubId());
9866         } catch (RemoteException | NullPointerException ex) {
9867             return false;
9868         }
9869     }
9870 
9871     /**
9872      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
9873      * @param subId the subscription ID.
9874      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
9875      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9876      * @hide
9877      */
9878     @UnsupportedAppUsage
isWifiCallingAvailable()9879     public boolean isWifiCallingAvailable() {
9880        try {
9881            return getITelephony().isWifiCallingAvailable(getSubId());
9882        } catch (RemoteException | NullPointerException ex) {
9883            return false;
9884        }
9885    }
9886 
9887     /**
9888      * The technology that IMS is registered for for the MMTEL feature.
9889      * @param subId subscription ID to get IMS registration technology for.
9890      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
9891      * Valid return results are:
9892      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
9893      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
9894      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
9895      *  result is unavailable.
9896      *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
9897      *  @hide
9898      */
getImsRegTechnologyForMmTel()9899     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
9900         try {
9901             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
9902         } catch (RemoteException ex) {
9903             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
9904         }
9905     }
9906 
9907    /**
9908     * Set TelephonyProperties.icc_operator_numeric for the default phone.
9909     *
9910     * @hide
9911     */
setSimOperatorNumeric(String numeric)9912     public void setSimOperatorNumeric(String numeric) {
9913         int phoneId = getPhoneId();
9914         setSimOperatorNumericForPhone(phoneId, numeric);
9915     }
9916 
9917    /**
9918     * Set TelephonyProperties.icc_operator_numeric for the given phone.
9919     *
9920     * @hide
9921     */
9922     @UnsupportedAppUsage
setSimOperatorNumericForPhone(int phoneId, String numeric)9923     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
9924         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9925             List<String> newList = updateTelephonyProperty(
9926                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
9927             TelephonyProperties.icc_operator_numeric(newList);
9928         }
9929     }
9930 
9931     /**
9932      * Set TelephonyProperties.icc_operator_alpha for the default phone.
9933      *
9934      * @hide
9935      */
setSimOperatorName(String name)9936     public void setSimOperatorName(String name) {
9937         int phoneId = getPhoneId();
9938         setSimOperatorNameForPhone(phoneId, name);
9939     }
9940 
9941     /**
9942      * Set TelephonyProperties.icc_operator_alpha for the given phone.
9943      *
9944      * @hide
9945      */
9946     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)9947     public void setSimOperatorNameForPhone(int phoneId, String name) {
9948         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9949             List<String> newList = updateTelephonyProperty(
9950                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
9951             TelephonyProperties.icc_operator_alpha(newList);
9952         }
9953     }
9954 
9955    /**
9956     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
9957     *
9958     * @hide
9959     */
setSimCountryIso(String iso)9960     public void setSimCountryIso(String iso) {
9961         int phoneId = getPhoneId();
9962         setSimCountryIsoForPhone(phoneId, iso);
9963     }
9964 
9965    /**
9966     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
9967     *
9968     * @hide
9969     */
9970     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)9971     public void setSimCountryIsoForPhone(int phoneId, String iso) {
9972         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9973             List<String> newList = updateTelephonyProperty(
9974                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
9975             TelephonyProperties.icc_operator_iso_country(newList);
9976         }
9977     }
9978 
9979     /**
9980      * Set TelephonyProperties.sim_state for the default phone.
9981      *
9982      * @hide
9983      */
setSimState(String state)9984     public void setSimState(String state) {
9985         int phoneId = getPhoneId();
9986         setSimStateForPhone(phoneId, state);
9987     }
9988 
9989     /**
9990      * Set TelephonyProperties.sim_state for the given phone.
9991      *
9992      * @hide
9993      */
9994     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)9995     public void setSimStateForPhone(int phoneId, String state) {
9996         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9997             List<String> newList = updateTelephonyProperty(
9998                     TelephonyProperties.sim_state(), phoneId, state);
9999             TelephonyProperties.sim_state(newList);
10000         }
10001     }
10002 
10003     /**
10004      * Powers down the SIM. SIM must be up prior.
10005      * @hide
10006      */
10007     public static final int CARD_POWER_DOWN = 0;
10008 
10009     /**
10010      * Powers up the SIM normally. SIM must be down prior.
10011      * @hide
10012      */
10013     public static final int CARD_POWER_UP = 1;
10014 
10015     /**
10016      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
10017      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
10018      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
10019      * and the SIM card is controlled completely by Telephony sending APDUs
10020      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
10021      * number of card apps will be 0.
10022      * No new error code is generated. Emergency calls are supported in the
10023      * same way as if the SIM card is absent.
10024      * The PASS_THROUGH mode is valid only for the specific card session where it
10025      * is activated, and normal behavior occurs at the next SIM initialization,
10026      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
10027      * is NOT persistent across boots. On reboot, SIM will power up normally.
10028      * @hide
10029      */
10030     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
10031 
10032     /**
10033      * Set SIM card power state.
10034      *
10035      * @param state  State of SIM (power down, power up, pass through)
10036      * @see #CARD_POWER_DOWN
10037      * @see #CARD_POWER_UP
10038      * @see #CARD_POWER_UP_PASS_THROUGH
10039      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
10040      * broadcasts to determine success or failure and timeout if needed.
10041      *
10042      * <p>Requires Permission:
10043      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10044      *
10045      * {@hide}
10046      **/
10047     @SystemApi
10048     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerState(int state)10049     public void setSimPowerState(int state) {
10050         setSimPowerStateForSlot(getSlotIndex(), state);
10051     }
10052 
10053     /**
10054      * Set SIM card power state.
10055      *
10056      * @param slotIndex SIM slot id
10057      * @param state  State of SIM (power down, power up, pass through)
10058      * @see #CARD_POWER_DOWN
10059      * @see #CARD_POWER_UP
10060      * @see #CARD_POWER_UP_PASS_THROUGH
10061      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
10062      * broadcasts to determine success or failure and timeout if needed.
10063      *
10064      * <p>Requires Permission:
10065      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10066      *
10067      * {@hide}
10068      **/
10069     @SystemApi
10070     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerStateForSlot(int slotIndex, int state)10071     public void setSimPowerStateForSlot(int slotIndex, int state) {
10072         try {
10073             ITelephony telephony = getITelephony();
10074             if (telephony != null) {
10075                 telephony.setSimPowerStateForSlot(slotIndex, state);
10076             }
10077         } catch (RemoteException e) {
10078             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
10079         } catch (SecurityException e) {
10080             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
10081         }
10082     }
10083 
10084     /**
10085      * Set baseband version for the default phone.
10086      *
10087      * @param version baseband version
10088      * @hide
10089      */
setBasebandVersion(String version)10090     public void setBasebandVersion(String version) {
10091         int phoneId = getPhoneId();
10092         setBasebandVersionForPhone(phoneId, version);
10093     }
10094 
10095     /**
10096      * Set baseband version by phone id.
10097      *
10098      * @param phoneId for which baseband version is set
10099      * @param version baseband version
10100      * @hide
10101      */
10102     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)10103     public void setBasebandVersionForPhone(int phoneId, String version) {
10104         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10105             List<String> newList = updateTelephonyProperty(
10106                     TelephonyProperties.baseband_version(), phoneId, version);
10107             TelephonyProperties.baseband_version(newList);
10108         }
10109     }
10110 
10111     /**
10112      * Get baseband version for the default phone.
10113      *
10114      * @return baseband version.
10115      * @hide
10116      */
getBasebandVersion()10117     public String getBasebandVersion() {
10118         int phoneId = getPhoneId();
10119         return getBasebandVersionForPhone(phoneId);
10120     }
10121 
10122     /**
10123      * Get baseband version by phone id.
10124      *
10125      * @return baseband version.
10126      * @hide
10127      */
getBasebandVersionForPhone(int phoneId)10128     public String getBasebandVersionForPhone(int phoneId) {
10129         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
10130     }
10131 
10132     /**
10133      * Set phone type for the default phone.
10134      *
10135      * @param type phone type
10136      *
10137      * @hide
10138      */
setPhoneType(int type)10139     public void setPhoneType(int type) {
10140         int phoneId = getPhoneId();
10141         setPhoneType(phoneId, type);
10142     }
10143 
10144     /**
10145      * Set phone type by phone id.
10146      *
10147      * @param phoneId for which phone type is set
10148      * @param type phone type
10149      *
10150      * @hide
10151      */
10152     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)10153     public void setPhoneType(int phoneId, int type) {
10154         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10155             List<Integer> newList = updateTelephonyProperty(
10156                     TelephonyProperties.current_active_phone(), phoneId, type);
10157             TelephonyProperties.current_active_phone(newList);
10158         }
10159     }
10160 
10161     /**
10162      * Get OTASP number schema for the default phone.
10163      *
10164      * @param defaultValue default value
10165      * @return OTA SP number schema
10166      *
10167      * @hide
10168      */
getOtaSpNumberSchema(String defaultValue)10169     public String getOtaSpNumberSchema(String defaultValue) {
10170         int phoneId = getPhoneId();
10171         return getOtaSpNumberSchemaForPhone(phoneId, defaultValue);
10172     }
10173 
10174     /**
10175      * Get OTASP number schema by phone id.
10176      *
10177      * @param phoneId for which OTA SP number schema is get
10178      * @param defaultValue default value
10179      * @return OTA SP number schema
10180      *
10181      * @hide
10182      */
10183     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)10184     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
10185         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10186             return getTelephonyProperty(
10187                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
10188         }
10189 
10190         return defaultValue;
10191     }
10192 
10193     /**
10194      * Get SMS receive capable from system property for the default phone.
10195      *
10196      * @param defaultValue default value
10197      * @return SMS receive capable
10198      *
10199      * @hide
10200      */
getSmsReceiveCapable(boolean defaultValue)10201     public boolean getSmsReceiveCapable(boolean defaultValue) {
10202         int phoneId = getPhoneId();
10203         return getSmsReceiveCapableForPhone(phoneId, defaultValue);
10204     }
10205 
10206     /**
10207      * Get SMS receive capable from system property by phone id.
10208      *
10209      * @param phoneId for which SMS receive capable is get
10210      * @param defaultValue default value
10211      * @return SMS receive capable
10212      *
10213      * @hide
10214      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)10215     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
10216         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10217             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
10218         }
10219 
10220         return defaultValue;
10221     }
10222 
10223     /**
10224      * Get SMS send capable from system property for the default phone.
10225      *
10226      * @param defaultValue default value
10227      * @return SMS send capable
10228      *
10229      * @hide
10230      */
getSmsSendCapable(boolean defaultValue)10231     public boolean getSmsSendCapable(boolean defaultValue) {
10232         int phoneId = getPhoneId();
10233         return getSmsSendCapableForPhone(phoneId, defaultValue);
10234     }
10235 
10236     /**
10237      * Get SMS send capable from system property by phone id.
10238      *
10239      * @param phoneId for which SMS send capable is get
10240      * @param defaultValue default value
10241      * @return SMS send capable
10242      *
10243      * @hide
10244      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)10245     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
10246         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10247             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
10248         }
10249 
10250         return defaultValue;
10251     }
10252 
10253     /**
10254      * Gets the default Respond Via Message application, updating the cache if there is no
10255      * respond-via-message application currently configured.
10256      * @return component name of the app and class to direct Respond Via Message intent to, or
10257      * {@code null} if the functionality is not supported.
10258      * @hide
10259      */
10260     @SystemApi
10261     @TestApi
10262     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
getAndUpdateDefaultRespondViaMessageApplication()10263     public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
10264         return SmsApplication.getDefaultRespondViaMessageApplication(mContext, true);
10265     }
10266 
10267     /**
10268      * Gets the default Respond Via Message application.
10269      * @return component name of the app and class to direct Respond Via Message intent to, or
10270      * {@code null} if the functionality is not supported.
10271      * @hide
10272      */
10273     @SystemApi
10274     @TestApi
10275     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
getDefaultRespondViaMessageApplication()10276     public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
10277         return SmsApplication.getDefaultRespondViaMessageApplication(mContext, false);
10278     }
10279 
10280     /**
10281      * Set the alphabetic name of current registered operator.
10282      * @param name the alphabetic name of current registered operator.
10283      * @hide
10284      */
setNetworkOperatorName(String name)10285     public void setNetworkOperatorName(String name) {
10286         int phoneId = getPhoneId();
10287         setNetworkOperatorNameForPhone(phoneId, name);
10288     }
10289 
10290     /**
10291      * Set the alphabetic name of current registered operator.
10292      * @param phoneId which phone you want to set
10293      * @param name the alphabetic name of current registered operator.
10294      * @hide
10295      */
10296     @UnsupportedAppUsage
setNetworkOperatorNameForPhone(int phoneId, String name)10297     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
10298         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10299             List<String> newList = updateTelephonyProperty(
10300                     TelephonyProperties.operator_alpha(), phoneId, name);
10301             TelephonyProperties.operator_alpha(newList);
10302         }
10303     }
10304 
10305     /**
10306      * Set the numeric name (MCC+MNC) of current registered operator.
10307      * @param operator the numeric name (MCC+MNC) of current registered operator
10308      * @hide
10309      */
setNetworkOperatorNumeric(String numeric)10310     public void setNetworkOperatorNumeric(String numeric) {
10311         int phoneId = getPhoneId();
10312         setNetworkOperatorNumericForPhone(phoneId, numeric);
10313     }
10314 
10315     /**
10316      * Set the numeric name (MCC+MNC) of current registered operator.
10317      * @param phoneId for which phone type is set
10318      * @param operator the numeric name (MCC+MNC) of current registered operator
10319      * @hide
10320      */
10321     @UnsupportedAppUsage
setNetworkOperatorNumericForPhone(int phoneId, String numeric)10322     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
10323         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10324             List<String> newList = updateTelephonyProperty(
10325                     TelephonyProperties.operator_numeric(), phoneId, numeric);
10326             TelephonyProperties.operator_numeric(newList);
10327         }
10328     }
10329 
10330     /**
10331      * Set roaming state of the current network, for GSM purposes.
10332      * @param isRoaming is network in romaing state or not
10333      * @hide
10334      */
setNetworkRoaming(boolean isRoaming)10335     public void setNetworkRoaming(boolean isRoaming) {
10336         int phoneId = getPhoneId();
10337         setNetworkRoamingForPhone(phoneId, isRoaming);
10338     }
10339 
10340     /**
10341      * Set roaming state of the current network, for GSM purposes.
10342      * @param phoneId which phone you want to set
10343      * @param isRoaming is network in romaing state or not
10344      * @hide
10345      */
10346     @UnsupportedAppUsage
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)10347     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
10348         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10349             List<Boolean> newList = updateTelephonyProperty(
10350                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
10351             TelephonyProperties.operator_is_roaming(newList);
10352         }
10353     }
10354 
10355     /**
10356      * Set the network type currently in use on the device for data transmission.
10357      *
10358      * If this object has been created with {@link #createForSubscriptionId}, applies to the
10359      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
10360      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10361      * @param type the network type currently in use on the device for data transmission
10362      * @hide
10363      */
setDataNetworkType(int type)10364     public void setDataNetworkType(int type) {
10365         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
10366         setDataNetworkTypeForPhone(phoneId, type);
10367     }
10368 
10369     /**
10370      * Set the network type currently in use on the device for data transmission.
10371      * @param phoneId which phone you want to set
10372      * @param type the network type currently in use on the device for data transmission
10373      * @hide
10374      */
10375     @UnsupportedAppUsage
setDataNetworkTypeForPhone(int phoneId, int type)10376     public void setDataNetworkTypeForPhone(int phoneId, int type) {
10377         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10378             List<String> newList = updateTelephonyProperty(
10379                     TelephonyProperties.data_network_type(), phoneId,
10380                     ServiceState.rilRadioTechnologyToString(type));
10381             TelephonyProperties.data_network_type(newList);
10382         }
10383     }
10384 
10385     /**
10386      * Returns the subscription ID for the given phone account.
10387      * @hide
10388      */
10389     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)10390     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
10391         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
10392         try {
10393             ITelephony service = getITelephony();
10394             if (service != null) {
10395                 retval = service.getSubIdForPhoneAccount(phoneAccount);
10396             }
10397         } catch (RemoteException e) {
10398         }
10399 
10400         return retval;
10401     }
10402 
10403     /**
10404      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
10405      *
10406      * @param subscriptionId The subscription Id to check.
10407      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
10408      * there is no associated {@link PhoneAccountHandle}.
10409      * @hide
10410      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)10411     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
10412         PhoneAccountHandle returnValue = null;
10413         try {
10414             ITelephony service = getITelephony();
10415             if (service != null) {
10416                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
10417             }
10418         } catch (RemoteException e) {
10419         }
10420 
10421         return returnValue;
10422     }
10423 
10424     /**
10425      * Returns the subscription ID for the given phone account handle.
10426      *
10427      * @param phoneAccountHandle the phone account handle for outgoing calls
10428      * @return subscription ID for the given phone account handle; or
10429      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
10430      *         if not available; or throw a SecurityException if the caller doesn't have the
10431      *         permission.
10432      */
10433     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)10434     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
10435         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
10436         try {
10437             ITelephony service = getITelephony();
10438             if (service != null) {
10439                 retval = service.getSubIdForPhoneAccountHandle(
10440                         phoneAccountHandle, mContext.getOpPackageName(),
10441                         mContext.getAttributionTag());
10442             }
10443         } catch (RemoteException ex) {
10444             Log.e(TAG, "getSubscriptionId RemoteException", ex);
10445             ex.rethrowAsRuntimeException();
10446         }
10447         return retval;
10448     }
10449 
10450     /**
10451      * Resets telephony manager settings back to factory defaults.
10452      *
10453      * @hide
10454      */
factoryReset(int subId)10455     public void factoryReset(int subId) {
10456         try {
10457             Log.d(TAG, "factoryReset: subId=" + subId);
10458             ITelephony telephony = getITelephony();
10459             if (telephony != null) {
10460                 telephony.factoryReset(subId);
10461             }
10462         } catch (RemoteException e) {
10463         }
10464     }
10465 
10466 
10467     /**
10468      * Resets Telephony and IMS settings back to factory defaults only for the subscription
10469      * associated with this instance.
10470      * @see #createForSubscriptionId(int)
10471      * @hide
10472      */
10473     @SystemApi
10474     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
resetSettings()10475     public void resetSettings() {
10476         try {
10477             Log.d(TAG, "resetSettings: subId=" + getSubId());
10478             ITelephony telephony = getITelephony();
10479             if (telephony != null) {
10480                 telephony.factoryReset(getSubId());
10481             }
10482         } catch (RemoteException e) {
10483         }
10484     }
10485 
10486 
10487     /**
10488      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
10489      * no locale could be derived from subscriptions.
10490      *
10491      * <p>Requires Permission:
10492      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
10493      *
10494      * @see Locale#toLanguageTag()
10495      *
10496      * @hide
10497      */
10498     @SystemApi
10499     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimLocale()10500     @Nullable public Locale getSimLocale() {
10501         try {
10502             final ITelephony telephony = getITelephony();
10503             if (telephony != null) {
10504                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
10505                 if (!TextUtils.isEmpty(languageTag)) {
10506                     return Locale.forLanguageTag(languageTag);
10507                 }
10508             }
10509         } catch (RemoteException ex) {
10510         }
10511         return null;
10512     }
10513 
10514     /**
10515      * TODO delete after SuW migrates to new API.
10516      * @hide
10517      */
getLocaleFromDefaultSim()10518     public String getLocaleFromDefaultSim() {
10519         try {
10520             final ITelephony telephony = getITelephony();
10521             if (telephony != null) {
10522                 return telephony.getSimLocaleForSubscriber(getSubId());
10523             }
10524         } catch (RemoteException ex) {
10525         }
10526         return null;
10527     }
10528 
10529 
10530     /**
10531      * Requests the modem activity info. The recipient will place the result
10532      * in `result`.
10533      * @param result The object on which the recipient will send the resulting
10534      * {@link android.telephony.ModemActivityInfo} object with key of
10535      * {@link #MODEM_ACTIVITY_RESULT_KEY}.
10536      * @hide
10537      */
requestModemActivityInfo(@onNull ResultReceiver result)10538     public void requestModemActivityInfo(@NonNull ResultReceiver result) {
10539         try {
10540             ITelephony service = getITelephony();
10541             if (service != null) {
10542                 service.requestModemActivityInfo(result);
10543                 return;
10544             }
10545         } catch (RemoteException e) {
10546             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
10547         }
10548         result.send(0, null);
10549     }
10550 
10551     /**
10552      * Returns the current {@link ServiceState} information.
10553      *
10554      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10555      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10556      *
10557      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
10558      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
10559      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
10560      */
10561     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
10562     @RequiresPermission(allOf = {
10563             Manifest.permission.READ_PHONE_STATE,
10564             Manifest.permission.ACCESS_COARSE_LOCATION
10565     })
getServiceState()10566     public ServiceState getServiceState() {
10567         return getServiceStateForSubscriber(getSubId());
10568     }
10569 
10570     /**
10571      * Returns the service state information on specified subscription. Callers require
10572      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
10573      * @hide
10574      */
10575     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)10576     public ServiceState getServiceStateForSubscriber(int subId) {
10577         try {
10578             ITelephony service = getITelephony();
10579             if (service != null) {
10580                 return service.getServiceStateForSubscriber(subId, getOpPackageName(),
10581                         getAttributionTag());
10582             }
10583         } catch (RemoteException e) {
10584             Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
10585         } catch (NullPointerException e) {
10586             AnomalyReporter.reportAnomaly(
10587                     UUID.fromString("a3ab0b9d-f2aa-4baf-911d-7096c0d4645a"),
10588                     "getServiceStateForSubscriber " + subId + " NPE");
10589         }
10590         return null;
10591     }
10592 
10593     /**
10594      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
10595      *
10596      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
10597      * voicemail ringtone.
10598      * @return The URI for the ringtone to play when receiving a voicemail from a specific
10599      * PhoneAccount.
10600      */
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)10601     public Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
10602         try {
10603             ITelephony service = getITelephony();
10604             if (service != null) {
10605                 return service.getVoicemailRingtoneUri(accountHandle);
10606             }
10607         } catch (RemoteException e) {
10608             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
10609         }
10610         return null;
10611     }
10612 
10613     /**
10614      * Sets the per-account voicemail ringtone.
10615      *
10616      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
10617      * {@link #hasCarrierPrivileges}, or has permission
10618      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10619      *
10620      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
10621      * voicemail ringtone.
10622      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
10623      * PhoneAccount.
10624      *
10625      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
10626      * instead.
10627      */
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)10628     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
10629         try {
10630             ITelephony service = getITelephony();
10631             if (service != null) {
10632                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
10633             }
10634         } catch (RemoteException e) {
10635             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
10636         }
10637     }
10638 
10639     /**
10640      * Returns whether vibration is set for voicemail notification in Phone settings.
10641      *
10642      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
10643      * voicemail vibration setting.
10644      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
10645      */
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)10646     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
10647         try {
10648             ITelephony service = getITelephony();
10649             if (service != null) {
10650                 return service.isVoicemailVibrationEnabled(accountHandle);
10651             }
10652         } catch (RemoteException e) {
10653             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
10654         }
10655         return false;
10656     }
10657 
10658     /**
10659      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
10660      *
10661      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
10662      * {@link #hasCarrierPrivileges}, or has permission
10663      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10664      *
10665      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
10666      * voicemail vibration setting.
10667      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
10668      * specific PhoneAccount.
10669      *
10670      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
10671      * instead.
10672      */
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)10673     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
10674             boolean enabled) {
10675         try {
10676             ITelephony service = getITelephony();
10677             if (service != null) {
10678                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
10679                         enabled);
10680             }
10681         } catch (RemoteException e) {
10682             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
10683         }
10684     }
10685 
10686     /**
10687      * Returns carrier id of the current subscription.
10688      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
10689      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
10690      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
10691      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10692      *
10693      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
10694      * as an Android platform-wide identifier for carriers.
10695      *
10696      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
10697      * subscription is unavailable or the carrier cannot be identified.
10698      */
getSimCarrierId()10699     public int getSimCarrierId() {
10700         try {
10701             ITelephony service = getITelephony();
10702             if (service != null) {
10703                 return service.getSubscriptionCarrierId(getSubId());
10704             }
10705         } catch (RemoteException ex) {
10706             // This could happen if binder process crashes.
10707         }
10708         return UNKNOWN_CARRIER_ID;
10709     }
10710 
10711     /**
10712      * Returns carrier id name of the current subscription.
10713      * <p>Carrier id name is a user-facing name of carrier id returned by
10714      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
10715      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
10716      * should have a single carrier name. Carrier name is not a canonical identity,
10717      * use {@link #getSimCarrierId()} instead.
10718      * <p>The returned carrier name is unlocalized.
10719      *
10720      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
10721      * unavailable or the carrier cannot be identified.
10722      */
getSimCarrierIdName()10723     public @Nullable CharSequence getSimCarrierIdName() {
10724         try {
10725             ITelephony service = getITelephony();
10726             if (service != null) {
10727                 return service.getSubscriptionCarrierName(getSubId());
10728             }
10729         } catch (RemoteException ex) {
10730             // This could happen if binder process crashes.
10731         }
10732         return null;
10733     }
10734 
10735     /**
10736      * Returns fine-grained carrier ID of the current subscription.
10737      *
10738      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
10739      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
10740      * are used to make up the actual carrier service may have different carrier configurations.
10741      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
10742      * different carrier configuration for different service offering such as a prepaid plan.
10743      *
10744      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
10745      * about the carrier itself should use the regular carrier ID returned by
10746      * {@link #getSimCarrierId()}.
10747      *
10748      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
10749      * subscription while carrier ID remains the same.
10750      *
10751      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
10752      * <p>Specific carrier ids are defined in the same way as carrier id
10753      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10754      * except each with a "parent" id linking to its top-level carrier id.
10755      *
10756      * @return Returns fine-grained carrier id of the current subscription.
10757      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
10758      * be identified.
10759      */
getSimSpecificCarrierId()10760     public int getSimSpecificCarrierId() {
10761         try {
10762             ITelephony service = getITelephony();
10763             if (service != null) {
10764                 return service.getSubscriptionSpecificCarrierId(getSubId());
10765             }
10766         } catch (RemoteException ex) {
10767             // This could happen if binder process crashes.
10768         }
10769         return UNKNOWN_CARRIER_ID;
10770     }
10771 
10772     /**
10773      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
10774      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
10775      *
10776      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
10777      * about the carrier itself should use the regular carrier ID returned by
10778      * {@link #getSimCarrierIdName()}.
10779      *
10780      * <p>The returned name is unlocalized.
10781      *
10782      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
10783      * subscription is unavailable or the carrier cannot be identified.
10784      */
getSimSpecificCarrierIdName()10785     public @Nullable CharSequence getSimSpecificCarrierIdName() {
10786         try {
10787             ITelephony service = getITelephony();
10788             if (service != null) {
10789                 return service.getSubscriptionSpecificCarrierName(getSubId());
10790             }
10791         } catch (RemoteException ex) {
10792             // This could happen if binder process crashes.
10793         }
10794         return null;
10795     }
10796 
10797     /**
10798      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
10799      * This is used for fallback when configurations/logic for exact carrier id
10800      * {@link #getSimCarrierId()} are not found.
10801      *
10802      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10803      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
10804      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
10805      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
10806      * take the update with the new id, it might be helpful to always fallback by using carrier
10807      * id based on MCCMNC if there is no match.
10808      *
10809      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
10810      * subscription is unavailable or the carrier cannot be identified.
10811      */
getCarrierIdFromSimMccMnc()10812     public int getCarrierIdFromSimMccMnc() {
10813         try {
10814             ITelephony service = getITelephony();
10815             if (service != null) {
10816                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
10817             }
10818         } catch (RemoteException ex) {
10819             // This could happen if binder process crashes.
10820         }
10821         return UNKNOWN_CARRIER_ID;
10822     }
10823 
10824      /**
10825       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
10826       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
10827       * are not found.
10828       *
10829       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10830       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
10831       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
10832       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
10833       * take the update with the new id, it might be helpful to always fallback by using carrier
10834       * id based on MCCMNC if there is no match.
10835       *
10836       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
10837       * subscription is unavailable or the carrier cannot be identified.
10838       * @hide
10839       */
10840      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)10841      public int getCarrierIdFromMccMnc(String mccmnc) {
10842         try {
10843             ITelephony service = getITelephony();
10844             if (service != null) {
10845                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
10846             }
10847         } catch (RemoteException ex) {
10848             // This could happen if binder process crashes.
10849         }
10850         return UNKNOWN_CARRIER_ID;
10851     }
10852 
10853     /**
10854      * Return a list of certs in hex string from loaded carrier privileges access rules.
10855      *
10856      * @return a list of certificate in hex string. return {@code null} if there is no certs
10857      * or privilege rules are not loaded yet.
10858      *
10859      * <p>Requires Permission:
10860      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
10861      * @hide
10862      */
10863     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCertsFromCarrierPrivilegeAccessRules()10864     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
10865         try {
10866             ITelephony service = getITelephony();
10867             if (service != null) {
10868                 return service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
10869             }
10870         } catch (RemoteException ex) {
10871             // This could happen if binder process crashes.
10872         }
10873         return null;
10874     }
10875 
10876     /**
10877      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
10878      * All uicc applications are uniquely identified by application ID, represented by the hex
10879      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
10880      * <p>Requires Permission:
10881      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
10882      *
10883      * @param appType the uicc app type.
10884      * @return Application ID for specified app type or {@code null} if no uicc or error.
10885      * @hide
10886      */
10887     @Nullable
10888     @SystemApi
10889     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAidForAppType(@iccAppType int appType)10890     public String getAidForAppType(@UiccAppType int appType) {
10891         return getAidForAppType(getSubId(), appType);
10892     }
10893 
10894     /**
10895      * same as {@link #getAidForAppType(int)}
10896      * @hide
10897      */
getAidForAppType(int subId, int appType)10898     public String getAidForAppType(int subId, int appType) {
10899         try {
10900             ITelephony service = getITelephony();
10901             if (service != null) {
10902                 return service.getAidForAppType(subId, appType);
10903             }
10904         } catch (RemoteException e) {
10905             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
10906         }
10907         return null;
10908     }
10909 
10910     /**
10911      * Return the Electronic Serial Number.
10912      *
10913      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10914      *
10915      * @return ESN or null if error.
10916      * @hide
10917      */
getEsn()10918     public String getEsn() {
10919         return getEsn(getSubId());
10920     }
10921 
10922     /**
10923      * Return the Electronic Serial Number.
10924      *
10925      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10926      *
10927      * @param subId the subscription ID that this request applies to.
10928      * @return ESN or null if error.
10929      * @hide
10930      */
getEsn(int subId)10931     public String getEsn(int subId) {
10932         try {
10933             ITelephony service = getITelephony();
10934             if (service != null) {
10935                 return service.getEsn(subId);
10936             }
10937         } catch (RemoteException e) {
10938             Log.e(TAG, "Error calling ITelephony#getEsn", e);
10939         }
10940         return null;
10941     }
10942 
10943     /**
10944      * Return the Preferred Roaming List Version
10945      *
10946      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10947      *
10948      * @return PRLVersion or null if error.
10949      * @hide
10950      */
10951     @SystemApi
getCdmaPrlVersion()10952     public String getCdmaPrlVersion() {
10953         return getCdmaPrlVersion(getSubId());
10954     }
10955 
10956     /**
10957      * Return the Preferred Roaming List Version
10958      *
10959      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10960      *
10961      * @param subId the subscription ID that this request applies to.
10962      * @return PRLVersion or null if error.
10963      * @hide
10964      */
getCdmaPrlVersion(int subId)10965     public String getCdmaPrlVersion(int subId) {
10966         try {
10967             ITelephony service = getITelephony();
10968             if (service != null) {
10969                 return service.getCdmaPrlVersion(subId);
10970             }
10971         } catch (RemoteException e) {
10972             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
10973         }
10974         return null;
10975     }
10976 
10977     /**
10978      * Get snapshot of Telephony histograms
10979      * @return List of Telephony histograms
10980      * Requires Permission:
10981      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10982      * Or the calling app has carrier privileges.
10983      * @hide
10984      */
10985     @SystemApi
10986     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()10987     public List<TelephonyHistogram> getTelephonyHistograms() {
10988         try {
10989             ITelephony service = getITelephony();
10990             if (service != null) {
10991                 return service.getTelephonyHistograms();
10992             }
10993         } catch (RemoteException e) {
10994             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
10995         }
10996         return null;
10997     }
10998 
10999     /**
11000      * Set the allowed carrier list for slotIndex
11001      * Require system privileges. In the future we may add this to carrier APIs.
11002      *
11003      * <p>Requires Permission:
11004      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
11005      *
11006      * <p>This method works only on devices with {@link
11007      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11008      *
11009      * @deprecated use setCarrierRestrictionRules instead
11010      *
11011      * @return The number of carriers set successfully. Should be length of
11012      * carrierList on success; -1 if carrierList null or on error.
11013      * @hide
11014      */
11015     @SystemApi
11016     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)11017     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
11018         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
11019             return -1;
11020         }
11021         // Execute the method setCarrierRestrictionRules with an empty excluded list and
11022         // indicating priority for the allowed list.
11023         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
11024                 .setAllowedCarriers(carriers)
11025                 .setDefaultCarrierRestriction(
11026                     CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
11027                 .build();
11028 
11029         int result = setCarrierRestrictionRules(carrierRestrictionRules);
11030 
11031         // Convert result into int, as required by this method.
11032         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
11033             return carriers.size();
11034         } else {
11035             return -1;
11036         }
11037     }
11038 
11039     /**
11040      * The carrier restrictions were successfully set.
11041      * @hide
11042      */
11043     @SystemApi
11044     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
11045 
11046     /**
11047      * The carrier restrictions were not set due to lack of support in the modem. This can happen
11048      * if the modem does not support setting the carrier restrictions or if the configuration
11049      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
11050      * @hide
11051      */
11052     @SystemApi
11053     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
11054 
11055     /**
11056      * The setting of carrier restrictions failed.
11057      * @hide
11058      */
11059     @SystemApi
11060     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
11061 
11062     /** @hide */
11063     @Retention(RetentionPolicy.SOURCE)
11064     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
11065             value = {
11066                     SET_CARRIER_RESTRICTION_SUCCESS,
11067                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
11068                     SET_CARRIER_RESTRICTION_ERROR
11069             })
11070     public @interface SetCarrierRestrictionResult {}
11071 
11072     /**
11073      * Set the allowed carrier list and the excluded carrier list indicating the priority between
11074      * the two lists.
11075      * Requires system privileges.
11076      *
11077      * <p>Requires Permission:
11078      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
11079      *
11080      * <p>This method works only on devices with {@link
11081      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11082      *
11083      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
11084      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
11085      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
11086      * @hide
11087      */
11088     @SystemApi
11089     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11090     @SetCarrierRestrictionResult
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)11091     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
11092         try {
11093             ITelephony service = getITelephony();
11094             if (service != null) {
11095                 return service.setAllowedCarriers(rules);
11096             }
11097         } catch (RemoteException e) {
11098             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
11099         } catch (NullPointerException e) {
11100             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
11101         }
11102         return SET_CARRIER_RESTRICTION_ERROR;
11103     }
11104 
11105     /**
11106      * Get the allowed carrier list for slotIndex.
11107      * Requires system privileges.
11108      *
11109      * <p>This method returns valid data on devices with {@link
11110      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11111      *
11112      * @deprecated Apps should use {@link getCarriersRestrictionRules} to retrieve the list of
11113      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
11114      * list is empty. This API could return an empty list, even if some restrictions are present.
11115      *
11116      * @return List of {@link android.telephony.CarrierIdentifier}; empty list
11117      * means all carriers are allowed.
11118      * @hide
11119      */
11120     @Deprecated
11121     @SystemApi
11122     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedCarriers(int slotIndex)11123     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
11124         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
11125             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
11126             if (carrierRestrictionRule != null) {
11127                 return carrierRestrictionRule.getAllowedCarriers();
11128             }
11129         }
11130         return new ArrayList<CarrierIdentifier>(0);
11131     }
11132 
11133     /**
11134      * Get the allowed carrier list and the excluded carrier list indicating the priority between
11135      * the two lists.
11136      * Require system privileges. In the future we may add this to carrier APIs.
11137      *
11138      * <p>This method returns valid data on devices with {@link
11139      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11140      *
11141      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
11142      * excluded carrier list with the priority between the two lists. Returns {@code null}
11143      * in case of error.
11144      * @hide
11145      */
11146     @SystemApi
11147     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11148     @Nullable
getCarrierRestrictionRules()11149     public CarrierRestrictionRules getCarrierRestrictionRules() {
11150         try {
11151             ITelephony service = getITelephony();
11152             if (service != null) {
11153                 return service.getAllowedCarriers();
11154             }
11155         } catch (RemoteException e) {
11156             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
11157         } catch (NullPointerException e) {
11158             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
11159         }
11160         return null;
11161     }
11162 
11163     /**
11164      * Used to enable or disable carrier data by the system based on carrier signalling or
11165      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
11166      * user settings, carrier data on/off won't affect user settings but will bypass the
11167      * settings and turns off data internally if set to {@code false}.
11168      *
11169      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11170      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11171      *
11172      * <p>Requires Permission:
11173      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11174      *
11175      * @param enabled control enable or disable carrier data.
11176      * @see #resetAllCarrierActions()
11177      * @hide
11178      */
11179     @SystemApi
11180     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCarrierDataEnabled(boolean enabled)11181     public void setCarrierDataEnabled(boolean enabled) {
11182         try {
11183             ITelephony service = getITelephony();
11184             if (service != null) {
11185                 service.carrierActionSetMeteredApnsEnabled(
11186                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
11187             }
11188         } catch (RemoteException e) {
11189             Log.e(TAG, "Error calling ITelephony#setCarrierDataEnabled", e);
11190         }
11191     }
11192 
11193     /**
11194      * Carrier action to enable or disable the radio.
11195      *
11196      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11197      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11198      *
11199      * <p>Requires Permission:
11200      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11201      *
11202      * @param enabled control enable or disable radio.
11203      * @see #resetAllCarrierActions()
11204      * @hide
11205      */
11206     @SystemApi
11207     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioEnabled(boolean enabled)11208     public void setRadioEnabled(boolean enabled) {
11209         try {
11210             ITelephony service = getITelephony();
11211             if (service != null) {
11212                 service.carrierActionSetRadioEnabled(
11213                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
11214             }
11215         } catch (RemoteException e) {
11216             Log.e(TAG, "Error calling ITelephony#carrierActionSetRadioEnabled", e);
11217         }
11218     }
11219 
11220     /**
11221      * Carrier action to start or stop reporting default network available events.
11222      *
11223      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11224      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11225      *
11226      * <p>Requires Permission:
11227      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11228      *
11229      * @param report control start/stop reporting network status.
11230      * @see #resetAllCarrierActions()
11231      * @hide
11232      */
11233     @SystemApi
11234     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
reportDefaultNetworkStatus(boolean report)11235     public void reportDefaultNetworkStatus(boolean report) {
11236         try {
11237             ITelephony service = getITelephony();
11238             if (service != null) {
11239                 service.carrierActionReportDefaultNetworkStatus(
11240                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
11241             }
11242         } catch (RemoteException e) {
11243             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
11244         }
11245     }
11246 
11247     /**
11248      * Reset all carrier actions previously set by {@link #setRadioEnabled},
11249      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
11250      *
11251      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11252      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11253      *
11254      * <p>Requires Permission:
11255      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11256      * @hide
11257      */
11258     @SystemApi
11259     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetAllCarrierActions()11260     public void resetAllCarrierActions() {
11261         try {
11262             ITelephony service = getITelephony();
11263             if (service != null) {
11264                 service.carrierActionResetAll(
11265                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
11266             }
11267         } catch (RemoteException e) {
11268             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
11269         }
11270     }
11271 
11272     /**
11273      * Policy control of data connection. Usually used when data limit is passed.
11274      * @param enabled True if enabling the data, otherwise disabling.
11275      * @hide
11276      */
11277     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setPolicyDataEnabled(boolean enabled)11278     public void setPolicyDataEnabled(boolean enabled) {
11279         try {
11280             ITelephony service = getITelephony();
11281             if (service != null) {
11282                 service.setPolicyDataEnabled(enabled, getSubId());
11283             }
11284         } catch (RemoteException e) {
11285             Log.e(TAG, "Error calling ITelephony#setPolicyDataEnabled", e);
11286         }
11287     }
11288 
11289     /**
11290      * Get Client request stats which will contain statistical information
11291      * on each request made by client.
11292      * Callers require either READ_PRIVILEGED_PHONE_STATE or
11293      * READ_PHONE_STATE to retrieve the information.
11294      * @param subId sub id
11295      * @return List of Client Request Stats
11296      * @hide
11297      */
getClientRequestStats(int subId)11298     public List<ClientRequestStats> getClientRequestStats(int subId) {
11299         try {
11300             ITelephony service = getITelephony();
11301             if (service != null) {
11302                 return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
11303                         subId);
11304             }
11305         } catch (RemoteException e) {
11306             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
11307         }
11308 
11309         return null;
11310     }
11311 
11312     /**
11313      * Checks if phone is in emergency callback mode.
11314      *
11315      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11316      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11317      *
11318      * @return true if phone is in emergency callback mode.
11319      * @hide
11320      */
11321     @SystemApi
11322     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyCallbackMode()11323     public boolean getEmergencyCallbackMode() {
11324         return getEmergencyCallbackMode(getSubId());
11325     }
11326 
11327     /**
11328      * Check if phone is in emergency callback mode
11329      * @return true if phone is in emergency callback mode
11330      * @param subId the subscription ID that this action applies to.
11331      * @hide
11332      */
getEmergencyCallbackMode(int subId)11333     public boolean getEmergencyCallbackMode(int subId) {
11334         try {
11335             ITelephony telephony = getITelephony();
11336             if (telephony == null) {
11337                 return false;
11338             }
11339             return telephony.getEmergencyCallbackMode(subId);
11340         } catch (RemoteException e) {
11341             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
11342         }
11343         return false;
11344     }
11345 
11346     /**
11347      * Checks if manual network selection is allowed.
11348      *
11349      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
11350      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
11351      * (see {@link #hasCarrierPrivileges})
11352      *
11353      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11354      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
11355      *
11356      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
11357      */
11358     @SuppressAutoDoc // No support carrier privileges (b/72967236).
11359     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRECISE_PHONE_STATE,
11360             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
isManualNetworkSelectionAllowed()11361     public boolean isManualNetworkSelectionAllowed() {
11362         try {
11363             ITelephony telephony = getITelephony();
11364             if (telephony != null) {
11365                 return telephony.isManualNetworkSelectionAllowed(getSubId());
11366             }
11367         } catch (RemoteException e) {
11368             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
11369         }
11370         return true;
11371     }
11372 
11373     /**
11374      * Enable or disable signal strength changes from radio will always be reported in any
11375      * condition (e.g. screen is off). This is only allowed for System caller.
11376      *
11377      * @param isEnabled {@code true} for enabling; {@code false} for disabling.
11378      * @hide
11379      */
11380     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysReportSignalStrength(boolean isEnabled)11381     public void setAlwaysReportSignalStrength(boolean isEnabled) {
11382         try {
11383             ITelephony telephony = getITelephony();
11384             if (telephony != null) {
11385                 telephony.setAlwaysReportSignalStrength(getSubId(), isEnabled);
11386             }
11387         } catch (RemoteException ex) {
11388             Log.e(TAG, "setAlwaysReportSignalStrength RemoteException", ex);
11389             ex.rethrowAsRuntimeException();
11390         }
11391     }
11392 
11393     /**
11394      * Get the most recently available signal strength information.
11395      *
11396      * Get the most recent SignalStrength information reported by the modem. Due
11397      * to power saving this information may not always be current.
11398      * @return the most recent cached signal strength info from the modem
11399      */
11400     @Nullable
getSignalStrength()11401     public SignalStrength getSignalStrength() {
11402         try {
11403             ITelephony service = getITelephony();
11404             if (service != null) {
11405                 return service.getSignalStrength(getSubId());
11406             }
11407         } catch (RemoteException e) {
11408             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
11409         }
11410         return null;
11411     }
11412 
11413     /**
11414      * Checks whether cellular data connection is allowed in the device.
11415      *
11416      * <p>Whether cellular data connection is allowed considers all factors below:
11417      * <UL>
11418      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
11419      *   <LI>Carrier allows data to be on.</LI>
11420      *   <LI>Network policy.</LI>
11421      *   <LI>And possibly others.</LI>
11422      * </UL>
11423      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
11424      * @hide
11425      */
11426     @SystemApi
11427     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataConnectionAllowed()11428     public boolean isDataConnectionAllowed() {
11429         boolean retVal = false;
11430         try {
11431             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
11432             ITelephony telephony = getITelephony();
11433             if (telephony != null)
11434                 retVal = telephony.isDataEnabled(subId);
11435         } catch (RemoteException e) {
11436             Log.e(TAG, "Error isDataConnectionAllowed", e);
11437         }
11438         return retVal;
11439     }
11440 
11441     /**
11442      * @return true if the current device is "data capable" over a radio on the device.
11443      * <p>
11444      * "Data capable" means that this device supports packet-switched
11445      * data connections over the telephony network.
11446      * <p>
11447      * Note: the meaning of this flag is subtly different from the
11448      * PackageManager.FEATURE_TELEPHONY system feature, which is available
11449      * on any device with a telephony radio, even if the device is
11450      * voice-only.
11451      *
11452      * @hide
11453      */
isDataCapable()11454     public boolean isDataCapable() {
11455         if (mContext == null) return true;
11456         return mContext.getResources().getBoolean(
11457                 com.android.internal.R.bool.config_mobile_data_capable);
11458     }
11459 
11460     /**
11461      * In this mode, modem will not send specified indications when screen is off.
11462      * @hide
11463      */
11464     public static final int INDICATION_UPDATE_MODE_NORMAL                   = 1;
11465 
11466     /**
11467      * In this mode, modem will still send specified indications when screen is off.
11468      * @hide
11469      */
11470     public static final int INDICATION_UPDATE_MODE_IGNORE_SCREEN_OFF        = 2;
11471 
11472     /**
11473      * The indication for signal strength update.
11474      * @hide
11475      */
11476     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
11477 
11478     /**
11479      * The indication for full network state update.
11480      * @hide
11481      */
11482     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
11483 
11484     /**
11485      * The indication for data call dormancy changed update.
11486      * @hide
11487      */
11488     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
11489 
11490     /**
11491      * The indication for link capacity estimate update.
11492      * @hide
11493      */
11494     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
11495 
11496     /**
11497      * The indication for physical channel config update.
11498      * @hide
11499      */
11500     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
11501 
11502     /**
11503      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
11504      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
11505      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
11506      *
11507      * <p>Requires Permission:
11508      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11509      *
11510      *
11511      * @deprecated
11512      * @hide
11513      */
11514     @Deprecated
11515     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)11516     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
11517             String gid2, String plmn, String spn) {
11518         try {
11519             ITelephony telephony = getITelephony();
11520             if (telephony != null) {
11521                 telephony.setCarrierTestOverride(
11522                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
11523                         null, null);
11524             }
11525         } catch (RemoteException ex) {
11526             // This could happen if binder process crashes.
11527         }
11528     }
11529 
11530     /**
11531      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
11532      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
11533      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
11534      * a test SIM with a call box.
11535      *
11536      * <p>Requires Permission:
11537      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11538      *
11539      * @hide
11540      */
11541     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)11542     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
11543                                        String gid2, String plmn, String spn,
11544                                        String carrierPriviledgeRules, String apn) {
11545         try {
11546             ITelephony telephony = getITelephony();
11547             if (telephony != null) {
11548                 telephony.setCarrierTestOverride(
11549                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
11550                         carrierPriviledgeRules, apn);
11551             }
11552         } catch (RemoteException ex) {
11553             // This could happen if binder process crashes.
11554         }
11555     }
11556 
11557     /**
11558      * A test API to return installed carrier id list version
11559      *
11560      * <p>Requires Permission:
11561      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11562      *
11563      * @hide
11564      */
11565     @UnsupportedAppUsage
11566     @TestApi
getCarrierIdListVersion()11567     public int getCarrierIdListVersion() {
11568         try {
11569             ITelephony telephony = getITelephony();
11570             if (telephony != null) {
11571                 return telephony.getCarrierIdListVersion(getSubId());
11572             }
11573         } catch (RemoteException ex) {
11574             // This could happen if binder process crashes.
11575         }
11576         return UNKNOWN_CARRIER_ID_LIST_VERSION;
11577     }
11578 
11579     /**
11580      * How many modems can have simultaneous data connections.
11581      * @hide
11582      */
11583     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()11584     public int getNumberOfModemsWithSimultaneousDataConnections() {
11585         try {
11586             ITelephony telephony = getITelephony();
11587             if (telephony != null) {
11588                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
11589                         getSubId(), getOpPackageName(), getAttributionTag());
11590             }
11591         } catch (RemoteException ex) {
11592             // This could happen if binder process crashes.
11593         }
11594         return 0;
11595     }
11596 
11597     /**
11598      * Enable or disable OpportunisticNetworkService.
11599      *
11600      * This method should be called to enable or disable
11601      * OpportunisticNetwork service on the device.
11602      *
11603      * <p>
11604      * Requires Permission:
11605      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11606      *
11607      * @param enable enable(True) or disable(False)
11608      * @return returns true if successfully set.
11609      * @hide
11610      */
11611     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11612     @SystemApi
setOpportunisticNetworkState(boolean enable)11613     public boolean setOpportunisticNetworkState(boolean enable) {
11614         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11615         boolean ret = false;
11616         try {
11617             IOns iOpportunisticNetworkService = getIOns();
11618             if (iOpportunisticNetworkService != null) {
11619                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
11620             }
11621         } catch (RemoteException ex) {
11622             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
11623         }
11624 
11625         return ret;
11626     }
11627 
11628     /**
11629      * is OpportunisticNetworkService enabled
11630      *
11631      * This method should be called to determine if the OpportunisticNetworkService is
11632      * enabled
11633      *
11634      * <p>
11635      * Requires Permission:
11636      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11637      * @hide
11638      */
11639     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11640     @SystemApi
isOpportunisticNetworkEnabled()11641     public boolean isOpportunisticNetworkEnabled() {
11642         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11643         boolean isEnabled = false;
11644 
11645         try {
11646             IOns iOpportunisticNetworkService = getIOns();
11647             if (iOpportunisticNetworkService != null) {
11648                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
11649             }
11650         } catch (RemoteException ex) {
11651             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
11652         }
11653 
11654         return isEnabled;
11655     }
11656 
11657     /** @hide */
11658     @Retention(RetentionPolicy.SOURCE)
11659     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
11660             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
11661                     NETWORK_TYPE_BITMASK_GSM,
11662                     NETWORK_TYPE_BITMASK_GPRS,
11663                     NETWORK_TYPE_BITMASK_EDGE,
11664                     NETWORK_TYPE_BITMASK_CDMA,
11665                     NETWORK_TYPE_BITMASK_1xRTT,
11666                     NETWORK_TYPE_BITMASK_EVDO_0,
11667                     NETWORK_TYPE_BITMASK_EVDO_A,
11668                     NETWORK_TYPE_BITMASK_EVDO_B,
11669                     NETWORK_TYPE_BITMASK_EHRPD,
11670                     NETWORK_TYPE_BITMASK_HSUPA,
11671                     NETWORK_TYPE_BITMASK_HSDPA,
11672                     NETWORK_TYPE_BITMASK_HSPA,
11673                     NETWORK_TYPE_BITMASK_HSPAP,
11674                     NETWORK_TYPE_BITMASK_UMTS,
11675                     NETWORK_TYPE_BITMASK_TD_SCDMA,
11676                     NETWORK_TYPE_BITMASK_LTE,
11677                     NETWORK_TYPE_BITMASK_LTE_CA,
11678                     NETWORK_TYPE_BITMASK_NR,
11679             })
11680     public @interface NetworkTypeBitMask {}
11681 
11682     // 2G
11683     /**
11684      * network type bitmask unknown.
11685      * @hide
11686      */
11687     @SystemApi
11688     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
11689     /**
11690      * network type bitmask indicating the support of radio tech GSM.
11691      * @hide
11692      */
11693     @SystemApi
11694     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
11695     /**
11696      * network type bitmask indicating the support of radio tech GPRS.
11697      * @hide
11698      */
11699     @SystemApi
11700     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
11701     /**
11702      * network type bitmask indicating the support of radio tech EDGE.
11703      * @hide
11704      */
11705     @SystemApi
11706     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
11707     /**
11708      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
11709      * @hide
11710      */
11711     @SystemApi
11712     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
11713     /**
11714      * network type bitmask indicating the support of radio tech 1xRTT.
11715      * @hide
11716      */
11717     @SystemApi
11718     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
11719     // 3G
11720     /**
11721      * network type bitmask indicating the support of radio tech EVDO 0.
11722      * @hide
11723      */
11724     @SystemApi
11725     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
11726     /**
11727      * network type bitmask indicating the support of radio tech EVDO A.
11728      * @hide
11729      */
11730     @SystemApi
11731     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
11732     /**
11733      * network type bitmask indicating the support of radio tech EVDO B.
11734      * @hide
11735      */
11736     @SystemApi
11737     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
11738     /**
11739      * network type bitmask indicating the support of radio tech EHRPD.
11740      * @hide
11741      */
11742     @SystemApi
11743     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
11744     /**
11745      * network type bitmask indicating the support of radio tech HSUPA.
11746      * @hide
11747      */
11748     @SystemApi
11749     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
11750     /**
11751      * network type bitmask indicating the support of radio tech HSDPA.
11752      * @hide
11753      */
11754     @SystemApi
11755     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
11756     /**
11757      * network type bitmask indicating the support of radio tech HSPA.
11758      * @hide
11759      */
11760     @SystemApi
11761     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
11762     /**
11763      * network type bitmask indicating the support of radio tech HSPAP.
11764      * @hide
11765      */
11766     @SystemApi
11767     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
11768     /**
11769      * network type bitmask indicating the support of radio tech UMTS.
11770      * @hide
11771      */
11772     @SystemApi
11773     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
11774     /**
11775      * network type bitmask indicating the support of radio tech TD_SCDMA.
11776      * @hide
11777      */
11778     @SystemApi
11779     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
11780     // 4G
11781     /**
11782      * network type bitmask indicating the support of radio tech LTE.
11783      * @hide
11784      */
11785     @SystemApi
11786     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
11787     /**
11788      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
11789      * @hide
11790      */
11791     @SystemApi
11792     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
11793 
11794     /**
11795      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
11796      * @hide
11797      */
11798     @SystemApi
11799     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
11800 
11801     /**
11802      * network type bitmask indicating the support of radio tech IWLAN.
11803      * @hide
11804      */
11805     @SystemApi
11806     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
11807 
11808     /** @hide */
11809     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
11810                 | NETWORK_TYPE_BITMASK_GPRS
11811                 | NETWORK_TYPE_BITMASK_EDGE
11812                 | NETWORK_TYPE_BITMASK_CDMA
11813                 | NETWORK_TYPE_BITMASK_1xRTT;
11814 
11815     /** @hide */
11816     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
11817             | NETWORK_TYPE_BITMASK_EVDO_A
11818             | NETWORK_TYPE_BITMASK_EVDO_B
11819             | NETWORK_TYPE_BITMASK_EHRPD
11820             | NETWORK_TYPE_BITMASK_HSUPA
11821             | NETWORK_TYPE_BITMASK_HSDPA
11822             | NETWORK_TYPE_BITMASK_HSPA
11823             | NETWORK_TYPE_BITMASK_HSPAP
11824             | NETWORK_TYPE_BITMASK_UMTS
11825             | NETWORK_TYPE_BITMASK_TD_SCDMA;
11826 
11827     /** @hide */
11828     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
11829             | NETWORK_TYPE_BITMASK_LTE_CA
11830             | NETWORK_TYPE_BITMASK_IWLAN;
11831 
11832     /** @hide */
11833     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
11834 
11835     /** @hide */
11836     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
11837             | NETWORK_TYPE_BITMASK_GPRS
11838             | NETWORK_TYPE_BITMASK_EDGE
11839             | NETWORK_TYPE_BITMASK_HSUPA
11840             | NETWORK_TYPE_BITMASK_HSDPA
11841             | NETWORK_TYPE_BITMASK_HSPA
11842             | NETWORK_TYPE_BITMASK_HSPAP
11843             | NETWORK_TYPE_BITMASK_UMTS
11844             | NETWORK_TYPE_BITMASK_TD_SCDMA
11845             | NETWORK_TYPE_BITMASK_LTE
11846             | NETWORK_TYPE_BITMASK_LTE_CA
11847             | NETWORK_TYPE_BITMASK_NR;
11848 
11849     /** @hide */
11850     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
11851             | NETWORK_TYPE_BITMASK_1xRTT
11852             | NETWORK_TYPE_BITMASK_EVDO_0
11853             | NETWORK_TYPE_BITMASK_EVDO_A
11854             | NETWORK_TYPE_BITMASK_EVDO_B
11855             | NETWORK_TYPE_BITMASK_EHRPD;
11856 
11857     /**
11858      * @return Modem supported radio access family bitmask
11859      *
11860      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
11861      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11862      * @hide
11863      */
11864     @SystemApi
11865     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSupportedRadioAccessFamily()11866     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
11867         try {
11868             ITelephony telephony = getITelephony();
11869             if (telephony != null) {
11870                 return (long) telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
11871             } else {
11872                 // This can happen when the ITelephony interface is not up yet.
11873                 return NETWORK_TYPE_BITMASK_UNKNOWN;
11874             }
11875         } catch (RemoteException ex) {
11876             // This shouldn't happen in the normal case
11877             return NETWORK_TYPE_BITMASK_UNKNOWN;
11878         } catch (NullPointerException ex) {
11879             // This could happen before phone restarts due to crashing
11880             return NETWORK_TYPE_BITMASK_UNKNOWN;
11881         }
11882     }
11883 
11884     /**
11885      * Indicates Emergency number database version is invalid.
11886      *
11887      * @hide
11888      */
11889     @TestApi
11890     @SystemApi
11891     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
11892 
11893     /**
11894      * Notify Telephony for OTA emergency number database installation complete.
11895      *
11896      * <p> Requires permission:
11897      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11898      *
11899      * @hide
11900      */
11901     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11902     @SystemApi
notifyOtaEmergencyNumberDbInstalled()11903     public void notifyOtaEmergencyNumberDbInstalled() {
11904         try {
11905             ITelephony telephony = getITelephony();
11906             if (telephony != null) {
11907                 telephony.notifyOtaEmergencyNumberDbInstalled();
11908             } else {
11909                 throw new IllegalStateException("telephony service is null.");
11910             }
11911         } catch (RemoteException ex) {
11912             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
11913             ex.rethrowAsRuntimeException();
11914         }
11915     }
11916 
11917     /**
11918      * Override the file path for OTA emergency number database in a file partition.
11919      *
11920      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
11921      *
11922      * <p> Requires permission:
11923      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
11924      *
11925      * @hide
11926      */
11927     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
11928     @SystemApi
11929     @TestApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)11930     public void updateOtaEmergencyNumberDbFilePath(
11931             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
11932         try {
11933             ITelephony telephony = getITelephony();
11934             if (telephony != null) {
11935                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
11936             } else {
11937                 throw new IllegalStateException("telephony service is null.");
11938             }
11939         } catch (RemoteException ex) {
11940             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
11941             ex.rethrowAsRuntimeException();
11942         }
11943     }
11944 
11945     /**
11946      * Reset the file path to default for OTA emergency number database in a file partition.
11947      *
11948      * <p> Requires permission:
11949      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
11950      *
11951      * @hide
11952      */
11953     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
11954     @SystemApi
11955     @TestApi
resetOtaEmergencyNumberDbFilePath()11956     public void resetOtaEmergencyNumberDbFilePath() {
11957         try {
11958             ITelephony telephony = getITelephony();
11959             if (telephony != null) {
11960                 telephony.resetOtaEmergencyNumberDbFilePath();
11961             } else {
11962                 throw new IllegalStateException("telephony service is null.");
11963             }
11964         } catch (RemoteException ex) {
11965             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
11966             ex.rethrowAsRuntimeException();
11967         }
11968     }
11969 
11970     /**
11971      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
11972      * available on the device.
11973      * <p>
11974      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
11975      *
11976      * @return {@code true} if emergency assistance is available, {@code false} otherwise
11977      *
11978      * @hide
11979      */
11980     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11981     @SystemApi
isEmergencyAssistanceEnabled()11982     public boolean isEmergencyAssistanceEnabled() {
11983         mContext.enforceCallingOrSelfPermission(
11984                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11985                 "isEmergencyAssistanceEnabled");
11986         return EMERGENCY_ASSISTANCE_ENABLED;
11987     }
11988 
11989     /**
11990      * Get the emergency number list based on current locale, sim, default, modem and network.
11991      *
11992      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
11993      * priority sources will be located at the smaller index; the priority order of sources are:
11994      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
11995      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
11996      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
11997      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
11998      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
11999      *
12000      * <p>The subscriptions which the returned list would be based on, are all the active
12001      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12002      *
12003      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
12004      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
12005      *
12006      * @return Map including the keys as the active subscription IDs (Note: if there is no active
12007      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
12008      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
12009      * or throw a SecurityException if the caller does not have the permission.
12010      */
12011     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12012     @NonNull
getEmergencyNumberList()12013     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
12014         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
12015         try {
12016             ITelephony telephony = getITelephony();
12017             if (telephony != null) {
12018                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
12019                         mContext.getAttributionTag());
12020             } else {
12021                 throw new IllegalStateException("telephony service is null.");
12022             }
12023         } catch (RemoteException ex) {
12024             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
12025             ex.rethrowAsRuntimeException();
12026         }
12027         return emergencyNumberList;
12028     }
12029 
12030     /**
12031      * Get the per-category emergency number list based on current locale, sim, default, modem
12032      * and network.
12033      *
12034      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
12035      * priority sources will be located at the smaller index; the priority order of sources are:
12036      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
12037      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
12038      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
12039      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
12040      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
12041      *
12042      * <p>The subscriptions which the returned list would be based on, are all the active
12043      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12044      *
12045      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
12046      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
12047      *
12048      * @param categories the emergency service categories which are the bitwise-OR combination of
12049      * the following constants:
12050      * <ol>
12051      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
12052      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
12053      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
12054      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
12055      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
12056      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
12057      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
12058      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
12059      * </ol>
12060      * @return Map including the keys as the active subscription IDs (Note: if there is no active
12061      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
12062      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
12063      * or throw a SecurityException if the caller does not have the permission.
12064      * @throws IllegalStateException if the Telephony process is not currently available.
12065      */
12066     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12067     @NonNull
getEmergencyNumberList( @mergencyServiceCategories int categories)12068     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
12069             @EmergencyServiceCategories int categories) {
12070         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
12071         try {
12072             ITelephony telephony = getITelephony();
12073             if (telephony != null) {
12074                 emergencyNumberList = telephony.getEmergencyNumberList(
12075                         mContext.getOpPackageName(), mContext.getAttributionTag());
12076                 if (emergencyNumberList != null) {
12077                     for (Integer subscriptionId : emergencyNumberList.keySet()) {
12078                         List<EmergencyNumber> numberList = emergencyNumberList.get(subscriptionId);
12079                         for (EmergencyNumber number : numberList) {
12080                             if (!number.isInEmergencyServiceCategories(categories)) {
12081                                 numberList.remove(number);
12082                             }
12083                         }
12084                     }
12085                 }
12086                 return emergencyNumberList;
12087             } else {
12088                 throw new IllegalStateException("telephony service is null.");
12089             }
12090         } catch (RemoteException ex) {
12091             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
12092             ex.rethrowAsRuntimeException();
12093         }
12094         return emergencyNumberList;
12095     }
12096 
12097     /**
12098      * Identifies if the supplied phone number is an emergency number that matches a known
12099      * emergency number based on current locale, SIM card(s), Android database, modem, network,
12100      * or defaults.
12101      *
12102      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
12103      * numbers are not considered emergency numbers. A dialable phone number consists only
12104      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
12105      *
12106      * <p>The subscriptions which the identification would be based on, are all the active
12107      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12108      *
12109      * @param number - the number to look up
12110      * @return {@code true} if the given number is an emergency number based on current locale,
12111      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
12112      * @throws IllegalStateException if the Telephony process is not currently available.
12113      */
isEmergencyNumber(@onNull String number)12114     public boolean isEmergencyNumber(@NonNull String number) {
12115         try {
12116             ITelephony telephony = getITelephony();
12117             if (telephony != null) {
12118                 return telephony.isEmergencyNumber(number, true);
12119             } else {
12120                 throw new IllegalStateException("telephony service is null.");
12121             }
12122         } catch (RemoteException ex) {
12123             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
12124             ex.rethrowAsRuntimeException();
12125         }
12126         return false;
12127     }
12128 
12129     /**
12130      * Checks if the supplied number is an emergency number based on current locale, sim, default,
12131      * modem and network.
12132      *
12133      * <p> Specifically, this method will return {@code true} if the specified number is an
12134      * emergency number, *or* if the number simply starts with the same digits as any current
12135      * emergency number.
12136      *
12137      * <p>The subscriptions which the identification would be based on, are all the active
12138      * subscriptions, no matter which subscription could be used to create TelephonyManager.
12139      *
12140      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
12141      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12142      *
12143      * @param number - the number to look up
12144      * @return {@code true} if the given number is an emergency number or it simply starts with
12145      * the same digits of any current emergency number based on current locale, sim, modem and
12146      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
12147      * have the required permission/privileges
12148      * @throws IllegalStateException if the Telephony process is not currently available.
12149      * @hide
12150      */
12151     @SystemApi
12152     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isPotentialEmergencyNumber(@onNull String number)12153     public boolean isPotentialEmergencyNumber(@NonNull String number) {
12154         try {
12155             ITelephony telephony = getITelephony();
12156             if (telephony != null) {
12157                 return telephony.isEmergencyNumber(number, false);
12158             } else {
12159                 throw new IllegalStateException("telephony service is null.");
12160             }
12161         } catch (RemoteException ex) {
12162             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
12163             ex.rethrowAsRuntimeException();
12164         }
12165         return false;
12166     }
12167 
12168     /**
12169      * Returns the emergency number database version.
12170      *
12171      * <p>Requires Permission:
12172      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12173      *
12174      * @hide
12175      */
12176     @TestApi
12177     @SystemApi
12178     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyNumberDbVersion()12179     public int getEmergencyNumberDbVersion() {
12180         try {
12181             ITelephony telephony = getITelephony();
12182             if (telephony != null) {
12183                 return telephony.getEmergencyNumberDbVersion(getSubId());
12184             }
12185         } catch (RemoteException ex) {
12186             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
12187             ex.rethrowAsRuntimeException();
12188         }
12189         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
12190     }
12191 
12192     /** @hide */
12193     @Retention(RetentionPolicy.SOURCE)
12194     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
12195             SET_OPPORTUNISTIC_SUB_SUCCESS,
12196             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
12197             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
12198             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
12199             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
12200     public @interface SetOpportunisticSubscriptionResult {}
12201 
12202     /**
12203      * No error. Operation succeeded.
12204      */
12205     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
12206 
12207     /**
12208      * Validation failed when trying to switch to preferred subscription.
12209      */
12210     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
12211 
12212     /**
12213      * The subscription is not valid. It must be an active opportunistic subscription.
12214      */
12215     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
12216 
12217     /**
12218      * The subscription is not valid. It must be an opportunistic subscription.
12219      */
12220     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
12221 
12222     /**
12223      * Subscription service happened remote exception.
12224      */
12225     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
12226 
12227 
12228     /** @hide */
12229     @Retention(RetentionPolicy.SOURCE)
12230     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
12231             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
12232             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
12233             UPDATE_AVAILABLE_NETWORKS_ABORTED,
12234             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
12235             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
12236             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
12237             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
12238             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
12239             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
12240             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
12241             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED})
12242     public @interface UpdateAvailableNetworksResult {}
12243 
12244     /**
12245      * No error. Operation succeeded.
12246      */
12247     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
12248 
12249     /**
12250      * There is a unknown failure happened.
12251      */
12252     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
12253 
12254     /**
12255      * The request is aborted.
12256      */
12257     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
12258 
12259     /**
12260      * The parameter passed in is invalid.
12261      */
12262     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
12263 
12264     /**
12265      * No carrier privilege.
12266      */
12267     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
12268 
12269     /**
12270      * Disable modem fail.
12271      */
12272     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
12273 
12274     /**
12275      * Enable modem fail.
12276      */
12277     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
12278 
12279     /**
12280      * Carrier app does not support multiple available networks.
12281      */
12282     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
12283 
12284     /**
12285      * The subscription is not valid. It must be an opportunistic subscription.
12286      */
12287     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
12288 
12289     /**
12290      * There is no OpportunisticNetworkService.
12291      */
12292     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
12293 
12294     /**
12295      * OpportunisticNetworkService is disabled.
12296      */
12297     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
12298 
12299     /**
12300      * Set preferred opportunistic data subscription id.
12301      *
12302      * Switch internet data to preferred opportunistic data subscription id. This api
12303      * can result in lose of internet connectivity for short period of time while internet data
12304      * is handed over.
12305      * <p>Requires that the calling app has carrier privileges on both primary and
12306      * secondary subscriptions (see
12307      * {@link #hasCarrierPrivileges}), or has permission
12308      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12309      *
12310      * @param subId which opportunistic subscription
12311      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
12312      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
12313      * @param needValidation whether validation is needed before switch happens.
12314      * @param executor The executor of where the callback will execute.
12315      * @param callback Callback will be triggered once it succeeds or failed.
12316      *                 See {@link TelephonyManager.SetOpportunisticSubscriptionResult}
12317      *                 for more details. Pass null if don't care about the result.
12318      */
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)12319     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
12320             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
12321         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12322         try {
12323             IOns iOpportunisticNetworkService = getIOns();
12324             if (iOpportunisticNetworkService == null) {
12325                 if (executor == null || callback == null) {
12326                     return;
12327                 }
12328                 final long identity = Binder.clearCallingIdentity();
12329                 try {
12330                     executor.execute(() -> {
12331                         if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
12332                             callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
12333                         } else {
12334                             callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
12335                         }
12336                     });
12337                 } finally {
12338                     Binder.restoreCallingIdentity(identity);
12339                 }
12340                 return;
12341             }
12342             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
12343                 @Override
12344                 public void onComplete(int result) {
12345                     if (executor == null || callback == null) {
12346                         return;
12347                     }
12348                     final long identity = Binder.clearCallingIdentity();
12349                     try {
12350                         executor.execute(() -> {
12351                             callback.accept(result);
12352                         });
12353                     } finally {
12354                         Binder.restoreCallingIdentity(identity);
12355                     }
12356                 }
12357             };
12358 
12359             iOpportunisticNetworkService
12360                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
12361                             pkgForDebug);
12362         } catch (RemoteException ex) {
12363             Rlog.e(TAG, "setPreferredDataSubscriptionId RemoteException", ex);
12364         }
12365         return;
12366     }
12367 
12368     /**
12369      * Get preferred opportunistic data subscription Id
12370      *
12371      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
12372      * or has either READ_PRIVILEGED_PHONE_STATE
12373      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
12374      * @return subId preferred opportunistic subscription id or
12375      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
12376      * subscription id
12377      *
12378      */
12379     @RequiresPermission(anyOf = {
12380             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
12381             android.Manifest.permission.READ_PHONE_STATE
12382     })
getPreferredOpportunisticDataSubscription()12383     public int getPreferredOpportunisticDataSubscription() {
12384         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12385         String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
12386         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
12387         try {
12388             IOns iOpportunisticNetworkService = getIOns();
12389             if (iOpportunisticNetworkService != null) {
12390                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
12391                         packageName, attributionTag);
12392             }
12393         } catch (RemoteException ex) {
12394             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
12395         }
12396         return subId;
12397     }
12398 
12399     /**
12400      * Update availability of a list of networks in the current location.
12401      *
12402      * This api should be called to inform OpportunisticNetwork Service about the availability
12403      * of a network at the current location. This information will be used by OpportunisticNetwork
12404      * service to enable modem stack and to attach to the network. If an empty list is passed,
12405      * it is assumed that no network is available and will result in disabling the modem stack
12406      * to save power. This api do not switch internet data once network attach is completed.
12407      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
12408      * to switch internet data after network attach is complete.
12409      * Requires that the calling app has carrier privileges on both primary and
12410      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
12411      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12412      * @param availableNetworks is a list of available network information.
12413      * @param executor The executor of where the callback will execute.
12414      * @param callback Callback will be triggered once it succeeds or failed.
12415      *
12416      */
12417     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)12418     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
12419             @Nullable @CallbackExecutor Executor executor,
12420             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
12421         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12422         try {
12423             IOns iOpportunisticNetworkService = getIOns();
12424             if (iOpportunisticNetworkService == null || availableNetworks == null) {
12425                 if (executor == null || callback == null) {
12426                     return;
12427                 }
12428                 if (iOpportunisticNetworkService == null) {
12429                     final long identity = Binder.clearCallingIdentity();
12430                     try {
12431                         executor.execute(() -> {
12432                             if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
12433                                 callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
12434                             } else {
12435                                 callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
12436                             }
12437                         });
12438                     } finally {
12439                         Binder.restoreCallingIdentity(identity);
12440                     }
12441                 } else {
12442                     final long identity = Binder.clearCallingIdentity();
12443                     try {
12444                         executor.execute(() -> {
12445                             callback.accept(UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS);
12446                         });
12447                     } finally {
12448                         Binder.restoreCallingIdentity(identity);
12449                     }
12450                 }
12451                 return;
12452             }
12453             IUpdateAvailableNetworksCallback callbackStub =
12454                     new IUpdateAvailableNetworksCallback.Stub() {
12455                         @Override
12456                         public void onComplete(int result) {
12457                             if (executor == null || callback == null) {
12458                                 return;
12459                             }
12460                             final long identity = Binder.clearCallingIdentity();
12461                             try {
12462                                 executor.execute(() -> {
12463                                     callback.accept(result);
12464                                 });
12465                             } finally {
12466                                 Binder.restoreCallingIdentity(identity);
12467                             }
12468                         }
12469                     };
12470             iOpportunisticNetworkService.updateAvailableNetworks(availableNetworks, callbackStub,
12471                     pkgForDebug);
12472         } catch (RemoteException ex) {
12473             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
12474         }
12475     }
12476 
12477     /**
12478      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
12479      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
12480      * For example, we will disable a modem when user or system believes the corresponding SIM
12481      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
12482      *
12483      * Requires that the calling app has permission
12484      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12485      * @param slotIndex which corresponding modem will operate on.
12486      * @param enable whether to enable or disable the modem stack.
12487      * @return whether the operation is successful.
12488      *
12489      * @hide
12490      */
12491     @SystemApi
12492     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableModemForSlot(int slotIndex, boolean enable)12493     public boolean enableModemForSlot(int slotIndex, boolean enable) {
12494         boolean ret = false;
12495         try {
12496             ITelephony telephony = getITelephony();
12497             if (telephony != null) {
12498                 ret = telephony.enableModemForSlot(slotIndex, enable);
12499             }
12500         } catch (RemoteException ex) {
12501             Log.e(TAG, "enableModem RemoteException", ex);
12502         }
12503         return ret;
12504     }
12505 
12506     /**
12507      * It indicates whether modem is enabled or not per slot.
12508      * It's the corresponding status of TelephonyManager.enableModemForSlot.
12509      *
12510      * <p>Requires Permission:
12511      * READ_PRIVILEGED_PHONE_STATE or
12512      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12513      * @param slotIndex which slot it's checking.
12514      */
12515     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isModemEnabledForSlot(int slotIndex)12516     public boolean isModemEnabledForSlot(int slotIndex) {
12517         try {
12518             ITelephony telephony = getITelephony();
12519             if (telephony != null) {
12520                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
12521                         mContext.getAttributionTag());
12522             }
12523         } catch (RemoteException ex) {
12524             Log.e(TAG, "enableModem RemoteException", ex);
12525         }
12526         return false;
12527     }
12528 
12529     /**
12530      * Broadcast intent action for network country code changes.
12531      *
12532      * <p>
12533      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
12534      * network returned by {@link #getNetworkCountryIso()}.
12535      *
12536      * <p>There may be a delay of several minutes before reporting that no country is detected.
12537      *
12538      * @see #EXTRA_NETWORK_COUNTRY
12539      * @see #getNetworkCountryIso()
12540      */
12541     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
12542             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
12543 
12544     /**
12545      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
12546      * the country code in ISO-3166-1 alpha-2 format.
12547      * <p class="note">
12548      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
12549      */
12550     public static final String EXTRA_NETWORK_COUNTRY =
12551             "android.telephony.extra.NETWORK_COUNTRY";
12552 
12553     /**
12554      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
12555      * last known the country code in ISO-3166-1 alpha-2 format.
12556      * <p class="note">
12557      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
12558      *
12559      * @hide
12560      */
12561     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
12562             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
12563 
12564     /**
12565      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
12566      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
12567      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
12568      * policies of the carrier.
12569      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
12570      * access to the network.
12571      *
12572      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
12573      * otherwise.
12574      *
12575      * @hide
12576      */
12577     @SystemApi
12578     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)12579     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
12580         try {
12581             ITelephony service = getITelephony();
12582             if (service != null) {
12583                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
12584             }
12585         } catch (RemoteException e) {
12586             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
12587         }
12588     }
12589 
12590     /**
12591      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12592      * Standby or Dual Active) is supported.
12593      */
12594     public static final int MULTISIM_ALLOWED = 0;
12595 
12596     /**
12597      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12598      * Standby or Dual Active) is not supported by the hardware.
12599      */
12600     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
12601 
12602     /**
12603      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12604      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
12605      */
12606     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
12607 
12608     /** @hide */
12609     @Retention(RetentionPolicy.SOURCE)
12610     @IntDef(prefix = {"MULTISIM_"},
12611             value = {
12612                     MULTISIM_ALLOWED,
12613                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
12614                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
12615             })
12616     public @interface IsMultiSimSupportedResult {}
12617 
12618     /**
12619      * Returns if the usage of multiple SIM cards at the same time to register on the network
12620      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
12621      *
12622      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12623      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12624      *
12625      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
12626      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
12627      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
12628      * functionality is restricted by the carrier.
12629      */
12630     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12631     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12632     @IsMultiSimSupportedResult
isMultiSimSupported()12633     public int isMultiSimSupported() {
12634         if (getSupportedModemCount() < 2) {
12635             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
12636         }
12637         try {
12638             ITelephony service = getITelephony();
12639             if (service != null) {
12640                 return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
12641             }
12642         } catch (RemoteException e) {
12643             Log.e(TAG, "isMultiSimSupported RemoteException", e);
12644         }
12645         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
12646     }
12647 
12648     /**
12649      * Switch configs to enable multi-sim or switch back to single-sim
12650      * <p>Requires Permission:
12651      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
12652      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12653      *
12654      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
12655      * to single-sim
12656      *
12657      * @param numOfSims number of live SIMs we want to switch to
12658      * @throws android.os.RemoteException
12659      */
12660     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12661     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchMultiSimConfig(int numOfSims)12662     public void switchMultiSimConfig(int numOfSims) {
12663         try {
12664             ITelephony telephony = getITelephony();
12665             if (telephony != null) {
12666                 telephony.switchMultiSimConfig(numOfSims);
12667             }
12668         } catch (RemoteException ex) {
12669             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
12670         }
12671     }
12672 
12673     /**
12674      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
12675      * trigger device reboot.
12676      * The modem configuration change refers to switching from single SIM configuration to DSDS
12677      * or the other way around.
12678      *
12679      *  <p>Requires Permission:
12680      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
12681      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12682      *
12683      * @return {@code true} if reboot will be triggered after making changes to modem
12684      * configurations, otherwise return {@code false}.
12685      */
12686     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
doesSwitchMultiSimConfigTriggerReboot()12687     public boolean doesSwitchMultiSimConfigTriggerReboot() {
12688         try {
12689             ITelephony service = getITelephony();
12690             if (service != null) {
12691                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
12692                         getOpPackageName(), getAttributionTag());
12693             }
12694         } catch (RemoteException e) {
12695             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
12696         }
12697         return false;
12698     }
12699 
12700     /**
12701      * Retrieve the Radio HAL Version for this device.
12702      *
12703      * Get the HAL version for the IRadio interface for test purposes.
12704      *
12705      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
12706      *
12707      * @hide
12708      */
12709     @UnsupportedAppUsage
12710     @TestApi
getRadioHalVersion()12711     public Pair<Integer, Integer> getRadioHalVersion() {
12712         try {
12713             ITelephony service = getITelephony();
12714             if (service != null) {
12715                 int version = service.getRadioHalVersion();
12716                 if (version == -1) return new Pair<Integer, Integer>(-1, -1);
12717                 return new Pair<Integer, Integer>(version / 100, version % 100);
12718             }
12719         } catch (RemoteException e) {
12720             Log.e(TAG, "getRadioHalVersion() RemoteException", e);
12721         }
12722         return new Pair<Integer, Integer>(-1, -1);
12723     }
12724 
12725     /**
12726      * Get the calling application status about carrier privileges for the subscription created
12727      * in TelephonyManager. Used by Telephony Module for permission checking.
12728      *
12729      * @param uid Uid to check.
12730      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
12731      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
12732      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
12733      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
12734      *
12735      * @hide
12736      */
12737     @SystemApi
12738     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierPrivilegeStatus(int uid)12739     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
12740         try {
12741             ITelephony telephony = getITelephony();
12742             if (telephony != null) {
12743                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
12744             }
12745         } catch (RemoteException ex) {
12746             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
12747         }
12748         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
12749     }
12750 
12751     /**
12752      * Returns a list of APNs set as overrides by the device policy manager via
12753      * {@link #addDevicePolicyOverrideApn}.
12754      * This method must only be called from the system or phone processes.
12755      *
12756      * @param context Context to use.
12757      * @return {@link List} of APNs that have been set as overrides.
12758      * @throws {@link SecurityException} if the caller is not the system or phone process.
12759      * @hide
12760      */
12761     @TestApi
12762     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)12763     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
12764         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
12765             if (cursor == null) {
12766                 return Collections.emptyList();
12767             }
12768             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
12769             cursor.moveToPosition(-1);
12770             while (cursor.moveToNext()) {
12771                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
12772                 apnList.add(apn);
12773             }
12774             return apnList;
12775         }
12776     }
12777 
12778     /**
12779      * Used by the device policy manager to add a new override APN.
12780      * This method must only be called from the system or phone processes.
12781      *
12782      * @param context Context to use.
12783      * @param apnSetting The {@link ApnSetting} describing the new APN.
12784      * @return An integer, corresponding to a primary key in a database, that allows the caller to
12785      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
12786      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
12787      *         failed.
12788      * @throws {@link SecurityException} if the caller is not the system or phone process.
12789      * @hide
12790      */
12791     @TestApi
12792     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)12793     public int addDevicePolicyOverrideApn(@NonNull Context context,
12794             @NonNull ApnSetting apnSetting) {
12795         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
12796 
12797         int resultId = INVALID_APN_ID;
12798         if (resultUri != null) {
12799             try {
12800                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
12801             } catch (NumberFormatException e) {
12802                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
12803                         + resultUri.getLastPathSegment());
12804             }
12805         }
12806         return resultId;
12807     }
12808 
12809     /**
12810      * Used by the device policy manager to modify an override APN.
12811      * This method must only be called from the system or phone processes.
12812      *
12813      * @param context Context to use.
12814      * @param apnId The integer key of the APN to modify, as returned by
12815      *              {@link #addDevicePolicyOverrideApn}
12816      * @param apnSetting The {@link ApnSetting} describing the updated APN.
12817      * @return {@code true} if successful, {@code false} otherwise.
12818      * @throws {@link SecurityException} if the caller is not the system or phone process.
12819      * @hide
12820      */
12821     @TestApi
12822     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)12823     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
12824             @NonNull ApnSetting apnSetting) {
12825         return context.getContentResolver().update(
12826                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
12827                 apnSetting.toContentValues(), null, null) > 0;
12828     }
12829 
12830     /**
12831      * Return whether data is enabled for certain APN type. This will tell if framework will accept
12832      * corresponding network requests on a subId.
12833      *
12834      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
12835      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
12836      *
12837      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
12838      * It will return true if:
12839      *
12840      *  1) User data is turned on, or
12841      *  2) APN is un-metered for this subscription, or
12842      *  3) APN type is whitelisted. E.g. MMS is whitelisted if
12843      *  {@link #setAlwaysAllowMmsData(boolean)} is turned on.
12844      *
12845      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
12846      * @return whether data is enabled for a apn type.
12847      *
12848      * @hide
12849      */
12850     @SystemApi
12851     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataEnabledForApn(@pnType int apnType)12852     public boolean isDataEnabledForApn(@ApnType int apnType) {
12853         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12854         try {
12855             ITelephony service = getITelephony();
12856             if (service != null) {
12857                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
12858             }
12859         } catch (RemoteException ex) {
12860             if (!isSystemProcess()) {
12861                 ex.rethrowAsRuntimeException();
12862             }
12863         }
12864         return false;
12865     }
12866 
12867     /**
12868      * Whether an APN type is metered or not. It will be evaluated with the subId associated
12869      * with the TelephonyManager instance.
12870      *
12871      * @hide
12872      */
12873     @SystemApi
12874     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApnMetered(@pnType int apnType)12875     public boolean isApnMetered(@ApnType int apnType) {
12876         try {
12877             ITelephony service = getITelephony();
12878             if (service != null) {
12879                 return service.isApnMetered(apnType, getSubId());
12880             }
12881         } catch (RemoteException ex) {
12882             if (!isSystemProcess()) {
12883                 ex.rethrowAsRuntimeException();
12884             }
12885         }
12886         return true;
12887     }
12888 
12889     /**
12890      * Specify which bands modem's background scan must act on.
12891      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
12892      * Otherwise, it scans all bands.
12893      *
12894      * For example, CBRS is only on LTE band 48. By specifying this band,
12895      * modem saves more power.
12896      *
12897      * @param specifiers which bands to scan.
12898      * @param executor The executor to execute the callback on
12899      * @param callback The callback that gets invoked when the radio responds to the request. Called
12900      *                 with {@code true} if the request succeeded, {@code false} otherwise.
12901      * @hide
12902      */
12903     @SystemApi
12904     @TestApi
12905     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)12906     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
12907             @NonNull @CallbackExecutor Executor executor,
12908             @NonNull Consumer<Boolean> callback) {
12909         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
12910         Objects.requireNonNull(executor, "Executor must not be null.");
12911         Objects.requireNonNull(callback, "Callback must not be null.");
12912         setSystemSelectionChannelsInternal(specifiers, executor, callback);
12913     }
12914 
12915     /**
12916      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
12917      * used when the caller does not need feedback on the results of the operation.
12918      * @param specifiers which bands to scan.
12919      * @hide
12920      */
12921     @SystemApi
12922     @TestApi
12923     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)12924     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
12925         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
12926         setSystemSelectionChannelsInternal(specifiers, null, null);
12927     }
12928 
12929 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)12930     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
12931             @Nullable @CallbackExecutor Executor executor,
12932             @Nullable Consumer<Boolean> callback) {
12933         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
12934             @Override
12935             public void accept(boolean result) {
12936                 executor.execute(() -> callback.accept(result));
12937             }
12938         };
12939 
12940         try {
12941             ITelephony service = getITelephony();
12942             if (service != null) {
12943                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
12944             }
12945         } catch (RemoteException ex) {
12946             if (!isSystemProcess()) {
12947                 ex.rethrowAsRuntimeException();
12948             }
12949         }
12950     }
12951 
12952     /**
12953      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
12954      *
12955      * @param mccmnc the carrier's mccmnc that you want to match
12956      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
12957      * @param mvnoMatchData the MVNO match data
12958      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
12959      * {@code false} otherwise.
12960      *
12961      * {@hide}
12962      */
12963     @SystemApi
12964     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
matchesCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)12965     public boolean matchesCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
12966             @Nullable String mvnoMatchData) {
12967         try {
12968             if (!mccmnc.equals(getSimOperator())) {
12969                 return false;
12970             }
12971             ITelephony service = getITelephony();
12972             if (service != null) {
12973                 return service.isMvnoMatched(getSubId(), mvnoType, mvnoMatchData);
12974             }
12975         } catch (RemoteException ex) {
12976             if (!isSystemProcess()) {
12977                 ex.rethrowAsRuntimeException();
12978             }
12979         }
12980         return false;
12981     }
12982 
12983     /**
12984      * Gets the voice call forwarding info {@link CallForwardingInfo}, given the call forward
12985      * reason.
12986      *
12987      * @param callForwardingReason the call forwarding reasons
12988      *
12989      * @throws IllegalArgumentException if callForwardingReason is not any of
12990      * {@link CallForwardingInfo.REASON_UNCONDITIONAL}, {@link CallForwardingInfo.REASON_BUSY},
12991      * {@link CallForwardingInfo.REASON_NO_REPLY}, {@link CallForwardingInfo.REASON_NOT_REACHABLE},
12992      * {@link CallForwardingInfo.REASON_ALL}, {@link CallForwardingInfo.REASON_ALL_CONDITIONAL}
12993      *
12994      * @return {@link CallForwardingInfo} with the status {@link CallForwardingInfo#STATUS_ACTIVE}
12995      * or {@link CallForwardingInfo#STATUS_INACTIVE} and the target phone number to forward calls
12996      * to, if it's available. Otherwise, it will return a {@link CallForwardingInfo} with status
12997      * {@link CallForwardingInfo#STATUS_UNKNOWN_ERROR},
12998      * {@link CallForwardingInfo#STATUS_NOT_SUPPORTED},
12999      * or {@link CallForwardingInfo#STATUS_FDN_CHECK_FAILURE} depending on the situation.
13000      *
13001      * @hide
13002      */
13003     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13004     @NonNull
getCallForwarding(@allForwardingReason int callForwardingReason)13005     public CallForwardingInfo getCallForwarding(@CallForwardingReason int callForwardingReason) {
13006         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
13007                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
13008             throw new IllegalArgumentException("callForwardingReason is out of range");
13009         }
13010         try {
13011             ITelephony telephony = getITelephony();
13012             if (telephony != null) {
13013                 return telephony.getCallForwarding(getSubId(), callForwardingReason);
13014             }
13015         } catch (RemoteException ex) {
13016             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
13017         } catch (NullPointerException ex) {
13018             Rlog.e(TAG, "getCallForwarding NPE", ex);
13019         }
13020         return new CallForwardingInfo(
13021                 CallForwardingInfo.STATUS_UNKNOWN_ERROR, 0 /* reason */, null /* number */,
13022                         0 /* timeout */);
13023     }
13024 
13025     /**
13026      * Sets the voice call forwarding info including status (enable/disable), call forwarding
13027      * reason, the number to forward, and the timeout before the forwarding is attempted.
13028      *
13029      * @param callForwardingInfo {@link CallForwardingInfo} to setup the call forwarding.
13030      * Enabling if {@link CallForwardingInfo#getStatus()} returns
13031      * {@link CallForwardingInfo#STATUS_ACTIVE}; Disabling if
13032      * {@link CallForwardingInfo#getStatus()} returns {@link CallForwardingInfo#STATUS_INACTIVE}.
13033      *
13034      * @throws IllegalArgumentException if any of the following for parameter callForwardingInfo:
13035      * 0) it is {@code null}.
13036      * 1) {@link CallForwardingInfo#getStatus()} returns neither
13037      * {@link CallForwardingInfo#STATUS_ACTIVE} nor {@link CallForwardingInfo#STATUS_INACTIVE}.
13038      * 2) {@link CallForwardingInfo#getReason()} is not any of
13039      * {@link CallForwardingInfo.REASON_UNCONDITIONAL}, {@link CallForwardingInfo.REASON_BUSY},
13040      * {@link CallForwardingInfo.REASON_NO_REPLY}, {@link CallForwardingInfo.REASON_NOT_REACHABLE},
13041      * {@link CallForwardingInfo.REASON_ALL}, {@link CallForwardingInfo.REASON_ALL_CONDITIONAL}
13042      * 3) {@link CallForwardingInfo#getNumber()} returns {@code null}.
13043      * 4) {@link CallForwardingInfo#getTimeoutSeconds()} doesn't return a positive value.
13044      *
13045      * @return {@code true} to indicate it was set successfully; {@code false} otherwise.
13046      *
13047      * @hide
13048      */
13049     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo)13050     public boolean setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo) {
13051         if (callForwardingInfo == null) {
13052             throw new IllegalArgumentException("callForwardingInfo is null");
13053         }
13054         int callForwardingStatus = callForwardingInfo.getStatus();
13055         if (callForwardingStatus != CallForwardingInfo.STATUS_ACTIVE
13056                 && callForwardingStatus != CallForwardingInfo.STATUS_INACTIVE) {
13057             throw new IllegalArgumentException(
13058                     "callForwardingStatus is neither active nor inactive");
13059         }
13060         int callForwardingReason = callForwardingInfo.getReason();
13061         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
13062                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
13063             throw new IllegalArgumentException("callForwardingReason is out of range");
13064         }
13065         if (callForwardingInfo.getNumber() == null) {
13066             throw new IllegalArgumentException("callForwarding number is null");
13067         }
13068         if (callForwardingInfo.getTimeoutSeconds() <= 0) {
13069             throw new IllegalArgumentException("callForwarding timeout isn't positive");
13070         }
13071         try {
13072             ITelephony telephony = getITelephony();
13073             if (telephony != null) {
13074                 return telephony.setCallForwarding(getSubId(), callForwardingInfo);
13075             }
13076         } catch (RemoteException ex) {
13077             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
13078         } catch (NullPointerException ex) {
13079             Rlog.e(TAG, "setCallForwarding NPE", ex);
13080         }
13081         return false;
13082     }
13083 
13084     /**
13085      * Indicates the call waiting status is active.
13086      *
13087      * @hide
13088      */
13089     public static final int CALL_WAITING_STATUS_ACTIVE = 1;
13090 
13091     /**
13092      * Indicates the call waiting status is inactive.
13093      *
13094      * @hide
13095      */
13096     public static final int CALL_WAITING_STATUS_INACTIVE = 2;
13097 
13098     /**
13099      * Indicates the call waiting status is with an unknown error.
13100      *
13101      * @hide
13102      */
13103     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
13104 
13105     /**
13106      * Indicates the call waiting is not supported (e.g. called via CDMA).
13107      *
13108      * @hide
13109      */
13110     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
13111 
13112     /**
13113      * Call waiting function status
13114      *
13115      * @hide
13116      */
13117     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
13118         CALL_WAITING_STATUS_ACTIVE,
13119         CALL_WAITING_STATUS_INACTIVE,
13120         CALL_WAITING_STATUS_NOT_SUPPORTED,
13121         CALL_WAITING_STATUS_UNKNOWN_ERROR
13122     })
13123     @Retention(RetentionPolicy.SOURCE)
13124     public @interface CallWaitingStatus {
13125     }
13126 
13127     /**
13128      * Gets the status of voice call waiting function. Call waiting function enables the waiting
13129      * for the incoming call when it reaches the user who is busy to make another call and allows
13130      * users to decide whether to switch to the incoming call.
13131      *
13132      * @return the status of call waiting function.
13133      * @hide
13134      */
13135     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCallWaitingStatus()13136     public @CallWaitingStatus int getCallWaitingStatus() {
13137         try {
13138             ITelephony telephony = getITelephony();
13139             if (telephony != null) {
13140                 return telephony.getCallWaitingStatus(getSubId());
13141             }
13142         } catch (RemoteException ex) {
13143             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
13144         } catch (NullPointerException ex) {
13145             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
13146         }
13147         return CALL_WAITING_STATUS_UNKNOWN_ERROR;
13148     }
13149 
13150     /**
13151      * Sets the status for voice call waiting function. Call waiting function enables the waiting
13152      * for the incoming call when it reaches the user who is busy to make another call and allows
13153      * users to decide whether to switch to the incoming call.
13154      *
13155      * @param isEnable {@code true} to enable; {@code false} to disable.
13156      * @return {@code true} to indicate it was set successfully; {@code false} otherwise.
13157      *
13158      * @hide
13159      */
13160     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallWaitingStatus(boolean isEnable)13161     public boolean setCallWaitingStatus(boolean isEnable) {
13162         try {
13163             ITelephony telephony = getITelephony();
13164             if (telephony != null) {
13165                 return telephony.setCallWaitingStatus(getSubId(), isEnable);
13166             }
13167         } catch (RemoteException ex) {
13168             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
13169         } catch (NullPointerException ex) {
13170             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
13171         }
13172         return false;
13173     }
13174 
13175     /**
13176      * Set allowing mobile data during voice call. This is used for allowing data on the non-default
13177      * data SIM. When a voice call is placed on the non-default data SIM on DSDS devices, users will
13178      * not be able to use mobile data. By calling this API, data will be temporarily enabled on the
13179      * non-default data SIM during the life cycle of the voice call.
13180      *
13181      * @param allow {@code true} if allowing using data during voice call, {@code false} if
13182      * disallowed.
13183      *
13184      * @return {@code true} if operation is successful. otherwise {@code false}.
13185      *
13186      * @throws SecurityException if the caller doesn't have the permission.
13187      *
13188      * @hide
13189      */
13190     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataAllowedDuringVoiceCall(boolean allow)13191     public boolean setDataAllowedDuringVoiceCall(boolean allow) {
13192         try {
13193             ITelephony service = getITelephony();
13194             if (service != null) {
13195                 return service.setDataAllowedDuringVoiceCall(getSubId(), allow);
13196             }
13197         } catch (RemoteException ex) {
13198             // This could happen if binder process crashes.
13199             if (!isSystemProcess()) {
13200                 ex.rethrowAsRuntimeException();
13201             }
13202         }
13203         return false;
13204     }
13205 
13206     /**
13207      * Check whether data is allowed during voice call. This is used for allowing data on the
13208      * non-default data SIM. When a voice call is placed on the non-default data SIM on DSDS
13209      * devices, users will not be able to use mobile data. By calling this API, data will be
13210      * temporarily enabled on the non-default data SIM during the life cycle of the voice call.
13211      *
13212      * @return {@code true} if data is allowed during voice call.
13213      *
13214      * @throws SecurityException if the caller doesn't have the permission.
13215      *
13216      * @hide
13217      */
13218     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataAllowedInVoiceCall()13219     public boolean isDataAllowedInVoiceCall() {
13220         try {
13221             ITelephony service = getITelephony();
13222             if (service != null) {
13223                 return service.isDataAllowedInVoiceCall(getSubId());
13224             }
13225         } catch (RemoteException ex) {
13226             // This could happen if binder process crashes.
13227             if (!isSystemProcess()) {
13228                 ex.rethrowAsRuntimeException();
13229             }
13230         }
13231         return false;
13232     }
13233 
13234     /**
13235      * Set whether the specific sim card always allows MMS connection. If true, MMS network
13236      * request will be accepted by telephony even if user turns "mobile data" off
13237      * on this specific sim card.
13238      *
13239      * @param alwaysAllow whether Mms data is always allowed.
13240      * @return whether operation is successful.
13241      *
13242      * @hide
13243      */
13244     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysAllowMmsData(boolean alwaysAllow)13245     public boolean setAlwaysAllowMmsData(boolean alwaysAllow) {
13246         try {
13247             ITelephony service = getITelephony();
13248             if (service != null) {
13249                 return service.setAlwaysAllowMmsData(getSubId(), alwaysAllow);
13250             }
13251         } catch (RemoteException ex) {
13252             if (!isSystemProcess()) {
13253                 ex.rethrowAsRuntimeException();
13254             }
13255         }
13256         return false;
13257     }
13258 
13259     /**
13260      * The IccLock state or password was changed successfully.
13261      * @hide
13262      */
13263     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
13264 
13265     /**
13266      * Check whether ICC pin lock is enabled.
13267      * This is a sync call which returns the cached pin enabled state.
13268      *
13269      * @return {@code true} if ICC lock enabled, {@code false} if ICC lock disabled.
13270      *
13271      * @throws SecurityException if the caller doesn't have the permission.
13272      *
13273      * @hide
13274      */
13275     @WorkerThread
13276     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13277     @SystemApi
isIccLockEnabled()13278     public boolean isIccLockEnabled() {
13279         try {
13280             ITelephony telephony = getITelephony();
13281             if (telephony != null) {
13282                 return telephony.isIccLockEnabled(getSubId());
13283             }
13284         } catch (RemoteException e) {
13285             Log.e(TAG, "isIccLockEnabled RemoteException", e);
13286         }
13287         return false;
13288     }
13289 
13290     /**
13291      * Set the ICC pin lock enabled or disabled.
13292      *
13293      * If enable/disable ICC pin lock successfully, a value of {@link Integer#MAX_VALUE} is
13294      * returned.
13295      * If an incorrect old password is specified, the return value will indicate how many more
13296      * attempts the user can make to change the password before the SIM is locked.
13297      * Using PUK code to unlock SIM if enter the incorrect old password 3 times.
13298      *
13299      * @param enabled    "true" for locked, "false" for unlocked.
13300      * @param password   needed to change the ICC pin state, aka. Pin1
13301      * @return an integer representing the status of IccLock enabled or disabled in the following
13302      * three cases:
13303      *   - {@link TelephonyManager#CHANGE_ICC_LOCK_SUCCESS} if enabled or disabled IccLock
13304      *   successfully.
13305      *   - Positive number and zero for remaining password attempts.
13306      *   - Negative number for other failure cases (such like enabling/disabling PIN failed).
13307      *
13308      * @throws SecurityException if the caller doesn't have the permission.
13309      *
13310      * @hide
13311      */
13312     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setIccLockEnabled(boolean enabled, @NonNull String password)13313     public int setIccLockEnabled(boolean enabled, @NonNull String password) {
13314         checkNotNull(password, "setIccLockEnabled password can't be null.");
13315         try {
13316             ITelephony telephony = getITelephony();
13317             if (telephony != null) {
13318                 return telephony.setIccLockEnabled(getSubId(), enabled, password);
13319             }
13320         } catch (RemoteException e) {
13321             Log.e(TAG, "setIccLockEnabled RemoteException", e);
13322         }
13323         return 0;
13324     }
13325 
13326     /**
13327      * Change the ICC password used in ICC pin lock.
13328      *
13329      * If the password was changed successfully, a value of {@link Integer#MAX_VALUE} is returned.
13330      * If an incorrect old password is specified, the return value will indicate how many more
13331      * attempts the user can make to change the password before the SIM is locked.
13332      * Using PUK code to unlock SIM if enter the incorrect old password 3 times.
13333      *
13334      * @param oldPassword is the old password
13335      * @param newPassword is the new password
13336      * @return an integer representing the status of IccLock changed in the following three cases:
13337      *   - {@link TelephonyManager#CHANGE_ICC_LOCK_SUCCESS} if changed IccLock successfully.
13338      *   - Positive number and zero for remaining password attempts.
13339      *   - Negative number for other failure cases (such like enabling/disabling PIN failed).
13340      *
13341      * @throws SecurityException if the caller doesn't have the permission.
13342      *
13343      * @hide
13344      */
13345     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
changeIccLockPassword(@onNull String oldPassword, @NonNull String newPassword)13346     public int changeIccLockPassword(@NonNull String oldPassword, @NonNull String newPassword) {
13347         checkNotNull(oldPassword, "changeIccLockPassword oldPassword can't be null.");
13348         checkNotNull(newPassword, "changeIccLockPassword newPassword can't be null.");
13349         try {
13350             ITelephony telephony = getITelephony();
13351             if (telephony != null) {
13352                 return telephony.changeIccLockPassword(getSubId(), oldPassword, newPassword);
13353             }
13354         } catch (RemoteException e) {
13355             Log.e(TAG, "changeIccLockPassword RemoteException", e);
13356         }
13357         return 0;
13358     }
13359 
13360     /**
13361      * Called when userActivity is signalled in the power manager.
13362      * This should only be called from system Uid.
13363      * @hide
13364      */
13365     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
notifyUserActivity()13366     public void notifyUserActivity() {
13367         try {
13368             ITelephony service = getITelephony();
13369             if (service != null) {
13370                 service.userActivity();
13371             }
13372         } catch (RemoteException e) {
13373             // one-way notification, if telephony is not available, it is okay to not throw
13374             // exception here.
13375             Log.w(TAG, "notifyUserActivity exception: " + e.getMessage());
13376         }
13377     }
13378 
13379     private static class DeathRecipient implements IBinder.DeathRecipient {
13380         @Override
binderDied()13381         public void binderDied() {
13382             resetServiceCache();
13383         }
13384     }
13385 
13386    /**
13387     * Reset everything in the service cache; if one handle died then they are
13388     * all probably broken.
13389     * @hide
13390     */
resetServiceCache()13391     private static void resetServiceCache() {
13392         synchronized (sCacheLock) {
13393             if (sISub != null) {
13394                 sISub.asBinder().unlinkToDeath(sServiceDeath, 0);
13395                 sISub = null;
13396                 SubscriptionManager.clearCaches();
13397             }
13398             if (sISms != null) {
13399                 sISms.asBinder().unlinkToDeath(sServiceDeath, 0);
13400                 sISms = null;
13401             }
13402             if (sIPhoneSubInfo != null) {
13403                 sIPhoneSubInfo.asBinder().unlinkToDeath(sServiceDeath, 0);
13404                 sIPhoneSubInfo = null;
13405             }
13406         }
13407     }
13408 
13409    /**
13410     * @hide
13411     */
getSubscriberInfoService()13412     static IPhoneSubInfo getSubscriberInfoService() {
13413         // Keeps cache disabled until test fixes are checked into AOSP.
13414         if (!sServiceHandleCacheEnabled) {
13415             return IPhoneSubInfo.Stub.asInterface(
13416                 TelephonyFrameworkInitializer
13417                         .getTelephonyServiceManager()
13418                         .getPhoneSubServiceRegisterer()
13419                         .get());
13420         }
13421 
13422         if (sIPhoneSubInfo == null) {
13423             IPhoneSubInfo temp = IPhoneSubInfo.Stub.asInterface(
13424                     TelephonyFrameworkInitializer
13425                         .getTelephonyServiceManager()
13426                         .getPhoneSubServiceRegisterer()
13427                         .get());
13428             synchronized (sCacheLock) {
13429                 if (sIPhoneSubInfo == null && temp != null) {
13430                     try {
13431                         sIPhoneSubInfo = temp;
13432                         sIPhoneSubInfo.asBinder().linkToDeath(sServiceDeath, 0);
13433                     } catch (Exception e) {
13434                         // something has gone horribly wrong
13435                         sIPhoneSubInfo = null;
13436                     }
13437                 }
13438             }
13439         }
13440         return sIPhoneSubInfo;
13441     }
13442 
13443    /**
13444     * @hide
13445     */
getSubscriptionService()13446     static ISub getSubscriptionService() {
13447         // Keeps cache disabled until test fixes are checked into AOSP.
13448         if (!sServiceHandleCacheEnabled) {
13449             return ISub.Stub.asInterface(
13450                     TelephonyFrameworkInitializer
13451                             .getTelephonyServiceManager()
13452                             .getSubscriptionServiceRegisterer()
13453                             .get());
13454         }
13455 
13456         if (sISub == null) {
13457             ISub temp = ISub.Stub.asInterface(
13458                     TelephonyFrameworkInitializer
13459                             .getTelephonyServiceManager()
13460                             .getSubscriptionServiceRegisterer()
13461                             .get());
13462             synchronized (sCacheLock) {
13463                 if (sISub == null && temp != null) {
13464                     try {
13465                         sISub = temp;
13466                         sISub.asBinder().linkToDeath(sServiceDeath, 0);
13467                     } catch (Exception e) {
13468                         // something has gone horribly wrong
13469                         sISub = null;
13470                     }
13471                 }
13472             }
13473         }
13474         return sISub;
13475     }
13476 
13477     /**
13478     * @hide
13479     */
getSmsService()13480     static ISms getSmsService() {
13481         // Keeps cache disabled until test fixes are checked into AOSP.
13482         if (!sServiceHandleCacheEnabled) {
13483             return ISms.Stub.asInterface(
13484                     TelephonyFrameworkInitializer
13485                             .getTelephonyServiceManager()
13486                             .getSmsServiceRegisterer()
13487                             .get());
13488         }
13489 
13490         if (sISms == null) {
13491             ISms temp = ISms.Stub.asInterface(
13492                     TelephonyFrameworkInitializer
13493                             .getTelephonyServiceManager()
13494                             .getSmsServiceRegisterer()
13495                             .get());
13496             synchronized (sCacheLock) {
13497                 if (sISms == null && temp != null) {
13498                     try {
13499                         sISms = temp;
13500                         sISms.asBinder().linkToDeath(sServiceDeath, 0);
13501                     } catch (Exception e) {
13502                         // something has gone horribly wrong
13503                         sISms = null;
13504                     }
13505                 }
13506             }
13507         }
13508         return sISms;
13509     }
13510 
13511     /**
13512      * Disables service handle caching for tests that utilize mock services.
13513      * @hide
13514      */
13515     @VisibleForTesting
disableServiceHandleCaching()13516     public static void disableServiceHandleCaching() {
13517         sServiceHandleCacheEnabled = false;
13518     }
13519 
13520     /**
13521      * Reenables service handle caching.
13522      * @hide
13523      */
13524     @VisibleForTesting
enableServiceHandleCaching()13525     public static void enableServiceHandleCaching() {
13526         sServiceHandleCacheEnabled = true;
13527     }
13528 
13529     /**
13530      * Whether device can connect to 5G network when two SIMs are active.
13531      * @hide
13532      * TODO b/153669716: remove or make system API.
13533      */
canConnectTo5GInDsdsMode()13534     public boolean canConnectTo5GInDsdsMode() {
13535         ITelephony telephony = getITelephony();
13536         if (telephony == null) return true;
13537         try {
13538             return telephony.canConnectTo5GInDsdsMode();
13539         } catch (RemoteException ex) {
13540             return true;
13541         } catch (NullPointerException ex) {
13542             return true;
13543         }
13544     }
13545 }
13546