OSDN Git Service

Verify all possible hosts that match web nav
[android-x86/frameworks-base.git] / telephony / java / android / telephony / TelephonyManager.java
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 com.android.internal.util.Preconditions.checkNotNull;
20
21 import android.annotation.IntDef;
22 import android.annotation.Nullable;
23 import android.annotation.RequiresPermission;
24 import android.annotation.SdkConstant;
25 import android.annotation.SuppressLint;
26 import android.annotation.SdkConstant.SdkConstantType;
27 import android.annotation.SystemApi;
28 import android.annotation.SystemService;
29 import android.annotation.WorkerThread;
30 import android.app.ActivityThread;
31 import android.app.PendingIntent;
32 import android.content.ContentResolver;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.net.ConnectivityManager;
36 import android.net.NetworkStats;
37 import android.net.Uri;
38 import android.os.BatteryStats;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.PersistableBundle;
42 import android.os.RemoteException;
43 import android.os.ResultReceiver;
44 import android.os.ServiceManager;
45 import android.os.SystemProperties;
46 import android.provider.Settings;
47 import android.provider.Settings.SettingNotFoundException;
48 import android.service.carrier.CarrierIdentifier;
49 import android.telecom.PhoneAccount;
50 import android.telecom.PhoneAccountHandle;
51 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
52 import android.telephony.ims.feature.ImsFeature;
53 import android.util.Log;
54
55 import com.android.ims.internal.IImsServiceController;
56 import com.android.ims.internal.IImsServiceFeatureListener;
57 import com.android.internal.annotations.VisibleForTesting;
58 import com.android.internal.telecom.ITelecomService;
59 import com.android.internal.telephony.CellNetworkScanResult;
60 import com.android.internal.telephony.IPhoneSubInfo;
61 import com.android.internal.telephony.ITelephony;
62 import com.android.internal.telephony.ITelephonyRegistry;
63 import com.android.internal.telephony.OperatorInfo;
64 import com.android.internal.telephony.PhoneConstants;
65 import com.android.internal.telephony.RILConstants;
66 import com.android.internal.telephony.TelephonyProperties;
67
68 import java.io.FileInputStream;
69 import java.io.IOException;
70 import java.lang.annotation.Retention;
71 import java.lang.annotation.RetentionPolicy;
72 import java.util.ArrayList;
73 import java.util.Collections;
74 import java.util.List;
75 import java.util.regex.Matcher;
76 import java.util.regex.Pattern;
77
78 /**
79  * Provides access to information about the telephony services on
80  * the device. Applications can use the methods in this class to
81  * determine telephony services and states, as well as to access some
82  * types of subscriber information. Applications can also register
83  * a listener to receive notification of telephony state changes.
84  * <p>
85  * The returned TelephonyManager will use the default subscription for all calls.
86  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
87  * <code>
88  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
89  * </code>
90  * <p>
91  * Note that access to some telephony information is
92  * permission-protected. Your application cannot access the protected
93  * information unless it has the appropriate permissions declared in
94  * its manifest file. Where permissions apply, they are noted in the
95  * the methods through which you access the protected information.
96  */
97 @SystemService(Context.TELEPHONY_SERVICE)
98 public class TelephonyManager {
99     private static final String TAG = "TelephonyManager";
100
101     /**
102      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
103      * into the ResultReceiver Bundle.
104      * @hide
105      */
106     public static final String MODEM_ACTIVITY_RESULT_KEY =
107             BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY;
108
109     /**
110      * The allowed states of Wi-Fi calling.
111      *
112      * @hide
113      */
114     public interface WifiCallingChoices {
115         /** Always use Wi-Fi calling */
116         static final int ALWAYS_USE = 0;
117         /** Ask the user whether to use Wi-Fi on every call */
118         static final int ASK_EVERY_TIME = 1;
119         /** Never use Wi-Fi calling */
120         static final int NEVER_USE = 2;
121     }
122
123     /** The otaspMode passed to PhoneStateListener#onOtaspChanged */
124     /** @hide */
125     static public final int OTASP_UNINITIALIZED = 0;
126     /** @hide */
127     static public final int OTASP_UNKNOWN = 1;
128     /** @hide */
129     static public final int OTASP_NEEDED = 2;
130     /** @hide */
131     static public final int OTASP_NOT_NEEDED = 3;
132     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
133     /** @hide */
134     static public final int OTASP_SIM_UNPROVISIONED = 5;
135
136
137     /** @hide */
138     static public final int KEY_TYPE_EPDG = 1;
139
140     /** @hide */
141     static public final int KEY_TYPE_WLAN = 2;
142
143     private final Context mContext;
144     private final int mSubId;
145     private SubscriptionManager mSubscriptionManager;
146     private TelephonyScanManager mTelephonyScanManager;
147
148     private static String multiSimConfig =
149             SystemProperties.get(TelephonyProperties.PROPERTY_MULTI_SIM_CONFIG);
150
151     /** Enum indicating multisim variants
152      *  DSDS - Dual SIM Dual Standby
153      *  DSDA - Dual SIM Dual Active
154      *  TSTS - Triple SIM Triple Standby
155      **/
156     /** @hide */
157     public enum MultiSimVariants {
158         DSDS,
159         DSDA,
160         TSTS,
161         UNKNOWN
162     };
163
164     /** @hide */
165     public TelephonyManager(Context context) {
166       this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
167     }
168
169     /** @hide */
170     public TelephonyManager(Context context, int subId) {
171         mSubId = subId;
172         Context appContext = context.getApplicationContext();
173         if (appContext != null) {
174             mContext = appContext;
175         } else {
176             mContext = context;
177         }
178         mSubscriptionManager = SubscriptionManager.from(mContext);
179     }
180
181     /** @hide */
182     private TelephonyManager() {
183         mContext = null;
184         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
185     }
186
187     private static TelephonyManager sInstance = new TelephonyManager();
188
189     /** @hide
190     /* @deprecated - use getSystemService as described above */
191     public static TelephonyManager getDefault() {
192         return sInstance;
193     }
194
195     private String getOpPackageName() {
196         // For legacy reasons the TelephonyManager has API for getting
197         // a static instance with no context set preventing us from
198         // getting the op package name. As a workaround we do a best
199         // effort and get the context from the current activity thread.
200         if (mContext != null) {
201             return mContext.getOpPackageName();
202         }
203         return ActivityThread.currentOpPackageName();
204     }
205
206     /**
207      * Returns the multi SIM variant
208      * Returns DSDS for Dual SIM Dual Standby
209      * Returns DSDA for Dual SIM Dual Active
210      * Returns TSTS for Triple SIM Triple Standby
211      * Returns UNKNOWN for others
212      */
213     /** {@hide} */
214     public MultiSimVariants getMultiSimConfiguration() {
215         String mSimConfig =
216             SystemProperties.get(TelephonyProperties.PROPERTY_MULTI_SIM_CONFIG);
217         if (mSimConfig.equals("dsds")) {
218             return MultiSimVariants.DSDS;
219         } else if (mSimConfig.equals("dsda")) {
220             return MultiSimVariants.DSDA;
221         } else if (mSimConfig.equals("tsts")) {
222             return MultiSimVariants.TSTS;
223         } else {
224             return MultiSimVariants.UNKNOWN;
225         }
226     }
227
228
229     /**
230      * Returns the number of phones available.
231      * Returns 0 if none of voice, sms, data is not supported
232      * Returns 1 for Single standby mode (Single SIM functionality)
233      * Returns 2 for Dual standby mode.(Dual SIM functionality)
234      */
235     public int getPhoneCount() {
236         int phoneCount = 1;
237         switch (getMultiSimConfiguration()) {
238             case UNKNOWN:
239                 // if voice or sms or data is supported, return 1 otherwise 0
240                 if (isVoiceCapable() || isSmsCapable()) {
241                     phoneCount = 1;
242                 } else {
243                     // todo: try to clean this up further by getting rid of the nested conditions
244                     if (mContext == null) {
245                         phoneCount = 1;
246                     } else {
247                         // check for data support
248                         ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(
249                                 Context.CONNECTIVITY_SERVICE);
250                         if (cm == null) {
251                             phoneCount = 1;
252                         } else {
253                             if (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE)) {
254                                 phoneCount = 1;
255                             } else {
256                                 phoneCount = 0;
257                             }
258                         }
259                     }
260                 }
261                 break;
262             case DSDS:
263             case DSDA:
264                 phoneCount = PhoneConstants.MAX_PHONE_COUNT_DUAL_SIM;
265                 break;
266             case TSTS:
267                 phoneCount = PhoneConstants.MAX_PHONE_COUNT_TRI_SIM;
268                 break;
269         }
270         return phoneCount;
271     }
272
273     /** {@hide} */
274     public static TelephonyManager from(Context context) {
275         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
276     }
277
278     /**
279      * Create a new TelephonyManager object pinned to the given subscription ID.
280      *
281      * @return a TelephonyManager that uses the given subId for all calls.
282      */
283     public TelephonyManager createForSubscriptionId(int subId) {
284       // Don't reuse any TelephonyManager objects.
285       return new TelephonyManager(mContext, subId);
286     }
287
288     /**
289      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
290      * phone account.
291      *
292      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
293      * if the phone account does not correspond to a valid subscription ID.
294      */
295     @Nullable
296     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
297         int subId = getSubIdForPhoneAccountHandle(phoneAccountHandle);
298         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
299             return null;
300         }
301         return new TelephonyManager(mContext, subId);
302     }
303
304     /** {@hide} */
305     public boolean isMultiSimEnabled() {
306         return (multiSimConfig.equals("dsds") || multiSimConfig.equals("dsda") ||
307             multiSimConfig.equals("tsts"));
308     }
309
310     //
311     // Broadcast Intent actions
312     //
313
314     /**
315      * Broadcast intent action indicating that the call state
316      * on the device has changed.
317      *
318      * <p>
319      * The {@link #EXTRA_STATE} extra indicates the new call state.
320      * If the new state is RINGING, a second extra
321      * {@link #EXTRA_INCOMING_NUMBER} provides the incoming phone number as
322      * a String.
323      *
324      * <p class="note">
325      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
326      * broadcast in version 1.0, but it is no longer sticky.
327      * Instead, use {@link #getCallState} to synchronously query the current call state.
328      *
329      * @see #EXTRA_STATE
330      * @see #EXTRA_INCOMING_NUMBER
331      * @see #getCallState
332      */
333     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
334     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
335     public static final String ACTION_PHONE_STATE_CHANGED =
336             "android.intent.action.PHONE_STATE";
337
338     /**
339      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
340      * call. By default, the device's default SMS app consumes this message and sends a text message
341      * to the caller. A third party app can also provide this functionality by consuming this Intent
342      * with a {@link android.app.Service} and sending the message using its own messaging system.
343      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
344      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
345      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
346      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
347      * set of phone numbers if there are multiple recipients. For example, {@code
348      * smsto:2065551234}.</p>
349      *
350      * <p>The intent may also contain extras for the message text (in {@link
351      * android.content.Intent#EXTRA_TEXT}) and a message subject
352      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
353      *
354      * <p class="note"><strong>Note:</strong>
355      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
356      * that requires the
357      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
358      * <p>For example, the service that receives this intent can be declared in the manifest file
359      * with an intent filter like this:</p>
360      * <pre>
361      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
362      * &lt;service android:name=".HeadlessSmsSendService"
363      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
364      *          android:exported="true" >
365      *   &lt;intent-filter>
366      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
367      *     &lt;category android:name="android.intent.category.DEFAULT" />
368      *     &lt;data android:scheme="sms" />
369      *     &lt;data android:scheme="smsto" />
370      *     &lt;data android:scheme="mms" />
371      *     &lt;data android:scheme="mmsto" />
372      *   &lt;/intent-filter>
373      * &lt;/service></pre>
374      * <p>
375      * Output: nothing.
376      */
377     @SdkConstant(SdkConstantType.SERVICE_ACTION)
378     public static final String ACTION_RESPOND_VIA_MESSAGE =
379             "android.intent.action.RESPOND_VIA_MESSAGE";
380
381     /**
382      * The emergency dialer may choose to present activities with intent filters for this
383      * action as emergency assistance buttons that launch the activity when clicked.
384      *
385      * @hide
386      */
387     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
388     public static final String ACTION_EMERGENCY_ASSISTANCE =
389             "android.telephony.action.EMERGENCY_ASSISTANCE";
390
391     /**
392      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
393      * call settings page launched by
394      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
395      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
396      * which would also like to manage voicemail settings should set this meta-data to {@code true}
397      * in the manifest registration of their application.
398      *
399      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
400      * @see #ACTION_CONFIGURE_VOICEMAIL
401      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
402      */
403     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
404             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
405
406     /**
407      * Open the voicemail settings activity to make changes to voicemail configuration.
408      *
409      * <p>
410      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
411      * API if set.
412      *
413      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
414      */
415     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
416     public static final String ACTION_CONFIGURE_VOICEMAIL =
417             "android.telephony.action.CONFIGURE_VOICEMAIL";
418
419     /**
420      * The boolean value indicating whether the voicemail settings activity launched by {@link
421      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
422      * used by dialer implementations which provides their own voicemail settings UI, but still
423      * needs to expose device specific voicemail settings to the user.
424      *
425      * @see #ACTION_CONFIGURE_VOICEMAIL
426      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
427      */
428     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
429             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
430
431     /**
432      * @hide
433      */
434     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
435
436     /**
437      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
438      * for a String containing the new call state.
439      *
440      * <p class="note">
441      * Retrieve with
442      * {@link android.content.Intent#getStringExtra(String)}.
443      *
444      * @see #EXTRA_STATE_IDLE
445      * @see #EXTRA_STATE_RINGING
446      * @see #EXTRA_STATE_OFFHOOK
447      */
448     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
449
450     /**
451      * Value used with {@link #EXTRA_STATE} corresponding to
452      * {@link #CALL_STATE_IDLE}.
453      */
454     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
455
456     /**
457      * Value used with {@link #EXTRA_STATE} corresponding to
458      * {@link #CALL_STATE_RINGING}.
459      */
460     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
461
462     /**
463      * Value used with {@link #EXTRA_STATE} corresponding to
464      * {@link #CALL_STATE_OFFHOOK}.
465      */
466     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
467
468     /**
469      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
470      * for a String containing the incoming phone number.
471      * Only valid when the new call state is RINGING.
472      *
473      * <p class="note">
474      * Retrieve with
475      * {@link android.content.Intent#getStringExtra(String)}.
476      */
477     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
478
479     /**
480      * Broadcast intent action indicating that a precise call state
481      * (cellular) on the device has changed.
482      *
483      * <p>
484      * The {@link #EXTRA_RINGING_CALL_STATE} extra indicates the ringing call state.
485      * The {@link #EXTRA_FOREGROUND_CALL_STATE} extra indicates the foreground call state.
486      * The {@link #EXTRA_BACKGROUND_CALL_STATE} extra indicates the background call state.
487      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
488      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
489      *
490      * <p class="note">
491      * Requires the READ_PRECISE_PHONE_STATE permission.
492      *
493      * @see #EXTRA_RINGING_CALL_STATE
494      * @see #EXTRA_FOREGROUND_CALL_STATE
495      * @see #EXTRA_BACKGROUND_CALL_STATE
496      * @see #EXTRA_DISCONNECT_CAUSE
497      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
498      *
499      * <p class="note">
500      * Requires the READ_PRECISE_PHONE_STATE permission.
501      *
502      * @hide
503      */
504     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
505     public static final String ACTION_PRECISE_CALL_STATE_CHANGED =
506             "android.intent.action.PRECISE_CALL_STATE";
507
508     /**
509      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast
510      * for an integer containing the state of the current ringing call.
511      *
512      * @see PreciseCallState#PRECISE_CALL_STATE_NOT_VALID
513      * @see PreciseCallState#PRECISE_CALL_STATE_IDLE
514      * @see PreciseCallState#PRECISE_CALL_STATE_ACTIVE
515      * @see PreciseCallState#PRECISE_CALL_STATE_HOLDING
516      * @see PreciseCallState#PRECISE_CALL_STATE_DIALING
517      * @see PreciseCallState#PRECISE_CALL_STATE_ALERTING
518      * @see PreciseCallState#PRECISE_CALL_STATE_INCOMING
519      * @see PreciseCallState#PRECISE_CALL_STATE_WAITING
520      * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTED
521      * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTING
522      *
523      * <p class="note">
524      * Retrieve with
525      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
526      *
527      * @hide
528      */
529     public static final String EXTRA_RINGING_CALL_STATE = "ringing_state";
530
531     /**
532      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast
533      * for an integer containing the state of the current foreground call.
534      *
535      * @see PreciseCallState#PRECISE_CALL_STATE_NOT_VALID
536      * @see PreciseCallState#PRECISE_CALL_STATE_IDLE
537      * @see PreciseCallState#PRECISE_CALL_STATE_ACTIVE
538      * @see PreciseCallState#PRECISE_CALL_STATE_HOLDING
539      * @see PreciseCallState#PRECISE_CALL_STATE_DIALING
540      * @see PreciseCallState#PRECISE_CALL_STATE_ALERTING
541      * @see PreciseCallState#PRECISE_CALL_STATE_INCOMING
542      * @see PreciseCallState#PRECISE_CALL_STATE_WAITING
543      * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTED
544      * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTING
545      *
546      * <p class="note">
547      * Retrieve with
548      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
549      *
550      * @hide
551      */
552     public static final String EXTRA_FOREGROUND_CALL_STATE = "foreground_state";
553
554     /**
555      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast
556      * for an integer containing the state of the current background call.
557      *
558      * @see PreciseCallState#PRECISE_CALL_STATE_NOT_VALID
559      * @see PreciseCallState#PRECISE_CALL_STATE_IDLE
560      * @see PreciseCallState#PRECISE_CALL_STATE_ACTIVE
561      * @see PreciseCallState#PRECISE_CALL_STATE_HOLDING
562      * @see PreciseCallState#PRECISE_CALL_STATE_DIALING
563      * @see PreciseCallState#PRECISE_CALL_STATE_ALERTING
564      * @see PreciseCallState#PRECISE_CALL_STATE_INCOMING
565      * @see PreciseCallState#PRECISE_CALL_STATE_WAITING
566      * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTED
567      * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTING
568      *
569      * <p class="note">
570      * Retrieve with
571      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
572      *
573      * @hide
574      */
575     public static final String EXTRA_BACKGROUND_CALL_STATE = "background_state";
576
577     /**
578      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast
579      * for an integer containing the disconnect cause.
580      *
581      * @see DisconnectCause
582      *
583      * <p class="note">
584      * Retrieve with
585      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
586      *
587      * @hide
588      */
589     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
590
591     /**
592      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast
593      * for an integer containing the disconnect cause provided by the RIL.
594      *
595      * @see PreciseDisconnectCause
596      *
597      * <p class="note">
598      * Retrieve with
599      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
600      *
601      * @hide
602      */
603     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
604
605     /**
606      * Broadcast intent action indicating a data connection has changed,
607      * providing precise information about the connection.
608      *
609      * <p>
610      * The {@link #EXTRA_DATA_STATE} extra indicates the connection state.
611      * The {@link #EXTRA_DATA_NETWORK_TYPE} extra indicates the connection network type.
612      * The {@link #EXTRA_DATA_APN_TYPE} extra indicates the APN type.
613      * The {@link #EXTRA_DATA_APN} extra indicates the APN.
614      * The {@link #EXTRA_DATA_CHANGE_REASON} extra indicates the connection change reason.
615      * The {@link #EXTRA_DATA_IFACE_PROPERTIES} extra indicates the connection interface.
616      * The {@link #EXTRA_DATA_FAILURE_CAUSE} extra indicates the connection fail cause.
617      *
618      * <p class="note">
619      * Requires the READ_PRECISE_PHONE_STATE permission.
620      *
621      * @see #EXTRA_DATA_STATE
622      * @see #EXTRA_DATA_NETWORK_TYPE
623      * @see #EXTRA_DATA_APN_TYPE
624      * @see #EXTRA_DATA_APN
625      * @see #EXTRA_DATA_CHANGE_REASON
626      * @see #EXTRA_DATA_IFACE
627      * @see #EXTRA_DATA_FAILURE_CAUSE
628      * @hide
629      *
630      * @deprecated If the app is running in the background, it won't be able to receive this
631      * broadcast. Apps should use ConnectivityManager {@link #registerNetworkCallback(
632      * android.net.NetworkRequest, ConnectivityManager.NetworkCallback)} to listen for network
633      * changes.
634      */
635     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
636     @Deprecated
637     public static final String ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED =
638             "android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED";
639
640     /**
641      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
642      * for an integer containing the state of the current data connection.
643      *
644      * @see TelephonyManager#DATA_UNKNOWN
645      * @see TelephonyManager#DATA_DISCONNECTED
646      * @see TelephonyManager#DATA_CONNECTING
647      * @see TelephonyManager#DATA_CONNECTED
648      * @see TelephonyManager#DATA_SUSPENDED
649      *
650      * <p class="note">
651      * Retrieve with
652      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
653      *
654      * @hide
655      */
656     public static final String EXTRA_DATA_STATE = PhoneConstants.STATE_KEY;
657
658     /**
659      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
660      * for an integer containing the network type.
661      *
662      * @see TelephonyManager#NETWORK_TYPE_UNKNOWN
663      * @see TelephonyManager#NETWORK_TYPE_GPRS
664      * @see TelephonyManager#NETWORK_TYPE_EDGE
665      * @see TelephonyManager#NETWORK_TYPE_UMTS
666      * @see TelephonyManager#NETWORK_TYPE_CDMA
667      * @see TelephonyManager#NETWORK_TYPE_EVDO_0
668      * @see TelephonyManager#NETWORK_TYPE_EVDO_A
669      * @see TelephonyManager#NETWORK_TYPE_1xRTT
670      * @see TelephonyManager#NETWORK_TYPE_HSDPA
671      * @see TelephonyManager#NETWORK_TYPE_HSUPA
672      * @see TelephonyManager#NETWORK_TYPE_HSPA
673      * @see TelephonyManager#NETWORK_TYPE_IDEN
674      * @see TelephonyManager#NETWORK_TYPE_EVDO_B
675      * @see TelephonyManager#NETWORK_TYPE_LTE
676      * @see TelephonyManager#NETWORK_TYPE_EHRPD
677      * @see TelephonyManager#NETWORK_TYPE_HSPAP
678      *
679      * <p class="note">
680      * Retrieve with
681      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
682      *
683      * @hide
684      */
685     public static final String EXTRA_DATA_NETWORK_TYPE = PhoneConstants.DATA_NETWORK_TYPE_KEY;
686
687     /**
688      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
689      * for an String containing the data APN type.
690      *
691      * <p class="note">
692      * Retrieve with
693      * {@link android.content.Intent#getStringExtra(String name)}.
694      *
695      * @hide
696      */
697     public static final String EXTRA_DATA_APN_TYPE = PhoneConstants.DATA_APN_TYPE_KEY;
698
699     /**
700      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
701      * for an String containing the data APN.
702      *
703      * <p class="note">
704      * Retrieve with
705      * {@link android.content.Intent#getStringExtra(String name)}.
706      *
707      * @hide
708      */
709     public static final String EXTRA_DATA_APN = PhoneConstants.DATA_APN_KEY;
710
711     /**
712      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
713      * for an String representation of the change reason.
714      *
715      * <p class="note">
716      * Retrieve with
717      * {@link android.content.Intent#getStringExtra(String name)}.
718      *
719      * @hide
720      */
721     public static final String EXTRA_DATA_CHANGE_REASON = PhoneConstants.STATE_CHANGE_REASON_KEY;
722
723     /**
724      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
725      * for an String representation of the data interface.
726      *
727      * <p class="note">
728      * Retrieve with
729      * {@link android.content.Intent#getParcelableExtra(String name)}.
730      *
731      * @hide
732      */
733     public static final String EXTRA_DATA_LINK_PROPERTIES_KEY = PhoneConstants.DATA_LINK_PROPERTIES_KEY;
734
735     /**
736      * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
737      * for the data connection fail cause.
738      *
739      * <p class="note">
740      * Retrieve with
741      * {@link android.content.Intent#getStringExtra(String name)}.
742      *
743      * @hide
744      */
745     public static final String EXTRA_DATA_FAILURE_CAUSE = PhoneConstants.DATA_FAILURE_CAUSE_KEY;
746
747     /**
748      * Broadcast intent action for letting the default dialer to know to show voicemail
749      * notification.
750      *
751      * <p>
752      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
753      * voicemail is received on.
754      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
755      * voicemails.
756      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
757      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
758      * will call the voicemail number when sent. This extra will be empty if the voicemail number
759      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
760      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
761      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
762      * available when the voicemail number is not set.
763      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
764      * notification.
765      *
766      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
767      * @see #EXTRA_NOTIFICATION_COUNT
768      * @see #EXTRA_VOICEMAIL_NUMBER
769      * @see #EXTRA_CALL_VOICEMAIL_INTENT
770      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
771      * @see #EXTRA_IS_REFRESH
772      */
773     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
774             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
775
776     /**
777      * The extra used with an {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify
778      * the {@link PhoneAccountHandle} the notification is for.
779      * <p class="note">
780      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
781      */
782     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
783             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
784
785     /**
786      * The number of voice messages associated with the notification.
787      */
788     public static final String EXTRA_NOTIFICATION_COUNT =
789             "android.telephony.extra.NOTIFICATION_COUNT";
790
791     /**
792      * The voicemail number.
793      */
794     public static final String EXTRA_VOICEMAIL_NUMBER =
795             "android.telephony.extra.VOICEMAIL_NUMBER";
796
797     /**
798      * The intent to call voicemail.
799      */
800     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
801             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
802
803     /**
804      * The intent to launch voicemail settings.
805      */
806     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
807             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
808
809     /**
810      * Boolean value representing whether the {@link
811      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
812      * notification. Notification refresh happens after reboot or connectivity changes. The user has
813      * already been notified for the voicemail so it should not alert the user, and should not be
814      * shown again if the user has dismissed it.
815      */
816     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
817
818     /**
819      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
820      * successfully handed over from WIFI to LTE.
821      * <p>
822      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
823      * The {@link Bundle} parameter is expected to be null when this connection event is used.
824      * @hide
825      */
826     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
827             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
828
829     /**
830      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
831      * handed over from LTE to WIFI.
832      * <p>
833      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
834      * The {@link Bundle} parameter is expected to be null when this connection event is used.
835      * @hide
836      */
837     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
838             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
839
840     /**
841      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
842      * audio because the data limit was reached.
843      * <p>
844      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
845      * The {@link Bundle} parameter is expected to be null when this connection event is used.
846      * @hide
847      */
848     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
849             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
850
851     /**
852      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
853      * audio because the data was disabled.
854      * <p>
855      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
856      * The {@link Bundle} parameter is expected to be null when this connection event is used.
857      * @hide
858      */
859     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
860             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
861
862     /**
863      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
864      * the user when an international call is placed while on WFC only.
865      * <p>
866      * Used when the carrier config value
867      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
868      * is on WFC (VoLTE not available) and an international number is dialed.
869      * <p>
870      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
871      * The {@link Bundle} parameter is expected to be null when this connection event is used.
872      * @hide
873      */
874     public static final String EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
875             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
876
877     /**
878      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
879      * forwarded to another number.
880      * <p>
881      * Sent in response to an IMS supplementary service notification indicating the call has been
882      * forwarded.
883      * <p>
884      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
885      * The {@link Bundle} parameter is expected to be null when this connection event is used.
886      * @hide
887      */
888     public static final String EVENT_CALL_FORWARDED =
889             "android.telephony.event.EVENT_CALL_FORWARDED";
890
891     /* Visual voicemail protocols */
892
893     /**
894      * The OMTP protocol.
895      */
896     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
897
898     /**
899      * A flavor of OMTP protocol with a different mobile originated (MO) format
900      */
901     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
902
903     /**
904      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
905      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
906      * setting, this key will not exist.
907      *
908      * @see #getVisualVoicemailSettings()
909      * @hide
910      */
911     @SystemApi
912     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
913             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
914
915     /**
916      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
917      * access PIN scrambled during the auto provisioning process. The user is expected to reset
918      * their PIN if this value is not {@code null}.
919      *
920      * @see #getVisualVoicemailSettings()
921      * @hide
922      */
923     @SystemApi
924     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
925             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
926
927     /**
928      * @hide
929      */
930     public static final String USSD_RESPONSE = "USSD_RESPONSE";
931
932     /**
933      * USSD return code success.
934      * @hide
935      */
936     public static final int USSD_RETURN_SUCCESS = 100;
937
938     /**
939      * Failed code returned when the mobile network has failed to complete a USSD request.
940      * <p>
941      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
942      * TelephonyManager, String, int)}.
943      */
944     public static final int USSD_RETURN_FAILURE = -1;
945
946     /**
947      * Failure code returned when a USSD request has failed to execute because the Telephony
948      * service is unavailable.
949      * <p>
950      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
951      * TelephonyManager, String, int)}.
952      */
953     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
954
955     //
956     //
957     // Device Info
958     //
959     //
960
961     /**
962      * Returns the software version number for the device, for example,
963      * the IMEI/SV for GSM phones. Return null if the software version is
964      * not available.
965      */
966     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
967     public String getDeviceSoftwareVersion() {
968         return getDeviceSoftwareVersion(getSlotIndex());
969     }
970
971     /**
972      * Returns the software version number for the device, for example,
973      * the IMEI/SV for GSM phones. Return null if the software version is
974      * not available.
975      *
976      * @param slotIndex of which deviceID is returned
977      */
978     /** {@hide} */
979     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
980     public String getDeviceSoftwareVersion(int slotIndex) {
981         ITelephony telephony = getITelephony();
982         if (telephony == null) return null;
983
984         try {
985             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName());
986         } catch (RemoteException ex) {
987             return null;
988         } catch (NullPointerException ex) {
989             return null;
990         }
991     }
992
993     /**
994      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
995      * or ESN for CDMA phones. Return null if device ID is not available.
996      *
997      * @deprecated Use (@link getImei} which returns IMEI for GSM or (@link getMeid} which returns
998      * MEID for CDMA.
999      */
1000     @Deprecated
1001     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1002     public String getDeviceId() {
1003         try {
1004             ITelephony telephony = getITelephony();
1005             if (telephony == null)
1006                 return null;
1007             return telephony.getDeviceId(mContext.getOpPackageName());
1008         } catch (RemoteException ex) {
1009             return null;
1010         } catch (NullPointerException ex) {
1011             return null;
1012         }
1013     }
1014
1015     /**
1016      * Returns the unique device ID of a subscription, for example, the IMEI for
1017      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
1018      *
1019      * @param slotIndex of which deviceID is returned
1020      *
1021      * @deprecated Use (@link getImei} which returns IMEI for GSM or (@link getMeid} which returns
1022      * MEID for CDMA.
1023      */
1024     @Deprecated
1025     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1026     public String getDeviceId(int slotIndex) {
1027         // FIXME this assumes phoneId == slotIndex
1028         try {
1029             IPhoneSubInfo info = getSubscriberInfo();
1030             if (info == null)
1031                 return null;
1032             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName());
1033         } catch (RemoteException ex) {
1034             return null;
1035         } catch (NullPointerException ex) {
1036             return null;
1037         }
1038     }
1039
1040     /**
1041      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
1042      * available.
1043      */
1044     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1045     public String getImei() {
1046         return getImei(getSlotIndex());
1047     }
1048
1049     /**
1050      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
1051      * available.
1052      *
1053      * @param slotIndex of which IMEI is returned
1054      */
1055     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1056     public String getImei(int slotIndex) {
1057         ITelephony telephony = getITelephony();
1058         if (telephony == null) return null;
1059
1060         try {
1061             return telephony.getImeiForSlot(slotIndex, getOpPackageName());
1062         } catch (RemoteException ex) {
1063             return null;
1064         } catch (NullPointerException ex) {
1065             return null;
1066         }
1067     }
1068
1069     /**
1070      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
1071      */
1072     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1073     public String getMeid() {
1074         return getMeid(getSlotIndex());
1075     }
1076
1077     /**
1078      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
1079      *
1080      * @param slotIndex of which MEID is returned
1081      */
1082     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1083     public String getMeid(int slotIndex) {
1084         ITelephony telephony = getITelephony();
1085         if (telephony == null) return null;
1086
1087         try {
1088             return telephony.getMeidForSlot(slotIndex, getOpPackageName());
1089         } catch (RemoteException ex) {
1090             return null;
1091         } catch (NullPointerException ex) {
1092             return null;
1093         }
1094     }
1095
1096     /**
1097      * Returns the NAI. Return null if NAI is not available.
1098      *
1099      */
1100     /** {@hide}*/
1101     public String getNai() {
1102         return getNai(getSlotIndex());
1103     }
1104
1105     /**
1106      * Returns the NAI. Return null if NAI is not available.
1107      *
1108      *  @param slotIndex of which Nai is returned
1109      */
1110     /** {@hide}*/
1111     public String getNai(int slotIndex) {
1112         int[] subId = SubscriptionManager.getSubId(slotIndex);
1113         try {
1114             IPhoneSubInfo info = getSubscriberInfo();
1115             if (info == null)
1116                 return null;
1117             String nai = info.getNaiForSubscriber(subId[0], mContext.getOpPackageName());
1118             if (Log.isLoggable(TAG, Log.VERBOSE)) {
1119                 Rlog.v(TAG, "Nai = " + nai);
1120             }
1121             return nai;
1122         } catch (RemoteException ex) {
1123             return null;
1124         } catch (NullPointerException ex) {
1125             return null;
1126         }
1127     }
1128
1129     /**
1130      * Returns the current location of the device.
1131      *<p>
1132      * If there is only one radio in the device and that radio has an LTE connection,
1133      * this method will return null. The implementation must not to try add LTE
1134      * identifiers into the existing cdma/gsm classes.
1135      *<p>
1136      * @return Current location of the device or null if not available.
1137      *
1138      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
1139      */
1140     @Deprecated
1141     @RequiresPermission(anyOf = {
1142             android.Manifest.permission.ACCESS_COARSE_LOCATION,
1143             android.Manifest.permission.ACCESS_FINE_LOCATION
1144     })
1145     public CellLocation getCellLocation() {
1146         try {
1147             ITelephony telephony = getITelephony();
1148             if (telephony == null) {
1149                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
1150                 return null;
1151             }
1152             Bundle bundle = telephony.getCellLocation(mContext.getOpPackageName());
1153             if (bundle.isEmpty()) {
1154                 Rlog.d(TAG, "getCellLocation returning null because bundle is empty");
1155                 return null;
1156             }
1157             CellLocation cl = CellLocation.newFromBundle(bundle);
1158             if (cl.isEmpty()) {
1159                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty");
1160                 return null;
1161             }
1162             return cl;
1163         } catch (RemoteException ex) {
1164             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
1165             return null;
1166         } catch (NullPointerException ex) {
1167             Rlog.d(TAG, "getCellLocation returning null due to NullPointerException " + ex);
1168             return null;
1169         }
1170     }
1171
1172     /**
1173      * Enables location update notifications.  {@link PhoneStateListener#onCellLocationChanged
1174      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
1175      *
1176      * @hide
1177      */
1178     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
1179     public void enableLocationUpdates() {
1180         enableLocationUpdates(getSubId());
1181     }
1182
1183     /**
1184      * Enables location update notifications for a subscription.
1185      * {@link PhoneStateListener#onCellLocationChanged
1186      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
1187      *
1188      * @param subId for which the location updates are enabled
1189      * @hide
1190      */
1191     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
1192     public void enableLocationUpdates(int subId) {
1193         try {
1194             ITelephony telephony = getITelephony();
1195             if (telephony != null)
1196                 telephony.enableLocationUpdatesForSubscriber(subId);
1197         } catch (RemoteException ex) {
1198         } catch (NullPointerException ex) {
1199         }
1200     }
1201
1202     /**
1203      * Disables location update notifications.  {@link PhoneStateListener#onCellLocationChanged
1204      * PhoneStateListener.onCellLocationChanged} will be called on location updates.
1205      *
1206      * @hide
1207      */
1208     @RequiresPermission(android.Manifest.permission.CONTROL_LOCATION_UPDATES)
1209     public void disableLocationUpdates() {
1210         disableLocationUpdates(getSubId());
1211     }
1212
1213     /** @hide */
1214     public void disableLocationUpdates(int subId) {
1215         try {
1216             ITelephony telephony = getITelephony();
1217             if (telephony != null)
1218                 telephony.disableLocationUpdatesForSubscriber(subId);
1219         } catch (RemoteException ex) {
1220         } catch (NullPointerException ex) {
1221         }
1222     }
1223
1224     /**
1225      * Returns the neighboring cell information of the device.
1226      *
1227      * @return List of NeighboringCellInfo or null if info unavailable.
1228      *
1229      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
1230      *             from NeighboringCellInfo.
1231      */
1232     @Deprecated
1233     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
1234     public List<NeighboringCellInfo> getNeighboringCellInfo() {
1235         try {
1236             ITelephony telephony = getITelephony();
1237             if (telephony == null)
1238                 return null;
1239             return telephony.getNeighboringCellInfo(mContext.getOpPackageName());
1240         } catch (RemoteException ex) {
1241             return null;
1242         } catch (NullPointerException ex) {
1243             return null;
1244         }
1245     }
1246
1247     /** No phone radio. */
1248     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
1249     /** Phone radio is GSM. */
1250     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
1251     /** Phone radio is CDMA. */
1252     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
1253     /** Phone is via SIP. */
1254     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
1255
1256     /**
1257      * Returns the current phone type.
1258      * TODO: This is a last minute change and hence hidden.
1259      *
1260      * @see #PHONE_TYPE_NONE
1261      * @see #PHONE_TYPE_GSM
1262      * @see #PHONE_TYPE_CDMA
1263      * @see #PHONE_TYPE_SIP
1264      *
1265      * {@hide}
1266      */
1267     @SystemApi
1268     public int getCurrentPhoneType() {
1269         return getCurrentPhoneType(getSubId());
1270     }
1271
1272     /**
1273      * Returns a constant indicating the device phone type for a subscription.
1274      *
1275      * @see #PHONE_TYPE_NONE
1276      * @see #PHONE_TYPE_GSM
1277      * @see #PHONE_TYPE_CDMA
1278      *
1279      * @param subId for which phone type is returned
1280      * @hide
1281      */
1282     @SystemApi
1283     public int getCurrentPhoneType(int subId) {
1284         int phoneId;
1285         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1286             // if we don't have any sims, we don't have subscriptions, but we
1287             // still may want to know what type of phone we've got.
1288             phoneId = 0;
1289         } else {
1290             phoneId = SubscriptionManager.getPhoneId(subId);
1291         }
1292
1293         return getCurrentPhoneTypeForSlot(phoneId);
1294     }
1295
1296     /**
1297      * See getCurrentPhoneType.
1298      *
1299      * @hide
1300      */
1301     public int getCurrentPhoneTypeForSlot(int slotIndex) {
1302         try{
1303             ITelephony telephony = getITelephony();
1304             if (telephony != null) {
1305                 return telephony.getActivePhoneTypeForSlot(slotIndex);
1306             } else {
1307                 // This can happen when the ITelephony interface is not up yet.
1308                 return getPhoneTypeFromProperty(slotIndex);
1309             }
1310         } catch (RemoteException ex) {
1311             // This shouldn't happen in the normal case, as a backup we
1312             // read from the system property.
1313             return getPhoneTypeFromProperty(slotIndex);
1314         } catch (NullPointerException ex) {
1315             // This shouldn't happen in the normal case, as a backup we
1316             // read from the system property.
1317             return getPhoneTypeFromProperty(slotIndex);
1318         }
1319     }
1320
1321     /**
1322      * Returns a constant indicating the device phone type.  This
1323      * indicates the type of radio used to transmit voice calls.
1324      *
1325      * @see #PHONE_TYPE_NONE
1326      * @see #PHONE_TYPE_GSM
1327      * @see #PHONE_TYPE_CDMA
1328      * @see #PHONE_TYPE_SIP
1329      */
1330     public int getPhoneType() {
1331         if (!isVoiceCapable()) {
1332             return PHONE_TYPE_NONE;
1333         }
1334         return getCurrentPhoneType();
1335     }
1336
1337     private int getPhoneTypeFromProperty() {
1338         return getPhoneTypeFromProperty(getPhoneId());
1339     }
1340
1341     /** {@hide} */
1342     private int getPhoneTypeFromProperty(int phoneId) {
1343         String type = getTelephonyProperty(phoneId,
1344                 TelephonyProperties.CURRENT_ACTIVE_PHONE, null);
1345         if (type == null || type.isEmpty()) {
1346             return getPhoneTypeFromNetworkType(phoneId);
1347         }
1348         return Integer.parseInt(type);
1349     }
1350
1351     private int getPhoneTypeFromNetworkType() {
1352         return getPhoneTypeFromNetworkType(getPhoneId());
1353     }
1354
1355     /** {@hide} */
1356     private int getPhoneTypeFromNetworkType(int phoneId) {
1357         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
1358         // use the system property for default network type.
1359         // This is a fail safe, and can only happen at first boot.
1360         String mode = getTelephonyProperty(phoneId, "ro.telephony.default_network", null);
1361         if (mode != null && !mode.isEmpty()) {
1362             return TelephonyManager.getPhoneType(Integer.parseInt(mode));
1363         }
1364         return TelephonyManager.PHONE_TYPE_NONE;
1365     }
1366
1367     /**
1368      * This function returns the type of the phone, depending
1369      * on the network mode.
1370      *
1371      * @param networkMode
1372      * @return Phone Type
1373      *
1374      * @hide
1375      */
1376     public static int getPhoneType(int networkMode) {
1377         switch(networkMode) {
1378         case RILConstants.NETWORK_MODE_CDMA:
1379         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
1380         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
1381             return PhoneConstants.PHONE_TYPE_CDMA;
1382
1383         case RILConstants.NETWORK_MODE_WCDMA_PREF:
1384         case RILConstants.NETWORK_MODE_GSM_ONLY:
1385         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
1386         case RILConstants.NETWORK_MODE_GSM_UMTS:
1387         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
1388         case RILConstants.NETWORK_MODE_LTE_WCDMA:
1389         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
1390         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
1391         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
1392         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
1393         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
1394         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
1395         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
1396         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
1397         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
1398         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
1399             return PhoneConstants.PHONE_TYPE_GSM;
1400
1401         // Use CDMA Phone for the global mode including CDMA
1402         case RILConstants.NETWORK_MODE_GLOBAL:
1403         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
1404         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
1405             return PhoneConstants.PHONE_TYPE_CDMA;
1406
1407         case RILConstants.NETWORK_MODE_LTE_ONLY:
1408             if (getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
1409                 return PhoneConstants.PHONE_TYPE_CDMA;
1410             } else {
1411                 return PhoneConstants.PHONE_TYPE_GSM;
1412             }
1413         default:
1414             return PhoneConstants.PHONE_TYPE_GSM;
1415         }
1416     }
1417
1418     /**
1419      * The contents of the /proc/cmdline file
1420      */
1421     private static String getProcCmdLine()
1422     {
1423         String cmdline = "";
1424         FileInputStream is = null;
1425         try {
1426             is = new FileInputStream("/proc/cmdline");
1427             byte [] buffer = new byte[2048];
1428             int count = is.read(buffer);
1429             if (count > 0) {
1430                 cmdline = new String(buffer, 0, count);
1431             }
1432         } catch (IOException e) {
1433             Rlog.d(TAG, "No /proc/cmdline exception=" + e);
1434         } finally {
1435             if (is != null) {
1436                 try {
1437                     is.close();
1438                 } catch (IOException e) {
1439                 }
1440             }
1441         }
1442         Rlog.d(TAG, "/proc/cmdline=" + cmdline);
1443         return cmdline;
1444     }
1445
1446     /** Kernel command line */
1447     private static final String sKernelCmdLine = getProcCmdLine();
1448
1449     /** Pattern for selecting the product type from the kernel command line */
1450     private static final Pattern sProductTypePattern =
1451         Pattern.compile("\\sproduct_type\\s*=\\s*(\\w+)");
1452
1453     /** The ProductType used for LTE on CDMA devices */
1454     private static final String sLteOnCdmaProductType =
1455         SystemProperties.get(TelephonyProperties.PROPERTY_LTE_ON_CDMA_PRODUCT_TYPE, "");
1456
1457     /**
1458      * Return if the current radio is LTE on CDMA. This
1459      * is a tri-state return value as for a period of time
1460      * the mode may be unknown.
1461      *
1462      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
1463      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
1464      *
1465      * @hide
1466      */
1467     public static int getLteOnCdmaModeStatic() {
1468         int retVal;
1469         int curVal;
1470         String productType = "";
1471
1472         curVal = SystemProperties.getInt(TelephonyProperties.PROPERTY_LTE_ON_CDMA_DEVICE,
1473                     PhoneConstants.LTE_ON_CDMA_UNKNOWN);
1474         retVal = curVal;
1475         if (retVal == PhoneConstants.LTE_ON_CDMA_UNKNOWN) {
1476             Matcher matcher = sProductTypePattern.matcher(sKernelCmdLine);
1477             if (matcher.find()) {
1478                 productType = matcher.group(1);
1479                 if (sLteOnCdmaProductType.equals(productType)) {
1480                     retVal = PhoneConstants.LTE_ON_CDMA_TRUE;
1481                 } else {
1482                     retVal = PhoneConstants.LTE_ON_CDMA_FALSE;
1483                 }
1484             } else {
1485                 retVal = PhoneConstants.LTE_ON_CDMA_FALSE;
1486             }
1487         }
1488
1489         Rlog.d(TAG, "getLteOnCdmaMode=" + retVal + " curVal=" + curVal +
1490                 " product_type='" + productType +
1491                 "' lteOnCdmaProductType='" + sLteOnCdmaProductType + "'");
1492         return retVal;
1493     }
1494
1495     //
1496     //
1497     // Current Network
1498     //
1499     //
1500
1501     /**
1502      * Returns the alphabetic name of current registered operator.
1503      * <p>
1504      * Availability: Only when user is registered to a network. Result may be
1505      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1506      * on a CDMA network).
1507      */
1508     public String getNetworkOperatorName() {
1509         return getNetworkOperatorName(getSubId());
1510     }
1511
1512     /**
1513      * Returns the alphabetic name of current registered operator
1514      * for a particular subscription.
1515      * <p>
1516      * Availability: Only when user is registered to a network. Result may be
1517      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1518      * on a CDMA network).
1519      * @param subId
1520      * @hide
1521      */
1522     public String getNetworkOperatorName(int subId) {
1523         int phoneId = SubscriptionManager.getPhoneId(subId);
1524         return getTelephonyProperty(phoneId, TelephonyProperties.PROPERTY_OPERATOR_ALPHA, "");
1525     }
1526
1527     /**
1528      * Returns the numeric name (MCC+MNC) of current registered operator.
1529      * <p>
1530      * Availability: Only when user is registered to a network. Result may be
1531      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1532      * on a CDMA network).
1533      */
1534     public String getNetworkOperator() {
1535         return getNetworkOperatorForPhone(getPhoneId());
1536     }
1537
1538     /**
1539      * Returns the numeric name (MCC+MNC) of current registered operator
1540      * for a particular subscription.
1541      * <p>
1542      * Availability: Only when user is registered to a network. Result may be
1543      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1544      * on a CDMA network).
1545      *
1546      * @param subId
1547      * @hide
1548      */
1549     public String getNetworkOperator(int subId) {
1550         int phoneId = SubscriptionManager.getPhoneId(subId);
1551         return getNetworkOperatorForPhone(phoneId);
1552      }
1553
1554     /**
1555      * Returns the numeric name (MCC+MNC) of current registered operator
1556      * for a particular subscription.
1557      * <p>
1558      * Availability: Only when user is registered to a network. Result may be
1559      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1560      * on a CDMA network).
1561      *
1562      * @param phoneId
1563      * @hide
1564      **/
1565     public String getNetworkOperatorForPhone(int phoneId) {
1566         return getTelephonyProperty(phoneId, TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
1567      }
1568
1569
1570     /**
1571      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
1572      * network specifier is used by {@link
1573      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
1574      * android.net.NetworkRequest} that connects through the subscription.
1575      *
1576      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
1577      * @see #createForSubscriptionId(int)
1578      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
1579      */
1580     public String getNetworkSpecifier() {
1581         return String.valueOf(getSubId());
1582     }
1583
1584     /**
1585      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
1586      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
1587      * default values.
1588      *
1589      * @see CarrierConfigManager#getConfigForSubId(int)
1590      * @see #createForSubscriptionId(int)
1591      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
1592      */
1593     @WorkerThread
1594     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1595     public PersistableBundle getCarrierConfig() {
1596         CarrierConfigManager carrierConfigManager = mContext
1597                 .getSystemService(CarrierConfigManager.class);
1598         return carrierConfigManager.getConfigForSubId(getSubId());
1599     }
1600
1601     /**
1602      * Returns true if the device is considered roaming on the current
1603      * network, for GSM purposes.
1604      * <p>
1605      * Availability: Only when user registered to a network.
1606      */
1607     public boolean isNetworkRoaming() {
1608         return isNetworkRoaming(getSubId());
1609     }
1610
1611     /**
1612      * Returns true if the device is considered roaming on the current
1613      * network for a subscription.
1614      * <p>
1615      * Availability: Only when user registered to a network.
1616      *
1617      * @param subId
1618      * @hide
1619      */
1620     public boolean isNetworkRoaming(int subId) {
1621         int phoneId = SubscriptionManager.getPhoneId(subId);
1622         return Boolean.parseBoolean(getTelephonyProperty(phoneId,
1623                 TelephonyProperties.PROPERTY_OPERATOR_ISROAMING, null));
1624     }
1625
1626     /**
1627      * Returns the ISO country code equivalent of the current registered
1628      * operator's MCC (Mobile Country Code).
1629      * <p>
1630      * Availability: Only when user is registered to a network. Result may be
1631      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1632      * on a CDMA network).
1633      */
1634     public String getNetworkCountryIso() {
1635         return getNetworkCountryIsoForPhone(getPhoneId());
1636     }
1637
1638     /**
1639      * Returns the ISO country code equivalent of the current registered
1640      * operator's MCC (Mobile Country Code) of a subscription.
1641      * <p>
1642      * Availability: Only when user is registered to a network. Result may be
1643      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1644      * on a CDMA network).
1645      *
1646      * @param subId for which Network CountryIso is returned
1647      * @hide
1648      */
1649     public String getNetworkCountryIso(int subId) {
1650         return getNetworkCountryIsoForPhone(getPhoneId(subId));
1651     }
1652
1653     /**
1654      * Returns the ISO country code equivalent of the current registered
1655      * operator's MCC (Mobile Country Code) of a subscription.
1656      * <p>
1657      * Availability: Only when user is registered to a network. Result may be
1658      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
1659      * on a CDMA network).
1660      *
1661      * @param phoneId for which Network CountryIso is returned
1662      */
1663     /** {@hide} */
1664     public String getNetworkCountryIsoForPhone(int phoneId) {
1665         try {
1666             ITelephony telephony = getITelephony();
1667             if (telephony == null)
1668                 return "";
1669             return telephony.getNetworkCountryIsoForPhone(phoneId);
1670         } catch (RemoteException ex) {
1671                 return "";
1672         }
1673     }
1674
1675     /** Network type is unknown */
1676     public static final int NETWORK_TYPE_UNKNOWN = 0;
1677     /** Current network is GPRS */
1678     public static final int NETWORK_TYPE_GPRS = 1;
1679     /** Current network is EDGE */
1680     public static final int NETWORK_TYPE_EDGE = 2;
1681     /** Current network is UMTS */
1682     public static final int NETWORK_TYPE_UMTS = 3;
1683     /** Current network is CDMA: Either IS95A or IS95B*/
1684     public static final int NETWORK_TYPE_CDMA = 4;
1685     /** Current network is EVDO revision 0*/
1686     public static final int NETWORK_TYPE_EVDO_0 = 5;
1687     /** Current network is EVDO revision A*/
1688     public static final int NETWORK_TYPE_EVDO_A = 6;
1689     /** Current network is 1xRTT*/
1690     public static final int NETWORK_TYPE_1xRTT = 7;
1691     /** Current network is HSDPA */
1692     public static final int NETWORK_TYPE_HSDPA = 8;
1693     /** Current network is HSUPA */
1694     public static final int NETWORK_TYPE_HSUPA = 9;
1695     /** Current network is HSPA */
1696     public static final int NETWORK_TYPE_HSPA = 10;
1697     /** Current network is iDen */
1698     public static final int NETWORK_TYPE_IDEN = 11;
1699     /** Current network is EVDO revision B*/
1700     public static final int NETWORK_TYPE_EVDO_B = 12;
1701     /** Current network is LTE */
1702     public static final int NETWORK_TYPE_LTE = 13;
1703     /** Current network is eHRPD */
1704     public static final int NETWORK_TYPE_EHRPD = 14;
1705     /** Current network is HSPA+ */
1706     public static final int NETWORK_TYPE_HSPAP = 15;
1707     /** Current network is GSM */
1708     public static final int NETWORK_TYPE_GSM = 16;
1709     /** Current network is TD_SCDMA */
1710     public static final int NETWORK_TYPE_TD_SCDMA = 17;
1711     /** Current network is IWLAN */
1712     public static final int NETWORK_TYPE_IWLAN = 18;
1713     /** Current network is LTE_CA {@hide} */
1714     public static final int NETWORK_TYPE_LTE_CA = 19;
1715     /**
1716      * @return the NETWORK_TYPE_xxxx for current data connection.
1717      */
1718     public int getNetworkType() {
1719        try {
1720            ITelephony telephony = getITelephony();
1721            if (telephony != null) {
1722                return telephony.getNetworkType();
1723             } else {
1724                 // This can happen when the ITelephony interface is not up yet.
1725                 return NETWORK_TYPE_UNKNOWN;
1726             }
1727         } catch(RemoteException ex) {
1728             // This shouldn't happen in the normal case
1729             return NETWORK_TYPE_UNKNOWN;
1730         } catch (NullPointerException ex) {
1731             // This could happen before phone restarts due to crashing
1732             return NETWORK_TYPE_UNKNOWN;
1733         }
1734     }
1735
1736     /**
1737      * Returns a constant indicating the radio technology (network type)
1738      * currently in use on the device for a subscription.
1739      * @return the network type
1740      *
1741      * @param subId for which network type is returned
1742      *
1743      * @see #NETWORK_TYPE_UNKNOWN
1744      * @see #NETWORK_TYPE_GPRS
1745      * @see #NETWORK_TYPE_EDGE
1746      * @see #NETWORK_TYPE_UMTS
1747      * @see #NETWORK_TYPE_HSDPA
1748      * @see #NETWORK_TYPE_HSUPA
1749      * @see #NETWORK_TYPE_HSPA
1750      * @see #NETWORK_TYPE_CDMA
1751      * @see #NETWORK_TYPE_EVDO_0
1752      * @see #NETWORK_TYPE_EVDO_A
1753      * @see #NETWORK_TYPE_EVDO_B
1754      * @see #NETWORK_TYPE_1xRTT
1755      * @see #NETWORK_TYPE_IDEN
1756      * @see #NETWORK_TYPE_LTE
1757      * @see #NETWORK_TYPE_EHRPD
1758      * @see #NETWORK_TYPE_HSPAP
1759      *
1760      * @hide
1761      */
1762     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1763    public int getNetworkType(int subId) {
1764        try {
1765            ITelephony telephony = getITelephony();
1766            if (telephony != null) {
1767                return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName());
1768            } else {
1769                // This can happen when the ITelephony interface is not up yet.
1770                return NETWORK_TYPE_UNKNOWN;
1771            }
1772        } catch(RemoteException ex) {
1773            // This shouldn't happen in the normal case
1774            return NETWORK_TYPE_UNKNOWN;
1775        } catch (NullPointerException ex) {
1776            // This could happen before phone restarts due to crashing
1777            return NETWORK_TYPE_UNKNOWN;
1778        }
1779    }
1780
1781     /**
1782      * Returns a constant indicating the radio technology (network type)
1783      * currently in use on the device for data transmission.
1784      *
1785      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
1786      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
1787      *
1788      * @return the network type
1789      *
1790      * @see #NETWORK_TYPE_UNKNOWN
1791      * @see #NETWORK_TYPE_GPRS
1792      * @see #NETWORK_TYPE_EDGE
1793      * @see #NETWORK_TYPE_UMTS
1794      * @see #NETWORK_TYPE_HSDPA
1795      * @see #NETWORK_TYPE_HSUPA
1796      * @see #NETWORK_TYPE_HSPA
1797      * @see #NETWORK_TYPE_CDMA
1798      * @see #NETWORK_TYPE_EVDO_0
1799      * @see #NETWORK_TYPE_EVDO_A
1800      * @see #NETWORK_TYPE_EVDO_B
1801      * @see #NETWORK_TYPE_1xRTT
1802      * @see #NETWORK_TYPE_IDEN
1803      * @see #NETWORK_TYPE_LTE
1804      * @see #NETWORK_TYPE_EHRPD
1805      * @see #NETWORK_TYPE_HSPAP
1806      */
1807     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1808     public int getDataNetworkType() {
1809         return getDataNetworkType(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
1810     }
1811
1812     /**
1813      * Returns a constant indicating the radio technology (network type)
1814      * currently in use on the device for data transmission for a subscription
1815      * @return the network type
1816      *
1817      * @param subId for which network type is returned
1818      * @hide
1819      */
1820     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1821     public int getDataNetworkType(int subId) {
1822         try{
1823             ITelephony telephony = getITelephony();
1824             if (telephony != null) {
1825                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName());
1826             } else {
1827                 // This can happen when the ITelephony interface is not up yet.
1828                 return NETWORK_TYPE_UNKNOWN;
1829             }
1830         } catch(RemoteException ex) {
1831             // This shouldn't happen in the normal case
1832             return NETWORK_TYPE_UNKNOWN;
1833         } catch (NullPointerException ex) {
1834             // This could happen before phone restarts due to crashing
1835             return NETWORK_TYPE_UNKNOWN;
1836         }
1837     }
1838
1839     /**
1840      * Returns the NETWORK_TYPE_xxxx for voice
1841      */
1842     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1843     public int getVoiceNetworkType() {
1844         return getVoiceNetworkType(getSubId());
1845     }
1846
1847     /**
1848      * Returns the NETWORK_TYPE_xxxx for voice for a subId
1849      * @hide
1850      */
1851     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1852     public int getVoiceNetworkType(int subId) {
1853         try{
1854             ITelephony telephony = getITelephony();
1855             if (telephony != null) {
1856                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName());
1857             } else {
1858                 // This can happen when the ITelephony interface is not up yet.
1859                 return NETWORK_TYPE_UNKNOWN;
1860             }
1861         } catch(RemoteException ex) {
1862             // This shouldn't happen in the normal case
1863             return NETWORK_TYPE_UNKNOWN;
1864         } catch (NullPointerException ex) {
1865             // This could happen before phone restarts due to crashing
1866             return NETWORK_TYPE_UNKNOWN;
1867         }
1868     }
1869
1870     /**
1871      * Network Class Definitions.
1872      * Do not change this order, it is used for sorting during emergency calling in
1873      * {@link TelephonyConnectionService#getFirstPhoneForEmergencyCall()}. Any newer technologies
1874      * should be added after the current definitions.
1875      */
1876     /** Unknown network class. {@hide} */
1877     public static final int NETWORK_CLASS_UNKNOWN = 0;
1878     /** Class of broadly defined "2G" networks. {@hide} */
1879     public static final int NETWORK_CLASS_2_G = 1;
1880     /** Class of broadly defined "3G" networks. {@hide} */
1881     public static final int NETWORK_CLASS_3_G = 2;
1882     /** Class of broadly defined "4G" networks. {@hide} */
1883     public static final int NETWORK_CLASS_4_G = 3;
1884
1885     /**
1886      * Return general class of network type, such as "3G" or "4G". In cases
1887      * where classification is contentious, this method is conservative.
1888      *
1889      * @hide
1890      */
1891     public static int getNetworkClass(int networkType) {
1892         switch (networkType) {
1893             case NETWORK_TYPE_GPRS:
1894             case NETWORK_TYPE_GSM:
1895             case NETWORK_TYPE_EDGE:
1896             case NETWORK_TYPE_CDMA:
1897             case NETWORK_TYPE_1xRTT:
1898             case NETWORK_TYPE_IDEN:
1899                 return NETWORK_CLASS_2_G;
1900             case NETWORK_TYPE_UMTS:
1901             case NETWORK_TYPE_EVDO_0:
1902             case NETWORK_TYPE_EVDO_A:
1903             case NETWORK_TYPE_HSDPA:
1904             case NETWORK_TYPE_HSUPA:
1905             case NETWORK_TYPE_HSPA:
1906             case NETWORK_TYPE_EVDO_B:
1907             case NETWORK_TYPE_EHRPD:
1908             case NETWORK_TYPE_HSPAP:
1909             case NETWORK_TYPE_TD_SCDMA:
1910                 return NETWORK_CLASS_3_G;
1911             case NETWORK_TYPE_LTE:
1912             case NETWORK_TYPE_IWLAN:
1913             case NETWORK_TYPE_LTE_CA:
1914                 return NETWORK_CLASS_4_G;
1915             default:
1916                 return NETWORK_CLASS_UNKNOWN;
1917         }
1918     }
1919
1920     /**
1921      * Returns a string representation of the radio technology (network type)
1922      * currently in use on the device.
1923      * @return the name of the radio technology
1924      *
1925      * @hide pending API council review
1926      */
1927     public String getNetworkTypeName() {
1928         return getNetworkTypeName(getNetworkType());
1929     }
1930
1931     /**
1932      * Returns a string representation of the radio technology (network type)
1933      * currently in use on the device.
1934      * @param subId for which network type is returned
1935      * @return the name of the radio technology
1936      *
1937      */
1938     /** {@hide} */
1939     public static String getNetworkTypeName(int type) {
1940         switch (type) {
1941             case NETWORK_TYPE_GPRS:
1942                 return "GPRS";
1943             case NETWORK_TYPE_EDGE:
1944                 return "EDGE";
1945             case NETWORK_TYPE_UMTS:
1946                 return "UMTS";
1947             case NETWORK_TYPE_HSDPA:
1948                 return "HSDPA";
1949             case NETWORK_TYPE_HSUPA:
1950                 return "HSUPA";
1951             case NETWORK_TYPE_HSPA:
1952                 return "HSPA";
1953             case NETWORK_TYPE_CDMA:
1954                 return "CDMA";
1955             case NETWORK_TYPE_EVDO_0:
1956                 return "CDMA - EvDo rev. 0";
1957             case NETWORK_TYPE_EVDO_A:
1958                 return "CDMA - EvDo rev. A";
1959             case NETWORK_TYPE_EVDO_B:
1960                 return "CDMA - EvDo rev. B";
1961             case NETWORK_TYPE_1xRTT:
1962                 return "CDMA - 1xRTT";
1963             case NETWORK_TYPE_LTE:
1964                 return "LTE";
1965             case NETWORK_TYPE_EHRPD:
1966                 return "CDMA - eHRPD";
1967             case NETWORK_TYPE_IDEN:
1968                 return "iDEN";
1969             case NETWORK_TYPE_HSPAP:
1970                 return "HSPA+";
1971             case NETWORK_TYPE_GSM:
1972                 return "GSM";
1973             case NETWORK_TYPE_TD_SCDMA:
1974                 return "TD_SCDMA";
1975             case NETWORK_TYPE_IWLAN:
1976                 return "IWLAN";
1977             case NETWORK_TYPE_LTE_CA:
1978                 return "LTE_CA";
1979             default:
1980                 return "UNKNOWN";
1981         }
1982     }
1983
1984     //
1985     //
1986     // SIM Card
1987     //
1988     //
1989
1990     /**
1991      * SIM card state: Unknown. Signifies that the SIM is in transition
1992      * between states. For example, when the user inputs the SIM pin
1993      * under PIN_REQUIRED state, a query for sim status returns
1994      * this state before turning to SIM_STATE_READY.
1995      *
1996      * These are the ordinal value of IccCardConstants.State.
1997      */
1998     public static final int SIM_STATE_UNKNOWN = 0;
1999     /** SIM card state: no SIM card is available in the device */
2000     public static final int SIM_STATE_ABSENT = 1;
2001     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
2002     public static final int SIM_STATE_PIN_REQUIRED = 2;
2003     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
2004     public static final int SIM_STATE_PUK_REQUIRED = 3;
2005     /** SIM card state: Locked: requires a network PIN to unlock */
2006     public static final int SIM_STATE_NETWORK_LOCKED = 4;
2007     /** SIM card state: Ready */
2008     public static final int SIM_STATE_READY = 5;
2009     /** SIM card state: SIM Card is NOT READY */
2010     public static final int SIM_STATE_NOT_READY = 6;
2011     /** SIM card state: SIM Card Error, permanently disabled */
2012     public static final int SIM_STATE_PERM_DISABLED = 7;
2013     /** SIM card state: SIM Card Error, present but faulty */
2014     public static final int SIM_STATE_CARD_IO_ERROR = 8;
2015     /** SIM card state: SIM Card restricted, present but not usable due to
2016      * carrier restrictions.
2017      */
2018     public static final int SIM_STATE_CARD_RESTRICTED = 9;
2019
2020     /**
2021      * @return true if a ICC card is present
2022      */
2023     public boolean hasIccCard() {
2024         return hasIccCard(getSlotIndex());
2025     }
2026
2027     /**
2028      * @return true if a ICC card is present for a subscription
2029      *
2030      * @param slotIndex for which icc card presence is checked
2031      */
2032     /** {@hide} */
2033     // FIXME Input argument slotIndex should be of type int
2034     public boolean hasIccCard(int slotIndex) {
2035
2036         try {
2037             ITelephony telephony = getITelephony();
2038             if (telephony == null)
2039                 return false;
2040             return telephony.hasIccCardUsingSlotIndex(slotIndex);
2041         } catch (RemoteException ex) {
2042             // Assume no ICC card if remote exception which shouldn't happen
2043             return false;
2044         } catch (NullPointerException ex) {
2045             // This could happen before phone restarts due to crashing
2046             return false;
2047         }
2048     }
2049
2050     /**
2051      * Returns a constant indicating the state of the default SIM card.
2052      *
2053      * @see #SIM_STATE_UNKNOWN
2054      * @see #SIM_STATE_ABSENT
2055      * @see #SIM_STATE_PIN_REQUIRED
2056      * @see #SIM_STATE_PUK_REQUIRED
2057      * @see #SIM_STATE_NETWORK_LOCKED
2058      * @see #SIM_STATE_READY
2059      * @see #SIM_STATE_NOT_READY
2060      * @see #SIM_STATE_PERM_DISABLED
2061      * @see #SIM_STATE_CARD_IO_ERROR
2062      * @see #SIM_STATE_CARD_RESTRICTED
2063      */
2064     public int getSimState() {
2065         int slotIndex = getSlotIndex();
2066         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
2067         // sim state
2068         if (slotIndex < 0) {
2069             // query for all slots and return absent if all sim states are absent, otherwise
2070             // return unknown
2071             for (int i = 0; i < getPhoneCount(); i++) {
2072                 int simState = getSimState(i);
2073                 if (simState != SIM_STATE_ABSENT) {
2074                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
2075                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
2076                     return SIM_STATE_UNKNOWN;
2077                 }
2078             }
2079             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
2080                     "state as absent");
2081             return SIM_STATE_ABSENT;
2082         }
2083         return getSimState(slotIndex);
2084     }
2085
2086     /**
2087      * Returns a constant indicating the state of the device SIM card in a slot.
2088      *
2089      * @param slotIndex
2090      *
2091      * @see #SIM_STATE_UNKNOWN
2092      * @see #SIM_STATE_ABSENT
2093      * @see #SIM_STATE_PIN_REQUIRED
2094      * @see #SIM_STATE_PUK_REQUIRED
2095      * @see #SIM_STATE_NETWORK_LOCKED
2096      * @see #SIM_STATE_READY
2097      * @see #SIM_STATE_NOT_READY
2098      * @see #SIM_STATE_PERM_DISABLED
2099      * @see #SIM_STATE_CARD_IO_ERROR
2100      * @see #SIM_STATE_CARD_RESTRICTED
2101      */
2102     public int getSimState(int slotIndex) {
2103         int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex);
2104         return simState;
2105     }
2106
2107     /**
2108      * Returns the MCC+MNC (mobile country code + mobile network code) of the
2109      * provider of the SIM. 5 or 6 decimal digits.
2110      * <p>
2111      * Availability: SIM state must be {@link #SIM_STATE_READY}
2112      *
2113      * @see #getSimState
2114      */
2115     public String getSimOperator() {
2116         return getSimOperatorNumeric();
2117     }
2118
2119     /**
2120      * Returns the MCC+MNC (mobile country code + mobile network code) of the
2121      * provider of the SIM. 5 or 6 decimal digits.
2122      * <p>
2123      * Availability: SIM state must be {@link #SIM_STATE_READY}
2124      *
2125      * @see #getSimState
2126      *
2127      * @param subId for which SimOperator is returned
2128      * @hide
2129      */
2130     public String getSimOperator(int subId) {
2131         return getSimOperatorNumeric(subId);
2132     }
2133
2134     /**
2135      * Returns the MCC+MNC (mobile country code + mobile network code) of the
2136      * provider of the SIM. 5 or 6 decimal digits.
2137      * <p>
2138      * Availability: SIM state must be {@link #SIM_STATE_READY}
2139      *
2140      * @see #getSimState
2141      * @hide
2142      */
2143     public String getSimOperatorNumeric() {
2144         int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2145         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
2146             subId = SubscriptionManager.getDefaultSmsSubscriptionId();
2147             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
2148                 subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
2149                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
2150                     subId = SubscriptionManager.getDefaultSubscriptionId();
2151                 }
2152             }
2153         }
2154         return getSimOperatorNumeric(subId);
2155     }
2156
2157     /**
2158      * Returns the MCC+MNC (mobile country code + mobile network code) of the
2159      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
2160      * <p>
2161      * Availability: SIM state must be {@link #SIM_STATE_READY}
2162      *
2163      * @see #getSimState
2164      *
2165      * @param subId for which SimOperator is returned
2166      * @hide
2167      */
2168     public String getSimOperatorNumeric(int subId) {
2169         int phoneId = SubscriptionManager.getPhoneId(subId);
2170         return getSimOperatorNumericForPhone(phoneId);
2171     }
2172
2173     /**
2174      * Returns the MCC+MNC (mobile country code + mobile network code) of the
2175      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
2176      * <p>
2177      *
2178      * @param phoneId for which SimOperator is returned
2179      * @hide
2180      */
2181     public String getSimOperatorNumericForPhone(int phoneId) {
2182         return getTelephonyProperty(phoneId,
2183                 TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, "");
2184     }
2185
2186     /**
2187      * Returns the Service Provider Name (SPN).
2188      * <p>
2189      * Availability: SIM state must be {@link #SIM_STATE_READY}
2190      *
2191      * @see #getSimState
2192      */
2193     public String getSimOperatorName() {
2194         return getSimOperatorNameForPhone(getPhoneId());
2195     }
2196
2197     /**
2198      * Returns the Service Provider Name (SPN).
2199      * <p>
2200      * Availability: SIM state must be {@link #SIM_STATE_READY}
2201      *
2202      * @see #getSimState
2203      *
2204      * @param subId for which SimOperatorName is returned
2205      * @hide
2206      */
2207     public String getSimOperatorName(int subId) {
2208         int phoneId = SubscriptionManager.getPhoneId(subId);
2209         return getSimOperatorNameForPhone(phoneId);
2210     }
2211
2212     /**
2213      * Returns the Service Provider Name (SPN).
2214      *
2215      * @hide
2216      */
2217     public String getSimOperatorNameForPhone(int phoneId) {
2218          return getTelephonyProperty(phoneId,
2219                 TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA, "");
2220     }
2221
2222     /**
2223      * Returns the ISO country code equivalent for the SIM provider's country code.
2224      */
2225     public String getSimCountryIso() {
2226         return getSimCountryIsoForPhone(getPhoneId());
2227     }
2228
2229     /**
2230      * Returns the ISO country code equivalent for the SIM provider's country code.
2231      *
2232      * @param subId for which SimCountryIso is returned
2233      * @hide
2234      */
2235     public String getSimCountryIso(int subId) {
2236         int phoneId = SubscriptionManager.getPhoneId(subId);
2237         return getSimCountryIsoForPhone(phoneId);
2238     }
2239
2240     /**
2241      * Returns the ISO country code equivalent for the SIM provider's country code.
2242      *
2243      * @hide
2244      */
2245     public String getSimCountryIsoForPhone(int phoneId) {
2246         return getTelephonyProperty(phoneId,
2247                 TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY, "");
2248     }
2249
2250     /**
2251      * Returns the serial number of the SIM, if applicable. Return null if it is
2252      * unavailable.
2253      */
2254     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2255     public String getSimSerialNumber() {
2256          return getSimSerialNumber(getSubId());
2257     }
2258
2259     /**
2260      * Returns the serial number for the given subscription, if applicable. Return null if it is
2261      * unavailable.
2262      * <p>
2263      * @param subId for which Sim Serial number is returned
2264      * @hide
2265      */
2266     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2267     public String getSimSerialNumber(int subId) {
2268         try {
2269             IPhoneSubInfo info = getSubscriberInfo();
2270             if (info == null)
2271                 return null;
2272             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName());
2273         } catch (RemoteException ex) {
2274             return null;
2275         } catch (NullPointerException ex) {
2276             // This could happen before phone restarts due to crashing
2277             return null;
2278         }
2279     }
2280
2281     /**
2282      * Return if the current radio is LTE on CDMA. This
2283      * is a tri-state return value as for a period of time
2284      * the mode may be unknown.
2285      *
2286      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
2287      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
2288      *
2289      * @hide
2290      */
2291     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2292     public int getLteOnCdmaMode() {
2293         return getLteOnCdmaMode(getSubId());
2294     }
2295
2296     /**
2297      * Return if the current radio is LTE on CDMA for Subscription. This
2298      * is a tri-state return value as for a period of time
2299      * the mode may be unknown.
2300      *
2301      * @param subId for which radio is LTE on CDMA is returned
2302      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
2303      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
2304      * @hide
2305      */
2306     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2307     public int getLteOnCdmaMode(int subId) {
2308         try {
2309             ITelephony telephony = getITelephony();
2310             if (telephony == null)
2311                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
2312             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName());
2313         } catch (RemoteException ex) {
2314             // Assume no ICC card if remote exception which shouldn't happen
2315             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
2316         } catch (NullPointerException ex) {
2317             // This could happen before phone restarts due to crashing
2318             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
2319         }
2320     }
2321
2322     //
2323     //
2324     // Subscriber Info
2325     //
2326     //
2327
2328     /**
2329      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
2330      * Return null if it is unavailable.
2331      */
2332     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2333     public String getSubscriberId() {
2334         return getSubscriberId(getSubId());
2335     }
2336
2337     /**
2338      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
2339      * for a subscription.
2340      * Return null if it is unavailable.
2341      *
2342      * @param subId whose subscriber id is returned
2343      * @hide
2344      */
2345     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2346     public String getSubscriberId(int subId) {
2347         try {
2348             IPhoneSubInfo info = getSubscriberInfo();
2349             if (info == null)
2350                 return null;
2351             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName());
2352         } catch (RemoteException ex) {
2353             return null;
2354         } catch (NullPointerException ex) {
2355             // This could happen before phone restarts due to crashing
2356             return null;
2357         }
2358     }
2359
2360     /**
2361      * Returns Carrier specific information that will be used to encrypt the IMSI and IMPI.
2362      * This includes the public key and the key identifier. For multi-sim devices, if no subId
2363      * has been specified, we will return the value for the dafault data sim.
2364      * Return null if it is unavailable.
2365      * <p>
2366      * Requires Permission:
2367      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2368      * @param keyType whether the key is being used for wlan or epdg. Valid key types are
2369      *        {@link TelephonyManager#KEY_TYPE_EPDG} or
2370      *        {@link TelephonyManager#KEY_TYPE_WLAN}.
2371      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
2372      *         IMSI and IMPI. This includes the public key and the key identifier. This information
2373      *         will be stored in the device keystore. The system will return a null when no key was
2374      *         found, and the carrier does not require a key. The system will throw the following
2375      *         exceptions:
2376      *         1. IllegalArgumentException when an invalid key is sent.
2377      *         2. RuntimeException if the key is required but not found; and also if there was an
2378      *         internal exception.
2379      * @hide
2380      */
2381     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(int keyType) {
2382         try {
2383             IPhoneSubInfo info = getSubscriberInfo();
2384             if (info == null) {
2385                 throw new RuntimeException("IMSI error: Subscriber Info is null");
2386             }
2387             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
2388             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
2389                 throw new IllegalArgumentException("IMSI error: Invalid key type");
2390             }
2391             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
2392                     subId, keyType, mContext.getOpPackageName());
2393             if (imsiEncryptionInfo  == null
2394                     && isImsiEncryptionRequired(subId, keyType)) {
2395                 Rlog.e(TAG, "IMSI error: key is required but not found");
2396                 throw new RuntimeException("IMSI error: key is required but not found");
2397             }
2398             return imsiEncryptionInfo;
2399         } catch (RemoteException ex) {
2400             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
2401             throw new RuntimeException("IMSI error: Remote Exception");
2402         } catch (NullPointerException ex) {
2403             // This could happen before phone restarts due to crashing
2404             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
2405             throw new RuntimeException("IMSI error: Null Pointer exception");
2406         }
2407     }
2408
2409    /**
2410      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
2411      * @param keyType the key type which is being checked. (WLAN, EPDG)
2412      * @return true if the digit at position keyType is 1, else false.
2413      * @hide
2414      */
2415     private static boolean isKeyEnabled(int keyAvailability, int keyType) {
2416         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
2417         return (returnValue == 1) ? true : false;
2418     }
2419
2420     /**
2421      * If Carrier requires Imsi to be encrypted.
2422      * @hide
2423      */
2424     private boolean isImsiEncryptionRequired(int subId, int keyType) {
2425         CarrierConfigManager configManager =
2426                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
2427         if (configManager == null) {
2428             return false;
2429         }
2430         PersistableBundle pb = configManager.getConfigForSubId(subId);
2431         if (pb == null) {
2432             return false;
2433         }
2434         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
2435         return isKeyEnabled(keyAvailability, keyType);
2436     }
2437
2438     /**
2439      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
2440      * This includes the public key and the key identifier. This information will be stored in the
2441      * device keystore.
2442      * <p>
2443      * Requires Permission:
2444      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2445      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
2446      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
2447      *        The keyIdentifier Attribute value pair that helps a server locate
2448      *        the private key to decrypt the permanent identity. This field is
2449      *        optional and if it is present then it’s always separated from encrypted
2450      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
2451      *        with “name=value” format.
2452      * @hide
2453      */
2454     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
2455         try {
2456             IPhoneSubInfo info = getSubscriberInfo();
2457             if (info == null) return;
2458             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
2459                     imsiEncryptionInfo);
2460         } catch (NullPointerException ex) {
2461             // This could happen before phone restarts due to crashing
2462             return;
2463         } catch (RemoteException ex) {
2464             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
2465             return;
2466         }
2467     }
2468
2469     /**
2470      * Returns the Group Identifier Level1 for a GSM phone.
2471      * Return null if it is unavailable.
2472      */
2473     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2474     public String getGroupIdLevel1() {
2475         try {
2476             IPhoneSubInfo info = getSubscriberInfo();
2477             if (info == null)
2478                 return null;
2479             return info.getGroupIdLevel1(mContext.getOpPackageName());
2480         } catch (RemoteException ex) {
2481             return null;
2482         } catch (NullPointerException ex) {
2483             // This could happen before phone restarts due to crashing
2484             return null;
2485         }
2486     }
2487
2488     /**
2489      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
2490      * Return null if it is unavailable.
2491      *
2492      * @param subId whose subscriber id is returned
2493      * @hide
2494      */
2495     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2496     public String getGroupIdLevel1(int subId) {
2497         try {
2498             IPhoneSubInfo info = getSubscriberInfo();
2499             if (info == null)
2500                 return null;
2501             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName());
2502         } catch (RemoteException ex) {
2503             return null;
2504         } catch (NullPointerException ex) {
2505             // This could happen before phone restarts due to crashing
2506             return null;
2507         }
2508     }
2509
2510     /**
2511      * Returns the phone number string for line 1, for example, the MSISDN
2512      * for a GSM phone. Return null if it is unavailable.
2513      * <p>
2514      * The default SMS app can also use this.
2515      */
2516     @RequiresPermission(anyOf = {
2517             android.Manifest.permission.READ_PHONE_STATE,
2518             android.Manifest.permission.READ_SMS,
2519             android.Manifest.permission.READ_PHONE_NUMBERS
2520     })
2521     public String getLine1Number() {
2522         return getLine1Number(getSubId());
2523     }
2524
2525     /**
2526      * Returns the phone number string for line 1, for example, the MSISDN
2527      * for a GSM phone for a particular subscription. Return null if it is unavailable.
2528      * <p>
2529      * The default SMS app can also use this.
2530      *
2531      * @param subId whose phone number for line 1 is returned
2532      * @hide
2533      */
2534     @RequiresPermission(anyOf = {
2535             android.Manifest.permission.READ_PHONE_STATE,
2536             android.Manifest.permission.READ_SMS,
2537             android.Manifest.permission.READ_PHONE_NUMBERS
2538     })
2539     public String getLine1Number(int subId) {
2540         String number = null;
2541         try {
2542             ITelephony telephony = getITelephony();
2543             if (telephony != null)
2544                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName());
2545         } catch (RemoteException ex) {
2546         } catch (NullPointerException ex) {
2547         }
2548         if (number != null) {
2549             return number;
2550         }
2551         try {
2552             IPhoneSubInfo info = getSubscriberInfo();
2553             if (info == null)
2554                 return null;
2555             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName());
2556         } catch (RemoteException ex) {
2557             return null;
2558         } catch (NullPointerException ex) {
2559             // This could happen before phone restarts due to crashing
2560             return null;
2561         }
2562     }
2563
2564     /**
2565      * Set the line 1 phone number string and its alphatag for the current ICCID
2566      * for display purpose only, for example, displayed in Phone Status. It won't
2567      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
2568      * value.
2569      *
2570      * <p>Requires that the calling app has carrier privileges.
2571      * @see #hasCarrierPrivileges
2572      *
2573      * @param alphaTag alpha-tagging of the dailing nubmer
2574      * @param number The dialing number
2575      * @return true if the operation was executed correctly.
2576      */
2577     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
2578         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
2579     }
2580
2581     /**
2582      * Set the line 1 phone number string and its alphatag for the current ICCID
2583      * for display purpose only, for example, displayed in Phone Status. It won't
2584      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
2585      * value.
2586      *
2587      * <p>Requires that the calling app has carrier privileges.
2588      * @see #hasCarrierPrivileges
2589      *
2590      * @param subId the subscriber that the alphatag and dialing number belongs to.
2591      * @param alphaTag alpha-tagging of the dailing nubmer
2592      * @param number The dialing number
2593      * @return true if the operation was executed correctly.
2594      * @hide
2595      */
2596     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
2597         try {
2598             ITelephony telephony = getITelephony();
2599             if (telephony != null)
2600                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
2601         } catch (RemoteException ex) {
2602         } catch (NullPointerException ex) {
2603         }
2604         return false;
2605     }
2606
2607     /**
2608      * Returns the alphabetic identifier associated with the line 1 number.
2609      * Return null if it is unavailable.
2610      * @hide
2611      * nobody seems to call this.
2612      */
2613     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2614     public String getLine1AlphaTag() {
2615         return getLine1AlphaTag(getSubId());
2616     }
2617
2618     /**
2619      * Returns the alphabetic identifier associated with the line 1 number
2620      * for a subscription.
2621      * Return null if it is unavailable.
2622      * @param subId whose alphabetic identifier associated with line 1 is returned
2623      * nobody seems to call this.
2624      * @hide
2625      */
2626     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2627     public String getLine1AlphaTag(int subId) {
2628         String alphaTag = null;
2629         try {
2630             ITelephony telephony = getITelephony();
2631             if (telephony != null)
2632                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
2633                         getOpPackageName());
2634         } catch (RemoteException ex) {
2635         } catch (NullPointerException ex) {
2636         }
2637         if (alphaTag != null) {
2638             return alphaTag;
2639         }
2640         try {
2641             IPhoneSubInfo info = getSubscriberInfo();
2642             if (info == null)
2643                 return null;
2644             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName());
2645         } catch (RemoteException ex) {
2646             return null;
2647         } catch (NullPointerException ex) {
2648             // This could happen before phone restarts due to crashing
2649             return null;
2650         }
2651     }
2652
2653     /**
2654      * Return the set of subscriber IDs that should be considered as "merged
2655      * together" for data usage purposes. This is commonly {@code null} to
2656      * indicate no merging is required. Any returned subscribers are sorted in a
2657      * deterministic order.
2658      *
2659      * @hide
2660      */
2661     public @Nullable String[] getMergedSubscriberIds() {
2662         try {
2663             ITelephony telephony = getITelephony();
2664             if (telephony != null)
2665                 return telephony.getMergedSubscriberIds(getOpPackageName());
2666         } catch (RemoteException ex) {
2667         } catch (NullPointerException ex) {
2668         }
2669         return null;
2670     }
2671
2672     /**
2673      * Returns the MSISDN string.
2674      * for a GSM phone. Return null if it is unavailable.
2675      *
2676      * @hide
2677      */
2678     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2679     public String getMsisdn() {
2680         return getMsisdn(getSubId());
2681     }
2682
2683     /**
2684      * Returns the MSISDN string.
2685      * for a GSM phone. Return null if it is unavailable.
2686      *
2687      * @param subId for which msisdn is returned
2688      * @hide
2689      */
2690     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2691     public String getMsisdn(int subId) {
2692         try {
2693             IPhoneSubInfo info = getSubscriberInfo();
2694             if (info == null)
2695                 return null;
2696             return info.getMsisdnForSubscriber(subId, getOpPackageName());
2697         } catch (RemoteException ex) {
2698             return null;
2699         } catch (NullPointerException ex) {
2700             // This could happen before phone restarts due to crashing
2701             return null;
2702         }
2703     }
2704
2705     /**
2706      * Returns the voice mail number. Return null if it is unavailable.
2707      */
2708     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2709     public String getVoiceMailNumber() {
2710         return getVoiceMailNumber(getSubId());
2711     }
2712
2713     /**
2714      * Returns the voice mail number for a subscription.
2715      * Return null if it is unavailable.
2716      * @param subId whose voice mail number is returned
2717      * @hide
2718      */
2719     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2720     public String getVoiceMailNumber(int subId) {
2721         try {
2722             IPhoneSubInfo info = getSubscriberInfo();
2723             if (info == null)
2724                 return null;
2725             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName());
2726         } catch (RemoteException ex) {
2727             return null;
2728         } catch (NullPointerException ex) {
2729             // This could happen before phone restarts due to crashing
2730             return null;
2731         }
2732     }
2733
2734     /**
2735      * Returns the complete voice mail number. Return null if it is unavailable.
2736      *
2737      * @hide
2738      */
2739     @RequiresPermission(android.Manifest.permission.CALL_PRIVILEGED)
2740     public String getCompleteVoiceMailNumber() {
2741         return getCompleteVoiceMailNumber(getSubId());
2742     }
2743
2744     /**
2745      * Returns the complete voice mail number. Return null if it is unavailable.
2746      *
2747      * @param subId
2748      * @hide
2749      */
2750     @RequiresPermission(android.Manifest.permission.CALL_PRIVILEGED)
2751     public String getCompleteVoiceMailNumber(int subId) {
2752         try {
2753             IPhoneSubInfo info = getSubscriberInfo();
2754             if (info == null)
2755                 return null;
2756             return info.getCompleteVoiceMailNumberForSubscriber(subId);
2757         } catch (RemoteException ex) {
2758             return null;
2759         } catch (NullPointerException ex) {
2760             // This could happen before phone restarts due to crashing
2761             return null;
2762         }
2763     }
2764
2765     /**
2766      * Sets the voice mail number.
2767      *
2768      * <p>Requires that the calling app has carrier privileges.
2769      * @see #hasCarrierPrivileges
2770      *
2771      * @param alphaTag The alpha tag to display.
2772      * @param number The voicemail number.
2773      */
2774     public boolean setVoiceMailNumber(String alphaTag, String number) {
2775         return setVoiceMailNumber(getSubId(), alphaTag, number);
2776     }
2777
2778     /**
2779      * Sets the voicemail number for the given subscriber.
2780      *
2781      * <p>Requires that the calling app has carrier privileges.
2782      * @see #hasCarrierPrivileges
2783      *
2784      * @param subId The subscription id.
2785      * @param alphaTag The alpha tag to display.
2786      * @param number The voicemail number.
2787      * @hide
2788      */
2789     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
2790         try {
2791             ITelephony telephony = getITelephony();
2792             if (telephony != null)
2793                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
2794         } catch (RemoteException ex) {
2795         } catch (NullPointerException ex) {
2796         }
2797         return false;
2798     }
2799
2800     /**
2801      * Enables or disables the visual voicemail client for a phone account.
2802      *
2803      * <p>Requires that the calling app is the default dialer, or has carrier privileges, or
2804      * has permission {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
2805      * @see #hasCarrierPrivileges
2806      *
2807      * @param phoneAccountHandle the phone account to change the client state
2808      * @param enabled the new state of the client
2809      * @hide
2810      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
2811      * be implemented instead.
2812      */
2813     @SystemApi
2814     @SuppressLint("Doclava125")
2815     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
2816     }
2817
2818     /**
2819      * Returns whether the visual voicemail client is enabled.
2820      *
2821      * @param phoneAccountHandle the phone account to check for.
2822      * @return {@code true} when the visual voicemail client is enabled for this client
2823      * @hide
2824      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
2825      * be implemented instead.
2826      */
2827     @SystemApi
2828     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2829     @SuppressLint("Doclava125")
2830     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
2831         return false;
2832     }
2833
2834     /**
2835      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
2836      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
2837      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
2838      * voicemail client in telephony.
2839      *
2840      * <p>Requires the caller to be the system dialer.
2841      *
2842      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
2843      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
2844      *
2845      * @hide
2846      */
2847     @SystemApi
2848     @SuppressLint("Doclava125")
2849     @Nullable
2850     public Bundle getVisualVoicemailSettings(){
2851         try {
2852             ITelephony telephony = getITelephony();
2853             if (telephony != null) {
2854                 return telephony
2855                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
2856             }
2857         } catch (RemoteException ex) {
2858         } catch (NullPointerException ex) {
2859         }
2860         return null;
2861     }
2862
2863     /**
2864      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
2865      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
2866      * processing visual voicemail for the subscription.
2867      *
2868      * @see #createForSubscriptionId(int)
2869      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2870      * @see VisualVoicemailService
2871      */
2872     @Nullable
2873     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2874     public String getVisualVoicemailPackageName() {
2875         try {
2876             ITelephony telephony = getITelephony();
2877             if (telephony != null) {
2878                 return telephony
2879                         .getVisualVoicemailPackageName(mContext.getOpPackageName(), getSubId());
2880             }
2881         } catch (RemoteException ex) {
2882         } catch (NullPointerException ex) {
2883         }
2884         return null;
2885     }
2886
2887     /**
2888      * Set the visual voicemail SMS filter settings for the subscription ID pinned
2889      * to the TelephonyManager.
2890      * When the filter is enabled, {@link
2891      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
2892      * called when a SMS matching the settings is received. The caller should have
2893      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} and implement a
2894      * VisualVoicemailService.
2895      *
2896      * <p>Requires Permission:
2897      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2898      *
2899      * @param settings The settings for the filter, or {@code null} to disable the filter.
2900      */
2901     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
2902         if (settings == null) {
2903             disableVisualVoicemailSmsFilter(mSubId);
2904         } else {
2905             enableVisualVoicemailSmsFilter(mSubId, settings);
2906         }
2907     }
2908
2909     /**
2910      * Send a visual voicemail SMS. The caller must be the current default dialer.
2911      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
2912      * visual voicemail server.  Some examples for carriers using the OMTP standard include
2913      * activating and deactivating visual voicemail, or requesting the current visual voicemail
2914      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
2915      * format of these SMS messages.
2916      *
2917      * <p>Requires Permission:
2918      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
2919      *
2920      * @param number The destination number.
2921      * @param port The destination port for data SMS, or 0 for text SMS.
2922      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
2923      * @param sentIntent The sent intent passed to the {@link SmsManager}
2924      *
2925      * @throws SecurityException if the caller is not the current default dialer
2926      *
2927      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
2928      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
2929      */
2930     public void sendVisualVoicemailSms(String number, int port, String text,
2931             PendingIntent sentIntent) {
2932         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
2933     }
2934
2935     /**
2936      * Enables the visual voicemail SMS filter for a phone account. When the filter is
2937      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
2938      * visual voicemail client with
2939      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
2940      *
2941      * <p>This takes effect only when the caller is the default dialer. The enabled status and
2942      * settings persist through default dialer changes, but the filter will only honor the setting
2943      * set by the current default dialer.
2944      *
2945      *
2946      * @param subId The subscription id of the phone account.
2947      * @param settings The settings for the filter.
2948      */
2949     /** @hide */
2950     public void enableVisualVoicemailSmsFilter(int subId,
2951             VisualVoicemailSmsFilterSettings settings) {
2952         if(settings == null){
2953             throw new IllegalArgumentException("Settings cannot be null");
2954         }
2955         try {
2956             ITelephony telephony = getITelephony();
2957             if (telephony != null) {
2958                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
2959                         settings);
2960             }
2961         } catch (RemoteException ex) {
2962         } catch (NullPointerException ex) {
2963         }
2964     }
2965
2966     /**
2967      * Disables the visual voicemail SMS filter for a phone account.
2968      *
2969      * <p>This takes effect only when the caller is the default dialer. The enabled status and
2970      * settings persist through default dialer changes, but the filter will only honor the setting
2971      * set by the current default dialer.
2972      */
2973     /** @hide */
2974     public void disableVisualVoicemailSmsFilter(int subId) {
2975         try {
2976             ITelephony telephony = getITelephony();
2977             if (telephony != null) {
2978                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
2979             }
2980         } catch (RemoteException ex) {
2981         } catch (NullPointerException ex) {
2982         }
2983     }
2984
2985     /**
2986      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
2987      * if the filter is disabled.
2988      *
2989      * <p>This takes effect only when the caller is the default dialer. The enabled status and
2990      * settings persist through default dialer changes, but the filter will only honor the setting
2991      * set by the current default dialer.
2992      */
2993     /** @hide */
2994     @Nullable
2995     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
2996         try {
2997             ITelephony telephony = getITelephony();
2998             if (telephony != null) {
2999                 return telephony
3000                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
3001             }
3002         } catch (RemoteException ex) {
3003         } catch (NullPointerException ex) {
3004         }
3005
3006         return null;
3007     }
3008
3009     /**
3010      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
3011      * current active visual voicemail client, or {@code null} if the filter is disabled.
3012      *
3013      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
3014      */
3015     /** @hide */
3016     @Nullable
3017     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
3018         try {
3019             ITelephony telephony = getITelephony();
3020             if (telephony != null) {
3021                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
3022             }
3023         } catch (RemoteException ex) {
3024         } catch (NullPointerException ex) {
3025         }
3026
3027         return null;
3028     }
3029
3030     /**
3031      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
3032      *
3033      * @param phoneAccountHandle The account to send the SMS with.
3034      * @param number The destination number.
3035      * @param port The destination port for data SMS, or 0 for text SMS.
3036      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
3037      * @param sentIntent The sent intent passed to the {@link SmsManager}
3038      *
3039      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
3040      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
3041      *
3042      * @hide
3043      */
3044     @RequiresPermission(android.Manifest.permission.SEND_SMS)
3045     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
3046             String text, PendingIntent sentIntent) {
3047         try {
3048             ITelephony telephony = getITelephony();
3049             if (telephony != null) {
3050                 telephony.sendVisualVoicemailSmsForSubscriber(
3051                         mContext.getOpPackageName(), subId, number, port, text, sentIntent);
3052             }
3053         } catch (RemoteException ex) {
3054         }
3055     }
3056
3057     /**
3058      * Initial SIM activation state, unknown. Not set by any carrier apps.
3059      * @hide
3060      */
3061     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
3062
3063     /**
3064      * indicate SIM is under activation procedure now.
3065      * intermediate state followed by another state update with activation procedure result:
3066      * @see #SIM_ACTIVATION_STATE_ACTIVATED
3067      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
3068      * @see #SIM_ACTIVATION_STATE_RESTRICTED
3069      * @hide
3070      */
3071     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
3072
3073     /**
3074      * Indicate SIM has been successfully activated with full service
3075      * @hide
3076      */
3077     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
3078
3079     /**
3080      * Indicate SIM has been deactivated by the carrier so that service is not available
3081      * and requires activation service to enable services.
3082      * Carrier apps could be signalled to set activation state to deactivated if detected
3083      * deactivated sim state and set it back to activated after successfully run activation service.
3084      * @hide
3085      */
3086     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
3087
3088     /**
3089      * Restricted state indicate SIM has been activated but service are restricted.
3090      * note this is currently available for data activation state. For example out of byte sim.
3091      * @hide
3092      */
3093     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
3094
3095     /**
3096      * Sets the voice activation state for the given subscriber.
3097      *
3098      * <p>Requires Permission:
3099      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3100      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3101      *
3102      * @param subId The subscription id.
3103      * @param activationState The voice activation state of the given subscriber.
3104      * @see #SIM_ACTIVATION_STATE_UNKNOWN
3105      * @see #SIM_ACTIVATION_STATE_ACTIVATING
3106      * @see #SIM_ACTIVATION_STATE_ACTIVATED
3107      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
3108      * @hide
3109      */
3110     public void setVoiceActivationState(int subId, int activationState) {
3111         try {
3112             ITelephony telephony = getITelephony();
3113             if (telephony != null)
3114                 telephony.setVoiceActivationState(subId, activationState);
3115         } catch (RemoteException ex) {
3116         } catch (NullPointerException ex) {
3117         }
3118     }
3119
3120     /**
3121      * Sets the data activation state for the given subscriber.
3122      *
3123      * <p>Requires Permission:
3124      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
3125      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3126      *
3127      * @param subId The subscription id.
3128      * @param activationState The data activation state of the given subscriber.
3129      * @see #SIM_ACTIVATION_STATE_UNKNOWN
3130      * @see #SIM_ACTIVATION_STATE_ACTIVATING
3131      * @see #SIM_ACTIVATION_STATE_ACTIVATED
3132      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
3133      * @see #SIM_ACTIVATION_STATE_RESTRICTED
3134      * @hide
3135      */
3136     public void setDataActivationState(int subId, int activationState) {
3137         try {
3138             ITelephony telephony = getITelephony();
3139             if (telephony != null)
3140                 telephony.setDataActivationState(subId, activationState);
3141         } catch (RemoteException ex) {
3142         } catch (NullPointerException ex) {
3143         }
3144     }
3145
3146     /**
3147      * Returns the voice activation state for the given subscriber.
3148      *
3149      * @param subId The subscription id.
3150      *
3151      * @return voiceActivationState for the given subscriber
3152      * @see #SIM_ACTIVATION_STATE_UNKNOWN
3153      * @see #SIM_ACTIVATION_STATE_ACTIVATING
3154      * @see #SIM_ACTIVATION_STATE_ACTIVATED
3155      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
3156      * @hide
3157      */
3158     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3159     public int getVoiceActivationState(int subId) {
3160         try {
3161             ITelephony telephony = getITelephony();
3162             if (telephony != null)
3163                 return telephony.getVoiceActivationState(subId, getOpPackageName());
3164         } catch (RemoteException ex) {
3165         } catch (NullPointerException ex) {
3166         }
3167         return SIM_ACTIVATION_STATE_UNKNOWN;
3168     }
3169
3170     /**
3171      * Returns the data activation state for the given subscriber.
3172      *
3173      * @param subId The subscription id.
3174      *
3175      * @return dataActivationState for the given subscriber
3176      * @see #SIM_ACTIVATION_STATE_UNKNOWN
3177      * @see #SIM_ACTIVATION_STATE_ACTIVATING
3178      * @see #SIM_ACTIVATION_STATE_ACTIVATED
3179      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
3180      * @see #SIM_ACTIVATION_STATE_RESTRICTED
3181      * @hide
3182      */
3183     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3184     public int getDataActivationState(int subId) {
3185         try {
3186             ITelephony telephony = getITelephony();
3187             if (telephony != null)
3188                 return telephony.getDataActivationState(subId, getOpPackageName());
3189         } catch (RemoteException ex) {
3190         } catch (NullPointerException ex) {
3191         }
3192         return SIM_ACTIVATION_STATE_UNKNOWN;
3193     }
3194
3195     /**
3196      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
3197      * but the count is unknown.
3198      * @hide
3199      */
3200     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3201     public int getVoiceMessageCount() {
3202         return getVoiceMessageCount(getSubId());
3203     }
3204
3205     /**
3206      * Returns the voice mail count for a subscription. Return 0 if unavailable.
3207      * @param subId whose voice message count is returned
3208      * @hide
3209      */
3210     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3211     public int getVoiceMessageCount(int subId) {
3212         try {
3213             ITelephony telephony = getITelephony();
3214             if (telephony == null)
3215                 return 0;
3216             return telephony.getVoiceMessageCountForSubscriber(subId);
3217         } catch (RemoteException ex) {
3218             return 0;
3219         } catch (NullPointerException ex) {
3220             // This could happen before phone restarts due to crashing
3221             return 0;
3222         }
3223     }
3224
3225     /**
3226      * Retrieves the alphabetic identifier associated with the voice
3227      * mail number.
3228      */
3229     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3230     public String getVoiceMailAlphaTag() {
3231         return getVoiceMailAlphaTag(getSubId());
3232     }
3233
3234     /**
3235      * Retrieves the alphabetic identifier associated with the voice
3236      * mail number for a subscription.
3237      * @param subId whose alphabetic identifier associated with the
3238      * voice mail number is returned
3239      * @hide
3240      */
3241     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3242     public String getVoiceMailAlphaTag(int subId) {
3243         try {
3244             IPhoneSubInfo info = getSubscriberInfo();
3245             if (info == null)
3246                 return null;
3247             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName());
3248         } catch (RemoteException ex) {
3249             return null;
3250         } catch (NullPointerException ex) {
3251             // This could happen before phone restarts due to crashing
3252             return null;
3253         }
3254     }
3255
3256     /**
3257      * Send the special dialer code. The IPC caller must be the current default dialer or has
3258      * carrier privileges.
3259      * @see #hasCarrierPrivileges
3260      *
3261      * @param inputCode The special dialer code to send
3262      *
3263      * @throws SecurityException if the caller does not have carrier privileges or is not the
3264      *         current default dialer
3265      *
3266      * @throws IllegalStateException if telephony service is unavailable.
3267      */
3268     public void sendDialerSpecialCode(String inputCode) {
3269         try {
3270             final ITelephony telephony = getITelephony();
3271             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
3272         } catch (RemoteException ex) {
3273             // This could happen if binder process crashes.
3274             ex.rethrowFromSystemServer();
3275         } catch (NullPointerException ex) {
3276             // This could happen before phone restarts due to crashing
3277             throw new IllegalStateException("Telephony service unavailable");
3278         }
3279     }
3280
3281     /**
3282      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
3283      * @return the IMPI, or null if not present or not loaded
3284      * @hide
3285      */
3286     public String getIsimImpi() {
3287         try {
3288             IPhoneSubInfo info = getSubscriberInfo();
3289             if (info == null)
3290                 return null;
3291             return info.getIsimImpi();
3292         } catch (RemoteException ex) {
3293             return null;
3294         } catch (NullPointerException ex) {
3295             // This could happen before phone restarts due to crashing
3296             return null;
3297         }
3298     }
3299
3300     /**
3301      * Returns the IMS home network domain name that was loaded from the ISIM.
3302      * @return the IMS domain name, or null if not present or not loaded
3303      * @hide
3304      */
3305     public String getIsimDomain() {
3306         try {
3307             IPhoneSubInfo info = getSubscriberInfo();
3308             if (info == null)
3309                 return null;
3310             return info.getIsimDomain();
3311         } catch (RemoteException ex) {
3312             return null;
3313         } catch (NullPointerException ex) {
3314             // This could happen before phone restarts due to crashing
3315             return null;
3316         }
3317     }
3318
3319     /**
3320      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
3321      * @return an array of IMPU strings, with one IMPU per string, or null if
3322      *      not present or not loaded
3323      * @hide
3324      */
3325     public String[] getIsimImpu() {
3326         try {
3327             IPhoneSubInfo info = getSubscriberInfo();
3328             if (info == null)
3329                 return null;
3330             return info.getIsimImpu();
3331         } catch (RemoteException ex) {
3332             return null;
3333         } catch (NullPointerException ex) {
3334             // This could happen before phone restarts due to crashing
3335             return null;
3336         }
3337     }
3338
3339    /**
3340     * @hide
3341     */
3342     private IPhoneSubInfo getSubscriberInfo() {
3343         // get it each time because that process crashes a lot
3344         return IPhoneSubInfo.Stub.asInterface(ServiceManager.getService("iphonesubinfo"));
3345     }
3346
3347     /** Device call state: No activity. */
3348     public static final int CALL_STATE_IDLE = 0;
3349     /** Device call state: Ringing. A new call arrived and is
3350      *  ringing or waiting. In the latter case, another call is
3351      *  already active. */
3352     public static final int CALL_STATE_RINGING = 1;
3353     /** Device call state: Off-hook. At least one call exists
3354       * that is dialing, active, or on hold, and no calls are ringing
3355       * or waiting. */
3356     public static final int CALL_STATE_OFFHOOK = 2;
3357
3358     /**
3359      * Returns one of the following constants that represents the current state of all
3360      * phone calls.
3361      *
3362      * {@link TelephonyManager#CALL_STATE_RINGING}
3363      * {@link TelephonyManager#CALL_STATE_OFFHOOK}
3364      * {@link TelephonyManager#CALL_STATE_IDLE}
3365      */
3366     public int getCallState() {
3367         try {
3368             ITelecomService telecom = getTelecomService();
3369             if (telecom != null) {
3370                 return telecom.getCallState();
3371             }
3372         } catch (RemoteException e) {
3373             Log.e(TAG, "Error calling ITelecomService#getCallState", e);
3374         }
3375         return CALL_STATE_IDLE;
3376     }
3377
3378     /**
3379      * Returns a constant indicating the call state (cellular) on the device
3380      * for a subscription.
3381      *
3382      * @param subId whose call state is returned
3383      * @hide
3384      */
3385     public int getCallState(int subId) {
3386         int phoneId = SubscriptionManager.getPhoneId(subId);
3387         return getCallStateForSlot(phoneId);
3388     }
3389
3390     /**
3391      * See getCallState.
3392      *
3393      * @hide
3394      */
3395     public int getCallStateForSlot(int slotIndex) {
3396         try {
3397             ITelephony telephony = getITelephony();
3398             if (telephony == null)
3399                 return CALL_STATE_IDLE;
3400             return telephony.getCallStateForSlot(slotIndex);
3401         } catch (RemoteException ex) {
3402             // the phone process is restarting.
3403             return CALL_STATE_IDLE;
3404         } catch (NullPointerException ex) {
3405           // the phone process is restarting.
3406           return CALL_STATE_IDLE;
3407         }
3408     }
3409
3410
3411     /** Data connection activity: No traffic. */
3412     public static final int DATA_ACTIVITY_NONE = 0x00000000;
3413     /** Data connection activity: Currently receiving IP PPP traffic. */
3414     public static final int DATA_ACTIVITY_IN = 0x00000001;
3415     /** Data connection activity: Currently sending IP PPP traffic. */
3416     public static final int DATA_ACTIVITY_OUT = 0x00000002;
3417     /** Data connection activity: Currently both sending and receiving
3418      *  IP PPP traffic. */
3419     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
3420     /**
3421      * Data connection is active, but physical link is down
3422      */
3423     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
3424
3425     /**
3426      * Returns a constant indicating the type of activity on a data connection
3427      * (cellular).
3428      *
3429      * @see #DATA_ACTIVITY_NONE
3430      * @see #DATA_ACTIVITY_IN
3431      * @see #DATA_ACTIVITY_OUT
3432      * @see #DATA_ACTIVITY_INOUT
3433      * @see #DATA_ACTIVITY_DORMANT
3434      */
3435     public int getDataActivity() {
3436         try {
3437             ITelephony telephony = getITelephony();
3438             if (telephony == null)
3439                 return DATA_ACTIVITY_NONE;
3440             return telephony.getDataActivity();
3441         } catch (RemoteException ex) {
3442             // the phone process is restarting.
3443             return DATA_ACTIVITY_NONE;
3444         } catch (NullPointerException ex) {
3445           // the phone process is restarting.
3446           return DATA_ACTIVITY_NONE;
3447       }
3448     }
3449
3450     /** Data connection state: Unknown.  Used before we know the state.
3451      * @hide
3452      */
3453     public static final int DATA_UNKNOWN        = -1;
3454     /** Data connection state: Disconnected. IP traffic not available. */
3455     public static final int DATA_DISCONNECTED   = 0;
3456     /** Data connection state: Currently setting up a data connection. */
3457     public static final int DATA_CONNECTING     = 1;
3458     /** Data connection state: Connected. IP traffic should be available. */
3459     public static final int DATA_CONNECTED      = 2;
3460     /** Data connection state: Suspended. The connection is up, but IP
3461      * traffic is temporarily unavailable. For example, in a 2G network,
3462      * data activity may be suspended when a voice call arrives. */
3463     public static final int DATA_SUSPENDED      = 3;
3464
3465     /**
3466      * Returns a constant indicating the current data connection state
3467      * (cellular).
3468      *
3469      * @see #DATA_DISCONNECTED
3470      * @see #DATA_CONNECTING
3471      * @see #DATA_CONNECTED
3472      * @see #DATA_SUSPENDED
3473      */
3474     public int getDataState() {
3475         try {
3476             ITelephony telephony = getITelephony();
3477             if (telephony == null)
3478                 return DATA_DISCONNECTED;
3479             return telephony.getDataState();
3480         } catch (RemoteException ex) {
3481             // the phone process is restarting.
3482             return DATA_DISCONNECTED;
3483         } catch (NullPointerException ex) {
3484             return DATA_DISCONNECTED;
3485         }
3486     }
3487
3488    /**
3489     * @hide
3490     */
3491     private ITelephony getITelephony() {
3492         return ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
3493     }
3494
3495     /**
3496     * @hide
3497     */
3498     private ITelecomService getTelecomService() {
3499         return ITelecomService.Stub.asInterface(ServiceManager.getService(Context.TELECOM_SERVICE));
3500     }
3501
3502     private ITelephonyRegistry getTelephonyRegistry() {
3503         return ITelephonyRegistry.Stub.asInterface(ServiceManager.getService("telephony.registry"));
3504     }
3505
3506     //
3507     //
3508     // PhoneStateListener
3509     //
3510     //
3511
3512     /**
3513      * Registers a listener object to receive notification of changes
3514      * in specified telephony states.
3515      * <p>
3516      * To register a listener, pass a {@link PhoneStateListener}
3517      * and specify at least one telephony state of interest in
3518      * the events argument.
3519      *
3520      * At registration, and when a specified telephony state
3521      * changes, the telephony manager invokes the appropriate
3522      * callback method on the listener object and passes the
3523      * current (updated) values.
3524      * <p>
3525      * To unregister a listener, pass the listener object and set the
3526      * events argument to
3527      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
3528      *
3529      * @param listener The {@link PhoneStateListener} object to register
3530      *                 (or unregister)
3531      * @param events The telephony state(s) of interest to the listener,
3532      *               as a bitwise-OR combination of {@link PhoneStateListener}
3533      *               LISTEN_ flags.
3534      */
3535     public void listen(PhoneStateListener listener, int events) {
3536         if (mContext == null) return;
3537         try {
3538             boolean notifyNow = (getITelephony() != null);
3539             // If the listener has not explicitly set the subId (for example, created with the
3540             // default constructor), replace the subId so it will listen to the account the
3541             // telephony manager is created with.
3542             if (listener.mSubId == null) {
3543                 listener.mSubId = mSubId;
3544             }
3545
3546             ITelephonyRegistry registry = getTelephonyRegistry();
3547             if (registry != null) {
3548                 registry.listenForSubscriber(listener.mSubId, getOpPackageName(),
3549                         listener.callback, events, notifyNow);
3550             } else {
3551                 Rlog.w(TAG, "telephony registry not ready.");
3552             }
3553         } catch (RemoteException ex) {
3554             // system process dead
3555         }
3556     }
3557
3558     /**
3559      * Returns the CDMA ERI icon index to display
3560      * @hide
3561      */
3562     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3563     public int getCdmaEriIconIndex() {
3564         return getCdmaEriIconIndex(getSubId());
3565     }
3566
3567     /**
3568      * Returns the CDMA ERI icon index to display for a subscription
3569      * @hide
3570      */
3571     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3572     public int getCdmaEriIconIndex(int subId) {
3573         try {
3574             ITelephony telephony = getITelephony();
3575             if (telephony == null)
3576                 return -1;
3577             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName());
3578         } catch (RemoteException ex) {
3579             // the phone process is restarting.
3580             return -1;
3581         } catch (NullPointerException ex) {
3582             return -1;
3583         }
3584     }
3585
3586     /**
3587      * Returns the CDMA ERI icon mode,
3588      * 0 - ON
3589      * 1 - FLASHING
3590      *
3591      * @hide
3592      */
3593     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3594     public int getCdmaEriIconMode() {
3595         return getCdmaEriIconMode(getSubId());
3596     }
3597
3598     /**
3599      * Returns the CDMA ERI icon mode for a subscription.
3600      * 0 - ON
3601      * 1 - FLASHING
3602      *
3603      * @hide
3604      */
3605     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3606     public int getCdmaEriIconMode(int subId) {
3607         try {
3608             ITelephony telephony = getITelephony();
3609             if (telephony == null)
3610                 return -1;
3611             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName());
3612         } catch (RemoteException ex) {
3613             // the phone process is restarting.
3614             return -1;
3615         } catch (NullPointerException ex) {
3616             return -1;
3617         }
3618     }
3619
3620     /**
3621      * Returns the CDMA ERI text,
3622      *
3623      * @hide
3624      */
3625     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3626     public String getCdmaEriText() {
3627         return getCdmaEriText(getSubId());
3628     }
3629
3630     /**
3631      * Returns the CDMA ERI text, of a subscription
3632      *
3633      * @hide
3634      */
3635     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3636     public String getCdmaEriText(int subId) {
3637         try {
3638             ITelephony telephony = getITelephony();
3639             if (telephony == null)
3640                 return null;
3641             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName());
3642         } catch (RemoteException ex) {
3643             // the phone process is restarting.
3644             return null;
3645         } catch (NullPointerException ex) {
3646             return null;
3647         }
3648     }
3649
3650     /**
3651      * @return true if the current device is "voice capable".
3652      * <p>
3653      * "Voice capable" means that this device supports circuit-switched
3654      * (i.e. voice) phone calls over the telephony network, and is allowed
3655      * to display the in-call UI while a cellular voice call is active.
3656      * This will be false on "data only" devices which can't make voice
3657      * calls and don't support any in-call UI.
3658      * <p>
3659      * Note: the meaning of this flag is subtly different from the
3660      * PackageManager.FEATURE_TELEPHONY system feature, which is available
3661      * on any device with a telephony radio, even if the device is
3662      * data-only.
3663      */
3664     public boolean isVoiceCapable() {
3665         if (mContext == null) return true;
3666         return mContext.getResources().getBoolean(
3667                 com.android.internal.R.bool.config_voice_capable);
3668     }
3669
3670     /**
3671      * @return true if the current device supports sms service.
3672      * <p>
3673      * If true, this means that the device supports both sending and
3674      * receiving sms via the telephony network.
3675      * <p>
3676      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
3677      *       disabled when device doesn't support sms.
3678      */
3679     public boolean isSmsCapable() {
3680         if (mContext == null) return true;
3681         return mContext.getResources().getBoolean(
3682                 com.android.internal.R.bool.config_sms_capable);
3683     }
3684
3685     /**
3686      * Returns all observed cell information from all radios on the
3687      * device including the primary and neighboring cells. Calling this method does
3688      * not trigger a call to {@link android.telephony.PhoneStateListener#onCellInfoChanged
3689      * onCellInfoChanged()}, or change the rate at which
3690      * {@link android.telephony.PhoneStateListener#onCellInfoChanged
3691      * onCellInfoChanged()} is called.
3692      *
3693      *<p>
3694      * The list can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
3695      * {@link android.telephony.CellInfoCdma CellInfoCdma},
3696      * {@link android.telephony.CellInfoLte CellInfoLte}, and
3697      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
3698      * On devices with multiple radios it is typical to see instances of
3699      * one or more of any these in the list. In addition, zero, one, or more
3700      * of the returned objects may be considered registered; that is, their
3701      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
3702      * methods may return true.
3703      *
3704      * <p>This method returns valid data for registered cells on devices with
3705      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY}. In cases where only
3706      * partial information is available for a particular CellInfo entry, unavailable fields
3707      * will be reported as Integer.MAX_VALUE. All reported cells will include at least a
3708      * valid set of technology-specific identification info and a power level measurement.
3709      *
3710      *<p>
3711      * This method is preferred over using {@link
3712      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
3713      * However, for older devices, <code>getAllCellInfo()</code> may return
3714      * null. In these cases, you should call {@link
3715      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}
3716      * instead.
3717      *
3718      * @return List of {@link android.telephony.CellInfo}; null if cell
3719      * information is unavailable.
3720      */
3721     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
3722     public List<CellInfo> getAllCellInfo() {
3723         try {
3724             ITelephony telephony = getITelephony();
3725             if (telephony == null)
3726                 return null;
3727             return telephony.getAllCellInfo(getOpPackageName());
3728         } catch (RemoteException ex) {
3729             return null;
3730         } catch (NullPointerException ex) {
3731             return null;
3732         }
3733     }
3734
3735     /**
3736      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
3737      * PhoneStateListener.onCellInfoChanged} will be invoked.
3738      *<p>
3739      * The default, 0, means invoke onCellInfoChanged when any of the reported
3740      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
3741      * A onCellInfoChanged.
3742      *<p>
3743      * @param rateInMillis the rate
3744      *
3745      * @hide
3746      */
3747     public void setCellInfoListRate(int rateInMillis) {
3748         try {
3749             ITelephony telephony = getITelephony();
3750             if (telephony != null)
3751                 telephony.setCellInfoListRate(rateInMillis);
3752         } catch (RemoteException ex) {
3753         } catch (NullPointerException ex) {
3754         }
3755     }
3756
3757     /**
3758      * Returns the MMS user agent.
3759      */
3760     public String getMmsUserAgent() {
3761         if (mContext == null) return null;
3762         return mContext.getResources().getString(
3763                 com.android.internal.R.string.config_mms_user_agent);
3764     }
3765
3766     /**
3767      * Returns the MMS user agent profile URL.
3768      */
3769     public String getMmsUAProfUrl() {
3770         if (mContext == null) return null;
3771         return mContext.getResources().getString(
3772                 com.android.internal.R.string.config_mms_user_agent_profile_url);
3773     }
3774
3775     /**
3776      * Opens a logical channel to the ICC card.
3777      *
3778      * Input parameters equivalent to TS 27.007 AT+CCHO command.
3779      *
3780      * <p>Requires Permission:
3781      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3782      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3783      *
3784      * @param AID Application id. See ETSI 102.221 and 101.220.
3785      * @return an IccOpenLogicalChannelResponse object.
3786      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
3787      */
3788     @Deprecated
3789     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
3790         return iccOpenLogicalChannel(getSubId(), AID, -1);
3791     }
3792
3793     /**
3794      * Opens a logical channel to the ICC card.
3795      *
3796      * Input parameters equivalent to TS 27.007 AT+CCHO command.
3797      *
3798      * <p>Requires Permission:
3799      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3800      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3801      *
3802      * @param AID Application id. See ETSI 102.221 and 101.220.
3803      * @param p2 P2 parameter (described in ISO 7816-4).
3804      * @return an IccOpenLogicalChannelResponse object.
3805      */
3806     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
3807         return iccOpenLogicalChannel(getSubId(), AID, p2);
3808     }
3809
3810     /**
3811      * Opens a logical channel to the ICC card.
3812      *
3813      * Input parameters equivalent to TS 27.007 AT+CCHO command.
3814      *
3815      * <p>Requires Permission:
3816      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3817      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3818      *
3819      * @param subId The subscription to use.
3820      * @param AID Application id. See ETSI 102.221 and 101.220.
3821      * @param p2 P2 parameter (described in ISO 7816-4).
3822      * @return an IccOpenLogicalChannelResponse object.
3823      * @hide
3824      */
3825     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
3826         try {
3827             ITelephony telephony = getITelephony();
3828             if (telephony != null)
3829                 return telephony.iccOpenLogicalChannel(subId, getOpPackageName(), AID, p2);
3830         } catch (RemoteException ex) {
3831         } catch (NullPointerException ex) {
3832         }
3833         return null;
3834     }
3835
3836     /**
3837      * Closes a previously opened logical channel to the ICC card.
3838      *
3839      * Input parameters equivalent to TS 27.007 AT+CCHC command.
3840      *
3841      * <p>Requires Permission:
3842      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3843      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3844      *
3845      * @param channel is the channel id to be closed as retruned by a successful
3846      *            iccOpenLogicalChannel.
3847      * @return true if the channel was closed successfully.
3848      */
3849     public boolean iccCloseLogicalChannel(int channel) {
3850         return iccCloseLogicalChannel(getSubId(), channel);
3851     }
3852
3853     /**
3854      * Closes a previously opened logical channel to the ICC card.
3855      *
3856      * Input parameters equivalent to TS 27.007 AT+CCHC command.
3857      *
3858      * <p>Requires Permission:
3859      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3860      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3861      *
3862      * @param subId The subscription to use.
3863      * @param channel is the channel id to be closed as retruned by a successful
3864      *            iccOpenLogicalChannel.
3865      * @return true if the channel was closed successfully.
3866      * @hide
3867      */
3868     public boolean iccCloseLogicalChannel(int subId, int channel) {
3869         try {
3870             ITelephony telephony = getITelephony();
3871             if (telephony != null)
3872                 return telephony.iccCloseLogicalChannel(subId, channel);
3873         } catch (RemoteException ex) {
3874         } catch (NullPointerException ex) {
3875         }
3876         return false;
3877     }
3878
3879     /**
3880      * Transmit an APDU to the ICC card over a logical channel.
3881      *
3882      * Input parameters equivalent to TS 27.007 AT+CGLA command.
3883      *
3884      * <p>Requires Permission:
3885      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3886      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3887      *
3888      * @param channel is the channel id to be closed as returned by a successful
3889      *            iccOpenLogicalChannel.
3890      * @param cla Class of the APDU command.
3891      * @param instruction Instruction of the APDU command.
3892      * @param p1 P1 value of the APDU command.
3893      * @param p2 P2 value of the APDU command.
3894      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
3895      *            is sent to the SIM.
3896      * @param data Data to be sent with the APDU.
3897      * @return The APDU response from the ICC card with the status appended at
3898      *            the end.
3899      */
3900     public String iccTransmitApduLogicalChannel(int channel, int cla,
3901             int instruction, int p1, int p2, int p3, String data) {
3902         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
3903                     instruction, p1, p2, p3, data);
3904     }
3905
3906     /**
3907      * Transmit an APDU to the ICC card over a logical channel.
3908      *
3909      * Input parameters equivalent to TS 27.007 AT+CGLA command.
3910      *
3911      * <p>Requires Permission:
3912      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3913      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3914      *
3915      * @param subId The subscription to use.
3916      * @param channel is the channel id to be closed as returned by a successful
3917      *            iccOpenLogicalChannel.
3918      * @param cla Class of the APDU command.
3919      * @param instruction Instruction of the APDU command.
3920      * @param p1 P1 value of the APDU command.
3921      * @param p2 P2 value of the APDU command.
3922      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
3923      *            is sent to the SIM.
3924      * @param data Data to be sent with the APDU.
3925      * @return The APDU response from the ICC card with the status appended at
3926      *            the end.
3927      * @hide
3928      */
3929     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
3930             int instruction, int p1, int p2, int p3, String data) {
3931         try {
3932             ITelephony telephony = getITelephony();
3933             if (telephony != null)
3934                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
3935                     instruction, p1, p2, p3, data);
3936         } catch (RemoteException ex) {
3937         } catch (NullPointerException ex) {
3938         }
3939         return "";
3940     }
3941
3942     /**
3943      * Transmit an APDU to the ICC card over the basic channel.
3944      *
3945      * Input parameters equivalent to TS 27.007 AT+CSIM command.
3946      *
3947      * <p>Requires Permission:
3948      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3949      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3950      *
3951      * @param cla Class of the APDU command.
3952      * @param instruction Instruction of the APDU command.
3953      * @param p1 P1 value of the APDU command.
3954      * @param p2 P2 value of the APDU command.
3955      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
3956      *            is sent to the SIM.
3957      * @param data Data to be sent with the APDU.
3958      * @return The APDU response from the ICC card with the status appended at
3959      *            the end.
3960      */
3961     public String iccTransmitApduBasicChannel(int cla,
3962             int instruction, int p1, int p2, int p3, String data) {
3963         return iccTransmitApduBasicChannel(getSubId(), cla,
3964                     instruction, p1, p2, p3, data);
3965     }
3966
3967     /**
3968      * Transmit an APDU to the ICC card over the basic channel.
3969      *
3970      * Input parameters equivalent to TS 27.007 AT+CSIM command.
3971      *
3972      * <p>Requires Permission:
3973      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
3974      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
3975      *
3976      * @param subId The subscription to use.
3977      * @param cla Class of the APDU command.
3978      * @param instruction Instruction of the APDU command.
3979      * @param p1 P1 value of the APDU command.
3980      * @param p2 P2 value of the APDU command.
3981      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
3982      *            is sent to the SIM.
3983      * @param data Data to be sent with the APDU.
3984      * @return The APDU response from the ICC card with the status appended at
3985      *            the end.
3986      * @hide
3987      */
3988     public String iccTransmitApduBasicChannel(int subId, int cla,
3989             int instruction, int p1, int p2, int p3, String data) {
3990         try {
3991             ITelephony telephony = getITelephony();
3992             if (telephony != null)
3993                 return telephony.iccTransmitApduBasicChannel(subId, cla,
3994                     instruction, p1, p2, p3, data);
3995         } catch (RemoteException ex) {
3996         } catch (NullPointerException ex) {
3997         }
3998         return "";
3999     }
4000
4001     /**
4002      * Returns the response APDU for a command APDU sent through SIM_IO.
4003      *
4004      * <p>Requires Permission:
4005      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4006      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4007      *
4008      * @param fileID
4009      * @param command
4010      * @param p1 P1 value of the APDU command.
4011      * @param p2 P2 value of the APDU command.
4012      * @param p3 P3 value of the APDU command.
4013      * @param filePath
4014      * @return The APDU response.
4015      */
4016     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
4017             String filePath) {
4018         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
4019     }
4020
4021     /**
4022      * Returns the response APDU for a command APDU sent through SIM_IO.
4023      *
4024      * <p>Requires Permission:
4025      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4026      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4027      *
4028      * @param subId The subscription to use.
4029      * @param fileID
4030      * @param command
4031      * @param p1 P1 value of the APDU command.
4032      * @param p2 P2 value of the APDU command.
4033      * @param p3 P3 value of the APDU command.
4034      * @param filePath
4035      * @return The APDU response.
4036      * @hide
4037      */
4038     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
4039             int p3, String filePath) {
4040         try {
4041             ITelephony telephony = getITelephony();
4042             if (telephony != null)
4043                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
4044         } catch (RemoteException ex) {
4045         } catch (NullPointerException ex) {
4046         }
4047         return null;
4048     }
4049
4050     /**
4051      * Send ENVELOPE to the SIM and return the response.
4052      *
4053      * <p>Requires Permission:
4054      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4055      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4056      *
4057      * @param content String containing SAT/USAT response in hexadecimal
4058      *                format starting with command tag. See TS 102 223 for
4059      *                details.
4060      * @return The APDU response from the ICC card in hexadecimal format
4061      *         with the last 4 bytes being the status word. If the command fails,
4062      *         returns an empty string.
4063      */
4064     public String sendEnvelopeWithStatus(String content) {
4065         return sendEnvelopeWithStatus(getSubId(), content);
4066     }
4067
4068     /**
4069      * Send ENVELOPE to the SIM and return the response.
4070      *
4071      * <p>Requires Permission:
4072      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4073      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4074      *
4075      * @param subId The subscription to use.
4076      * @param content String containing SAT/USAT response in hexadecimal
4077      *                format starting with command tag. See TS 102 223 for
4078      *                details.
4079      * @return The APDU response from the ICC card in hexadecimal format
4080      *         with the last 4 bytes being the status word. If the command fails,
4081      *         returns an empty string.
4082      * @hide
4083      */
4084     public String sendEnvelopeWithStatus(int subId, String content) {
4085         try {
4086             ITelephony telephony = getITelephony();
4087             if (telephony != null)
4088                 return telephony.sendEnvelopeWithStatus(subId, content);
4089         } catch (RemoteException ex) {
4090         } catch (NullPointerException ex) {
4091         }
4092         return "";
4093     }
4094
4095     /**
4096      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
4097      * Used for device configuration by some CDMA operators.
4098      * <p>
4099      * Requires Permission:
4100      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4101      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4102      *
4103      * @param itemID the ID of the item to read.
4104      * @return the NV item as a String, or null on any failure.
4105      *
4106      * @hide
4107      */
4108     public String nvReadItem(int itemID) {
4109         try {
4110             ITelephony telephony = getITelephony();
4111             if (telephony != null)
4112                 return telephony.nvReadItem(itemID);
4113         } catch (RemoteException ex) {
4114             Rlog.e(TAG, "nvReadItem RemoteException", ex);
4115         } catch (NullPointerException ex) {
4116             Rlog.e(TAG, "nvReadItem NPE", ex);
4117         }
4118         return "";
4119     }
4120
4121     /**
4122      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
4123      * Used for device configuration by some CDMA operators.
4124      * <p>
4125      * Requires Permission:
4126      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4127      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4128      *
4129      * @param itemID the ID of the item to read.
4130      * @param itemValue the value to write, as a String.
4131      * @return true on success; false on any failure.
4132      *
4133      * @hide
4134      */
4135     public boolean nvWriteItem(int itemID, String itemValue) {
4136         try {
4137             ITelephony telephony = getITelephony();
4138             if (telephony != null)
4139                 return telephony.nvWriteItem(itemID, itemValue);
4140         } catch (RemoteException ex) {
4141             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
4142         } catch (NullPointerException ex) {
4143             Rlog.e(TAG, "nvWriteItem NPE", ex);
4144         }
4145         return false;
4146     }
4147
4148     /**
4149      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
4150      * Used for device configuration by some CDMA operators.
4151      * <p>
4152      * Requires Permission:
4153      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4154      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4155      *
4156      * @param preferredRoamingList byte array containing the new PRL.
4157      * @return true on success; false on any failure.
4158      *
4159      * @hide
4160      */
4161     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
4162         try {
4163             ITelephony telephony = getITelephony();
4164             if (telephony != null)
4165                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
4166         } catch (RemoteException ex) {
4167             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
4168         } catch (NullPointerException ex) {
4169             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
4170         }
4171         return false;
4172     }
4173
4174     /**
4175      * Perform the specified type of NV config reset. The radio will be taken offline
4176      * and the device must be rebooted after the operation. Used for device
4177      * configuration by some CDMA operators.
4178      * <p>
4179      * Requires Permission:
4180      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4181      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4182      *
4183      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
4184      * @return true on success; false on any failure.
4185      *
4186      * @hide
4187      */
4188     public boolean nvResetConfig(int resetType) {
4189         try {
4190             ITelephony telephony = getITelephony();
4191             if (telephony != null)
4192                 return telephony.nvResetConfig(resetType);
4193         } catch (RemoteException ex) {
4194             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
4195         } catch (NullPointerException ex) {
4196             Rlog.e(TAG, "nvResetConfig NPE", ex);
4197         }
4198         return false;
4199     }
4200
4201     /**
4202      * Return an appropriate subscription ID for any situation.
4203      *
4204      * If this object has been created with {@link #createForSubscriptionId}, then the provided
4205      * subId is returned. Otherwise, the default subId will be returned.
4206      */
4207     private int getSubId() {
4208       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
4209         return mSubId;
4210       }
4211       return SubscriptionManager.getDefaultSubscriptionId();
4212     }
4213
4214     /**
4215      * Return an appropriate subscription ID for any situation.
4216      *
4217      * If this object has been created with {@link #createForSubscriptionId}, then the provided
4218      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
4219      * returned.
4220      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
4221      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
4222      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
4223      */
4224     private int getSubId(int preferredSubId) {
4225         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
4226             return mSubId;
4227         }
4228         return preferredSubId;
4229     }
4230
4231     /**
4232      * Return an appropriate phone ID for any situation.
4233      *
4234      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
4235      * associated with the provided subId is returned. Otherwise, the default phoneId associated
4236      * with the default subId will be returned.
4237      */
4238     private int getPhoneId() {
4239         return SubscriptionManager.getPhoneId(getSubId());
4240     }
4241
4242     /**
4243      * Return an appropriate phone ID for any situation.
4244      *
4245      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
4246      * associated with the provided subId is returned. Otherwise, return the phoneId associated
4247      * with the preferred subId based on caller's context.
4248      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
4249      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
4250      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
4251      */
4252     private int getPhoneId(int preferredSubId) {
4253         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
4254     }
4255
4256     /**
4257      * Return an appropriate slot index for any situation.
4258      *
4259      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
4260      * associated with the provided subId is returned. Otherwise, return the slot index associated
4261      * with the default subId.
4262      * If SIM is not inserted, return default SIM slot index.
4263      *
4264      * {@hide}
4265      */
4266     @VisibleForTesting
4267     public int getSlotIndex() {
4268         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
4269         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
4270             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
4271         }
4272         return slotIndex;
4273     }
4274
4275     /**
4276      * Sets the telephony property with the value specified.
4277      *
4278      * @hide
4279      */
4280     public static void setTelephonyProperty(int phoneId, String property, String value) {
4281         String propVal = "";
4282         String p[] = null;
4283         String prop = SystemProperties.get(property);
4284
4285         if (value == null) {
4286             value = "";
4287         }
4288
4289         if (prop != null) {
4290             p = prop.split(",");
4291         }
4292
4293         if (!SubscriptionManager.isValidPhoneId(phoneId)) {
4294             Rlog.d(TAG, "setTelephonyProperty: invalid phoneId=" + phoneId +
4295                     " property=" + property + " value: " + value + " prop=" + prop);
4296             return;
4297         }
4298
4299         for (int i = 0; i < phoneId; i++) {
4300             String str = "";
4301             if ((p != null) && (i < p.length)) {
4302                 str = p[i];
4303             }
4304             propVal = propVal + str + ",";
4305         }
4306
4307         propVal = propVal + value;
4308         if (p != null) {
4309             for (int i = phoneId + 1; i < p.length; i++) {
4310                 propVal = propVal + "," + p[i];
4311             }
4312         }
4313
4314         if (propVal.length() > SystemProperties.PROP_VALUE_MAX) {
4315             Rlog.d(TAG, "setTelephonyProperty: property too long phoneId=" + phoneId +
4316                     " property=" + property + " value: " + value + " propVal=" + propVal);
4317             return;
4318         }
4319
4320         Rlog.d(TAG, "setTelephonyProperty: success phoneId=" + phoneId +
4321                 " property=" + property + " value: " + value + " propVal=" + propVal);
4322         SystemProperties.set(property, propVal);
4323     }
4324
4325     /**
4326      * Convenience function for retrieving a value from the secure settings
4327      * value list as an integer.  Note that internally setting values are
4328      * always stored as strings; this function converts the string to an
4329      * integer for you.
4330      * <p>
4331      * This version does not take a default value.  If the setting has not
4332      * been set, or the string value is not a number,
4333      * it throws {@link SettingNotFoundException}.
4334      *
4335      * @param cr The ContentResolver to access.
4336      * @param name The name of the setting to retrieve.
4337      * @param index The index of the list
4338      *
4339      * @throws SettingNotFoundException Thrown if a setting by the given
4340      * name can't be found or the setting value is not an integer.
4341      *
4342      * @return The value at the given index of settings.
4343      * @hide
4344      */
4345     public static int getIntAtIndex(android.content.ContentResolver cr,
4346             String name, int index)
4347             throws android.provider.Settings.SettingNotFoundException {
4348         String v = android.provider.Settings.Global.getString(cr, name);
4349         if (v != null) {
4350             String valArray[] = v.split(",");
4351             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
4352                 try {
4353                     return Integer.parseInt(valArray[index]);
4354                 } catch (NumberFormatException e) {
4355                     //Log.e(TAG, "Exception while parsing Integer: ", e);
4356                 }
4357             }
4358         }
4359         throw new android.provider.Settings.SettingNotFoundException(name);
4360     }
4361
4362     /**
4363      * Convenience function for updating settings value as coma separated
4364      * integer values. This will either create a new entry in the table if the
4365      * given name does not exist, or modify the value of the existing row
4366      * with that name.  Note that internally setting values are always
4367      * stored as strings, so this function converts the given value to a
4368      * string before storing it.
4369      *
4370      * @param cr The ContentResolver to access.
4371      * @param name The name of the setting to modify.
4372      * @param index The index of the list
4373      * @param value The new value for the setting to be added to the list.
4374      * @return true if the value was set, false on database errors
4375      * @hide
4376      */
4377     public static boolean putIntAtIndex(android.content.ContentResolver cr,
4378             String name, int index, int value) {
4379         String data = "";
4380         String valArray[] = null;
4381         String v = android.provider.Settings.Global.getString(cr, name);
4382
4383         if (index == Integer.MAX_VALUE) {
4384             throw new RuntimeException("putIntAtIndex index == MAX_VALUE index=" + index);
4385         }
4386         if (index < 0) {
4387             throw new RuntimeException("putIntAtIndex index < 0 index=" + index);
4388         }
4389         if (v != null) {
4390             valArray = v.split(",");
4391         }
4392
4393         // Copy the elements from valArray till index
4394         for (int i = 0; i < index; i++) {
4395             String str = "";
4396             if ((valArray != null) && (i < valArray.length)) {
4397                 str = valArray[i];
4398             }
4399             data = data + str + ",";
4400         }
4401
4402         data = data + value;
4403
4404         // Copy the remaining elements from valArray if any.
4405         if (valArray != null) {
4406             for (int i = index+1; i < valArray.length; i++) {
4407                 data = data + "," + valArray[i];
4408             }
4409         }
4410         return android.provider.Settings.Global.putString(cr, name, data);
4411     }
4412
4413     /**
4414      * Gets the telephony property.
4415      *
4416      * @hide
4417      */
4418     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
4419         String propVal = null;
4420         String prop = SystemProperties.get(property);
4421         if ((prop != null) && (prop.length() > 0)) {
4422             String values[] = prop.split(",");
4423             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
4424                 propVal = values[phoneId];
4425             }
4426         }
4427         return propVal == null ? defaultVal : propVal;
4428     }
4429
4430     /** @hide */
4431     public int getSimCount() {
4432         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
4433         // and then this method shouldn't be used at all!
4434         if(isMultiSimEnabled()) {
4435             return 2;
4436         } else {
4437             return 1;
4438         }
4439     }
4440
4441     /**
4442      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
4443      * @return IMS Service Table or null if not present or not loaded
4444      * @hide
4445      */
4446     public String getIsimIst() {
4447         try {
4448             IPhoneSubInfo info = getSubscriberInfo();
4449             if (info == null)
4450                 return null;
4451             return info.getIsimIst();
4452         } catch (RemoteException ex) {
4453             return null;
4454         } catch (NullPointerException ex) {
4455             // This could happen before phone restarts due to crashing
4456             return null;
4457         }
4458     }
4459
4460     /**
4461      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
4462      * @return an array of PCSCF strings with one PCSCF per string, or null if
4463      *         not present or not loaded
4464      * @hide
4465      */
4466     public String[] getIsimPcscf() {
4467         try {
4468             IPhoneSubInfo info = getSubscriberInfo();
4469             if (info == null)
4470                 return null;
4471             return info.getIsimPcscf();
4472         } catch (RemoteException ex) {
4473             return null;
4474         } catch (NullPointerException ex) {
4475             // This could happen before phone restarts due to crashing
4476             return null;
4477         }
4478     }
4479
4480     /**
4481      * Returns the response of ISIM Authetification through RIL.
4482      * Returns null if the Authentification hasn't been successed or isn't present iphonesubinfo.
4483      * @return the response of ISIM Authetification, or null if not available
4484      * @hide
4485      * @deprecated
4486      * @see getIccAuthentication with appType=PhoneConstants.APPTYPE_ISIM
4487      */
4488     public String getIsimChallengeResponse(String nonce){
4489         try {
4490             IPhoneSubInfo info = getSubscriberInfo();
4491             if (info == null)
4492                 return null;
4493             return info.getIsimChallengeResponse(nonce);
4494         } catch (RemoteException ex) {
4495             return null;
4496         } catch (NullPointerException ex) {
4497             // This could happen before phone restarts due to crashing
4498             return null;
4499         }
4500     }
4501
4502     // ICC SIM Application Types
4503     /** UICC application type is SIM */
4504     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
4505     /** UICC application type is USIM */
4506     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
4507     /** UICC application type is RUIM */
4508     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
4509     /** UICC application type is CSIM */
4510     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
4511     /** UICC application type is ISIM */
4512     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
4513     // authContext (parameter P2) when doing UICC challenge,
4514     // per 3GPP TS 31.102 (Section 7.1.2)
4515     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
4516     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
4517     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
4518     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
4519
4520     /**
4521      * Returns the response of authentication for the default subscription.
4522      * Returns null if the authentication hasn't been successful
4523      *
4524      * <p>Requires that the calling app has carrier privileges or READ_PRIVILEGED_PHONE_STATE
4525      * permission.
4526      *
4527      * @param appType the icc application type, like {@link #APPTYPE_USIM}
4528      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
4529      * {@link #AUTHTYPE_EAP_SIM}
4530      * @param data authentication challenge data, base64 encoded.
4531      * See 3GPP TS 31.102 7.1.2 for more details.
4532      * @return the response of authentication, or null if not available
4533      *
4534      * @see #hasCarrierPrivileges
4535      */
4536     public String getIccAuthentication(int appType, int authType, String data) {
4537         return getIccAuthentication(getSubId(), appType, authType, data);
4538     }
4539
4540     /**
4541      * Returns the response of USIM Authentication for specified subId.
4542      * Returns null if the authentication hasn't been successful
4543      *
4544      * <p>Requires that the calling app has carrier privileges.
4545      *
4546      * @param subId subscription ID used for authentication
4547      * @param appType the icc application type, like {@link #APPTYPE_USIM}
4548      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
4549      * {@link #AUTHTYPE_EAP_SIM}
4550      * @param data authentication challenge data, base64 encoded.
4551      * See 3GPP TS 31.102 7.1.2 for more details.
4552      * @return the response of authentication, or null if not available
4553      *
4554      * @see #hasCarrierPrivileges
4555      * @hide
4556      */
4557     public String getIccAuthentication(int subId, int appType, int authType, String data) {
4558         try {
4559             IPhoneSubInfo info = getSubscriberInfo();
4560             if (info == null)
4561                 return null;
4562             return info.getIccSimChallengeResponse(subId, appType, authType, data);
4563         } catch (RemoteException ex) {
4564             return null;
4565         } catch (NullPointerException ex) {
4566             // This could happen before phone starts
4567             return null;
4568         }
4569     }
4570
4571     /**
4572      * Returns an array of Forbidden PLMNs from the USIM App
4573      * Returns null if the query fails.
4574      *
4575      * @return an array of forbidden PLMNs or null if not available
4576      */
4577     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4578     public String[] getForbiddenPlmns() {
4579       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
4580     }
4581
4582     /**
4583      * Returns an array of Forbidden PLMNs from the specified SIM App
4584      * Returns null if the query fails.
4585      *
4586      * @param subId subscription ID used for authentication
4587      * @param appType the icc application type, like {@link #APPTYPE_USIM}
4588      * @return fplmns an array of forbidden PLMNs
4589      * @hide
4590      */
4591     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4592     public String[] getForbiddenPlmns(int subId, int appType) {
4593         try {
4594             ITelephony telephony = getITelephony();
4595             if (telephony == null)
4596                 return null;
4597             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName());
4598         } catch (RemoteException ex) {
4599             return null;
4600         } catch (NullPointerException ex) {
4601             // This could happen before phone starts
4602             return null;
4603         }
4604     }
4605
4606     /**
4607      * Get P-CSCF address from PCO after data connection is established or modified.
4608      * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN
4609      * @return array of P-CSCF address
4610      * @hide
4611      */
4612     public String[] getPcscfAddress(String apnType) {
4613         try {
4614             ITelephony telephony = getITelephony();
4615             if (telephony == null)
4616                 return new String[0];
4617             return telephony.getPcscfAddress(apnType, getOpPackageName());
4618         } catch (RemoteException e) {
4619             return new String[0];
4620         }
4621     }
4622
4623     /** @hide */
4624     @IntDef({ImsFeature.EMERGENCY_MMTEL, ImsFeature.MMTEL, ImsFeature.RCS})
4625     @Retention(RetentionPolicy.SOURCE)
4626     public @interface Feature {}
4627
4628     /**
4629      * Returns the {@link IImsServiceController} that corresponds to the given slot Id and IMS
4630      * feature or {@link null} if the service is not available. If an ImsServiceController is
4631      * available, the {@link IImsServiceFeatureListener} callback is registered as a listener for
4632      * feature updates.
4633      * @param slotIndex The SIM slot that we are requesting the {@link IImsServiceController} for.
4634      * @param feature The IMS Feature we are requesting, corresponding to {@link ImsFeature}.
4635      * @param callback Listener that will send updates to ImsManager when there are updates to
4636      * ImsServiceController.
4637      * @return {@link IImsServiceController} interface for the feature specified or {@link null} if
4638      * it is unavailable.
4639      * @hide
4640      */
4641     public IImsServiceController getImsServiceControllerAndListen(int slotIndex, @Feature int feature,
4642             IImsServiceFeatureListener callback) {
4643         try {
4644             ITelephony telephony = getITelephony();
4645             if (telephony != null) {
4646                 return telephony.getImsServiceControllerAndListen(slotIndex, feature, callback);
4647             }
4648         } catch (RemoteException e) {
4649             Rlog.e(TAG, "getImsServiceControllerAndListen, RemoteException: " + e.getMessage());
4650         }
4651         return null;
4652     }
4653
4654     /**
4655      * Set IMS registration state
4656      *
4657      * @param Registration state
4658      * @hide
4659      */
4660     public void setImsRegistrationState(boolean registered) {
4661         try {
4662             ITelephony telephony = getITelephony();
4663             if (telephony != null)
4664                 telephony.setImsRegistrationState(registered);
4665         } catch (RemoteException e) {
4666         }
4667     }
4668
4669     /**
4670      * Get the preferred network type.
4671      * Used for device configuration by some CDMA operators.
4672      * <p>
4673      * Requires Permission:
4674      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4675      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4676      *
4677      * @return the preferred network type, defined in RILConstants.java.
4678      * @hide
4679      */
4680     public int getPreferredNetworkType(int subId) {
4681         try {
4682             ITelephony telephony = getITelephony();
4683             if (telephony != null)
4684                 return telephony.getPreferredNetworkType(subId);
4685         } catch (RemoteException ex) {
4686             Rlog.e(TAG, "getPreferredNetworkType RemoteException", ex);
4687         } catch (NullPointerException ex) {
4688             Rlog.e(TAG, "getPreferredNetworkType NPE", ex);
4689         }
4690         return -1;
4691     }
4692
4693     /**
4694      * Sets the network selection mode to automatic.
4695      * <p>
4696      * Requires Permission:
4697      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4698      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4699      *
4700      * @hide
4701      * TODO: Add an overload that takes no args.
4702      */
4703     public void setNetworkSelectionModeAutomatic(int subId) {
4704         try {
4705             ITelephony telephony = getITelephony();
4706             if (telephony != null)
4707                 telephony.setNetworkSelectionModeAutomatic(subId);
4708         } catch (RemoteException ex) {
4709             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
4710         } catch (NullPointerException ex) {
4711             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
4712         }
4713     }
4714
4715     /**
4716      * Perform a radio scan and return the list of avialble networks.
4717      *
4718      * The return value is a list of the OperatorInfo of the networks found. Note that this
4719      * scan can take a long time (sometimes minutes) to happen.
4720      *
4721      * <p>
4722      * Requires Permission:
4723      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4724      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4725      *
4726      * @hide
4727      * TODO: Add an overload that takes no args.
4728      */
4729     public CellNetworkScanResult getCellNetworkScanResults(int subId) {
4730         try {
4731             ITelephony telephony = getITelephony();
4732             if (telephony != null)
4733                 return telephony.getCellNetworkScanResults(subId);
4734         } catch (RemoteException ex) {
4735             Rlog.e(TAG, "getCellNetworkScanResults RemoteException", ex);
4736         } catch (NullPointerException ex) {
4737             Rlog.e(TAG, "getCellNetworkScanResults NPE", ex);
4738         }
4739         return null;
4740     }
4741
4742     /**
4743      * Request a network scan.
4744      *
4745      * This method is asynchronous, so the network scan results will be returned by callback.
4746      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
4747      *
4748      * <p>
4749      * Requires Permission:
4750      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4751      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4752      *
4753      * @param request Contains all the RAT with bands/channels that need to be scanned.
4754      * @param callback Returns network scan results or errors.
4755      * @return A NetworkScan obj which contains a callback which can stop the scan.
4756      * @hide
4757      */
4758     public NetworkScan requestNetworkScan(
4759             NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
4760         synchronized (this) {
4761             if (mTelephonyScanManager == null) {
4762                 mTelephonyScanManager = new TelephonyScanManager();
4763             }
4764         }
4765         return mTelephonyScanManager.requestNetworkScan(getSubId(), request, callback);
4766     }
4767
4768     /**
4769      * Ask the radio to connect to the input network and change selection mode to manual.
4770      *
4771      * <p>
4772      * Requires Permission:
4773      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4774      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4775      *
4776      * @hide
4777      * TODO: Add an overload that takes no args.
4778      */
4779     public boolean setNetworkSelectionModeManual(int subId, OperatorInfo operator,
4780             boolean persistSelection) {
4781         try {
4782             ITelephony telephony = getITelephony();
4783             if (telephony != null)
4784                 return telephony.setNetworkSelectionModeManual(subId, operator, persistSelection);
4785         } catch (RemoteException ex) {
4786             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
4787         } catch (NullPointerException ex) {
4788             Rlog.e(TAG, "setNetworkSelectionModeManual NPE", ex);
4789         }
4790         return false;
4791     }
4792
4793     /**
4794      * Set the preferred network type.
4795      * Used for device configuration by some CDMA operators.
4796      * <p>
4797      * Requires Permission:
4798      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4799      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
4800      *
4801      * @param subId the id of the subscription to set the preferred network type for.
4802      * @param networkType the preferred network type, defined in RILConstants.java.
4803      * @return true on success; false on any failure.
4804      * @hide
4805      */
4806     public boolean setPreferredNetworkType(int subId, int networkType) {
4807         try {
4808             ITelephony telephony = getITelephony();
4809             if (telephony != null)
4810                 return telephony.setPreferredNetworkType(subId, networkType);
4811         } catch (RemoteException ex) {
4812             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
4813         } catch (NullPointerException ex) {
4814             Rlog.e(TAG, "setPreferredNetworkType NPE", ex);
4815         }
4816         return false;
4817     }
4818
4819     /**
4820      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
4821      *
4822      * <p>
4823      * Requires that the calling app has carrier privileges.
4824      * @see #hasCarrierPrivileges
4825      *
4826      * @return true on success; false on any failure.
4827      */
4828     public boolean setPreferredNetworkTypeToGlobal() {
4829         return setPreferredNetworkTypeToGlobal(getSubId());
4830     }
4831
4832     /**
4833      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
4834      *
4835      * <p>
4836      * Requires that the calling app has carrier privileges.
4837      * @see #hasCarrierPrivileges
4838      *
4839      * @return true on success; false on any failure.
4840      * @hide
4841      */
4842     public boolean setPreferredNetworkTypeToGlobal(int subId) {
4843         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
4844     }
4845
4846     /**
4847      * Check TETHER_DUN_REQUIRED and TETHER_DUN_APN settings, net.tethering.noprovisioning
4848      * SystemProperty, and config_tether_apndata to decide whether DUN APN is required for
4849      * tethering.
4850      *
4851      * @return 0: Not required. 1: required. 2: Not set.
4852      * @hide
4853      */
4854     public int getTetherApnRequired() {
4855         try {
4856             ITelephony telephony = getITelephony();
4857             if (telephony != null)
4858                 return telephony.getTetherApnRequired();
4859         } catch (RemoteException ex) {
4860             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
4861         } catch (NullPointerException ex) {
4862             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
4863         }
4864         return 2;
4865     }
4866
4867
4868     /**
4869      * Values used to return status for hasCarrierPrivileges call.
4870      */
4871     /** @hide */ @SystemApi
4872     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
4873     /** @hide */ @SystemApi
4874     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
4875     /** @hide */ @SystemApi
4876     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
4877     /** @hide */ @SystemApi
4878     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
4879
4880     /**
4881      * Has the calling application been granted carrier privileges by the carrier.
4882      *
4883      * If any of the packages in the calling UID has carrier privileges, the
4884      * call will return true. This access is granted by the owner of the UICC
4885      * card and does not depend on the registered carrier.
4886      *
4887      * @return true if the app has carrier privileges.
4888      */
4889     public boolean hasCarrierPrivileges() {
4890         return hasCarrierPrivileges(getSubId());
4891     }
4892
4893     /**
4894      * Has the calling application been granted carrier privileges by the carrier.
4895      *
4896      * If any of the packages in the calling UID has carrier privileges, the
4897      * call will return true. This access is granted by the owner of the UICC
4898      * card and does not depend on the registered carrier.
4899      *
4900      * @param subId The subscription to use.
4901      * @return true if the app has carrier privileges.
4902      * @hide
4903      */
4904     public boolean hasCarrierPrivileges(int subId) {
4905         try {
4906             ITelephony telephony = getITelephony();
4907             if (telephony != null) {
4908                 return telephony.getCarrierPrivilegeStatus(mSubId) ==
4909                     CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
4910             }
4911         } catch (RemoteException ex) {
4912             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
4913         } catch (NullPointerException ex) {
4914             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
4915         }
4916         return false;
4917     }
4918
4919     /**
4920      * Override the branding for the current ICCID.
4921      *
4922      * Once set, whenever the SIM is present in the device, the service
4923      * provider name (SPN) and the operator name will both be replaced by the
4924      * brand value input. To unset the value, the same function should be
4925      * called with a null brand value.
4926      *
4927      * <p>Requires that the calling app has carrier privileges.
4928      * @see #hasCarrierPrivileges
4929      *
4930      * @param brand The brand name to display/set.
4931      * @return true if the operation was executed correctly.
4932      */
4933     public boolean setOperatorBrandOverride(String brand) {
4934         return setOperatorBrandOverride(getSubId(), brand);
4935     }
4936
4937     /**
4938      * Override the branding for the current ICCID.
4939      *
4940      * Once set, whenever the SIM is present in the device, the service
4941      * provider name (SPN) and the operator name will both be replaced by the
4942      * brand value input. To unset the value, the same function should be
4943      * called with a null brand value.
4944      *
4945      * <p>Requires that the calling app has carrier privileges.
4946      * @see #hasCarrierPrivileges
4947      *
4948      * @param subId The subscription to use.
4949      * @param brand The brand name to display/set.
4950      * @return true if the operation was executed correctly.
4951      * @hide
4952      */
4953     public boolean setOperatorBrandOverride(int subId, String brand) {
4954         try {
4955             ITelephony telephony = getITelephony();
4956             if (telephony != null)
4957                 return telephony.setOperatorBrandOverride(subId, brand);
4958         } catch (RemoteException ex) {
4959             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
4960         } catch (NullPointerException ex) {
4961             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
4962         }
4963         return false;
4964     }
4965
4966     /**
4967      * Override the roaming preference for the current ICCID.
4968      *
4969      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
4970      * the platform's notion of a network operator being considered roaming or not.
4971      * The change only affects the ICCID that was active when this call was made.
4972      *
4973      * If null is passed as any of the input, the corresponding value is deleted.
4974      *
4975      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
4976      *
4977      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
4978      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
4979      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
4980      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
4981      * @return true if the operation was executed correctly.
4982      *
4983      * @hide
4984      */
4985     public boolean setRoamingOverride(List<String> gsmRoamingList,
4986             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
4987             List<String> cdmaNonRoamingList) {
4988         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
4989                 cdmaRoamingList, cdmaNonRoamingList);
4990     }
4991
4992     /**
4993      * Override the roaming preference for the current ICCID.
4994      *
4995      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
4996      * the platform's notion of a network operator being considered roaming or not.
4997      * The change only affects the ICCID that was active when this call was made.
4998      *
4999      * If null is passed as any of the input, the corresponding value is deleted.
5000      *
5001      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
5002      *
5003      * @param subId for which the roaming overrides apply.
5004      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
5005      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
5006      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
5007      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
5008      * @return true if the operation was executed correctly.
5009      *
5010      * @hide
5011      */
5012     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
5013             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
5014             List<String> cdmaNonRoamingList) {
5015         try {
5016             ITelephony telephony = getITelephony();
5017             if (telephony != null)
5018                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
5019                         cdmaRoamingList, cdmaNonRoamingList);
5020         } catch (RemoteException ex) {
5021             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
5022         } catch (NullPointerException ex) {
5023             Rlog.e(TAG, "setRoamingOverride NPE", ex);
5024         }
5025         return false;
5026     }
5027
5028     /**
5029      * Expose the rest of ITelephony to @SystemApi
5030      */
5031
5032     /** @hide */
5033     @SystemApi
5034     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5035     public String getCdmaMdn() {
5036         return getCdmaMdn(getSubId());
5037     }
5038
5039     /** @hide */
5040     @SystemApi
5041     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5042     public String getCdmaMdn(int subId) {
5043         try {
5044             ITelephony telephony = getITelephony();
5045             if (telephony == null)
5046                 return null;
5047             return telephony.getCdmaMdn(subId);
5048         } catch (RemoteException ex) {
5049             return null;
5050         } catch (NullPointerException ex) {
5051             return null;
5052         }
5053     }
5054
5055     /** @hide */
5056     @SystemApi
5057     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5058     public String getCdmaMin() {
5059         return getCdmaMin(getSubId());
5060     }
5061
5062     /** @hide */
5063     @SystemApi
5064     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5065     public String getCdmaMin(int subId) {
5066         try {
5067             ITelephony telephony = getITelephony();
5068             if (telephony == null)
5069                 return null;
5070             return telephony.getCdmaMin(subId);
5071         } catch (RemoteException ex) {
5072             return null;
5073         } catch (NullPointerException ex) {
5074             return null;
5075         }
5076     }
5077
5078     /** @hide */
5079     @SystemApi
5080     @SuppressLint("Doclava125")
5081     public int checkCarrierPrivilegesForPackage(String pkgName) {
5082         try {
5083             ITelephony telephony = getITelephony();
5084             if (telephony != null)
5085                 return telephony.checkCarrierPrivilegesForPackage(pkgName);
5086         } catch (RemoteException ex) {
5087             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
5088         } catch (NullPointerException ex) {
5089             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
5090         }
5091         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
5092     }
5093
5094     /** @hide */
5095     @SystemApi
5096     @SuppressLint("Doclava125")
5097     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
5098         try {
5099             ITelephony telephony = getITelephony();
5100             if (telephony != null)
5101                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
5102         } catch (RemoteException ex) {
5103             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
5104         } catch (NullPointerException ex) {
5105             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
5106         }
5107         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
5108     }
5109
5110     /** @hide */
5111     @SystemApi
5112     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
5113         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
5114     }
5115
5116     /** @hide */
5117     @SystemApi
5118     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
5119         try {
5120             ITelephony telephony = getITelephony();
5121             if (telephony != null)
5122                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
5123         } catch (RemoteException ex) {
5124             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
5125         } catch (NullPointerException ex) {
5126             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
5127         }
5128         return null;
5129     }
5130
5131     /** @hide */
5132     public List<String> getPackagesWithCarrierPrivileges() {
5133         try {
5134             ITelephony telephony = getITelephony();
5135             if (telephony != null) {
5136                 return telephony.getPackagesWithCarrierPrivileges();
5137             }
5138         } catch (RemoteException ex) {
5139             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
5140         } catch (NullPointerException ex) {
5141             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
5142         }
5143         return Collections.EMPTY_LIST;
5144     }
5145
5146     /** @hide */
5147     @SystemApi
5148     @SuppressLint("Doclava125")
5149     public void dial(String number) {
5150         try {
5151             ITelephony telephony = getITelephony();
5152             if (telephony != null)
5153                 telephony.dial(number);
5154         } catch (RemoteException e) {
5155             Log.e(TAG, "Error calling ITelephony#dial", e);
5156         }
5157     }
5158
5159     /** @hide */
5160     @SystemApi
5161     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
5162     public void call(String callingPackage, String number) {
5163         try {
5164             ITelephony telephony = getITelephony();
5165             if (telephony != null)
5166                 telephony.call(callingPackage, number);
5167         } catch (RemoteException e) {
5168             Log.e(TAG, "Error calling ITelephony#call", e);
5169         }
5170     }
5171
5172     /** @hide */
5173     @SystemApi
5174     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
5175     public boolean endCall() {
5176         try {
5177             ITelephony telephony = getITelephony();
5178             if (telephony != null)
5179                 return telephony.endCall();
5180         } catch (RemoteException e) {
5181             Log.e(TAG, "Error calling ITelephony#endCall", e);
5182         }
5183         return false;
5184     }
5185
5186     /** @hide */
5187     @SystemApi
5188     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5189     public void answerRingingCall() {
5190         try {
5191             ITelephony telephony = getITelephony();
5192             if (telephony != null)
5193                 telephony.answerRingingCall();
5194         } catch (RemoteException e) {
5195             Log.e(TAG, "Error calling ITelephony#answerRingingCall", e);
5196         }
5197     }
5198
5199     /** @hide */
5200     @SystemApi
5201     @SuppressLint("Doclava125")
5202     public void silenceRinger() {
5203         try {
5204             getTelecomService().silenceRinger(getOpPackageName());
5205         } catch (RemoteException e) {
5206             Log.e(TAG, "Error calling ITelecomService#silenceRinger", e);
5207         }
5208     }
5209
5210     /** @hide */
5211     @SystemApi
5212     @RequiresPermission(anyOf = {
5213             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
5214             android.Manifest.permission.READ_PHONE_STATE
5215     })
5216     public boolean isOffhook() {
5217         try {
5218             ITelephony telephony = getITelephony();
5219             if (telephony != null)
5220                 return telephony.isOffhook(getOpPackageName());
5221         } catch (RemoteException e) {
5222             Log.e(TAG, "Error calling ITelephony#isOffhook", e);
5223         }
5224         return false;
5225     }
5226
5227     /** @hide */
5228     @SystemApi
5229     @RequiresPermission(anyOf = {
5230             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
5231             android.Manifest.permission.READ_PHONE_STATE
5232     })
5233     public boolean isRinging() {
5234         try {
5235             ITelephony telephony = getITelephony();
5236             if (telephony != null)
5237                 return telephony.isRinging(getOpPackageName());
5238         } catch (RemoteException e) {
5239             Log.e(TAG, "Error calling ITelephony#isRinging", e);
5240         }
5241         return false;
5242     }
5243
5244     /** @hide */
5245     @SystemApi
5246     @RequiresPermission(anyOf = {
5247             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
5248             android.Manifest.permission.READ_PHONE_STATE
5249     })
5250     public boolean isIdle() {
5251         try {
5252             ITelephony telephony = getITelephony();
5253             if (telephony != null)
5254                 return telephony.isIdle(getOpPackageName());
5255         } catch (RemoteException e) {
5256             Log.e(TAG, "Error calling ITelephony#isIdle", e);
5257         }
5258         return true;
5259     }
5260
5261     /** @hide */
5262     @SystemApi
5263     @RequiresPermission(anyOf = {
5264             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
5265             android.Manifest.permission.READ_PHONE_STATE
5266     })
5267     public boolean isRadioOn() {
5268         try {
5269             ITelephony telephony = getITelephony();
5270             if (telephony != null)
5271                 return telephony.isRadioOn(getOpPackageName());
5272         } catch (RemoteException e) {
5273             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
5274         }
5275         return false;
5276     }
5277
5278     /** @hide */
5279     @SystemApi
5280     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5281     public boolean supplyPin(String pin) {
5282         try {
5283             ITelephony telephony = getITelephony();
5284             if (telephony != null)
5285                 return telephony.supplyPin(pin);
5286         } catch (RemoteException e) {
5287             Log.e(TAG, "Error calling ITelephony#supplyPin", e);
5288         }
5289         return false;
5290     }
5291
5292     /** @hide */
5293     @SystemApi
5294     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5295     public boolean supplyPuk(String puk, String pin) {
5296         try {
5297             ITelephony telephony = getITelephony();
5298             if (telephony != null)
5299                 return telephony.supplyPuk(puk, pin);
5300         } catch (RemoteException e) {
5301             Log.e(TAG, "Error calling ITelephony#supplyPuk", e);
5302         }
5303         return false;
5304     }
5305
5306     /** @hide */
5307     @SystemApi
5308     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5309     public int[] supplyPinReportResult(String pin) {
5310         try {
5311             ITelephony telephony = getITelephony();
5312             if (telephony != null)
5313                 return telephony.supplyPinReportResult(pin);
5314         } catch (RemoteException e) {
5315             Log.e(TAG, "Error calling ITelephony#supplyPinReportResult", e);
5316         }
5317         return new int[0];
5318     }
5319
5320     /** @hide */
5321     @SystemApi
5322     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5323     public int[] supplyPukReportResult(String puk, String pin) {
5324         try {
5325             ITelephony telephony = getITelephony();
5326             if (telephony != null)
5327                 return telephony.supplyPukReportResult(puk, pin);
5328         } catch (RemoteException e) {
5329             Log.e(TAG, "Error calling ITelephony#]", e);
5330         }
5331         return new int[0];
5332     }
5333
5334     /**
5335      * Used to notify callers of
5336      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
5337      * network either successfully executes a USSD request, or if there was a failure while
5338      * executing the request.
5339      * <p>
5340      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
5341      * USSD request has succeeded.
5342      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
5343      * USSD request has failed.
5344      */
5345     public static abstract class UssdResponseCallback {
5346        /**
5347         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
5348         * response received from the network.  The calling app can choose to either display the
5349         * response to the user or perform some operation based on the response.
5350         * <p>
5351         * USSD responses are unstructured text and their content is determined by the mobile network
5352         * operator.
5353         *
5354         * @param telephonyManager the TelephonyManager the callback is registered to.
5355         * @param request the USSD request sent to the mobile network.
5356         * @param response the response to the USSD request provided by the mobile network.
5357         **/
5358        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
5359                                          String request, CharSequence response) {};
5360
5361        /**
5362         * Called when a USSD request has failed to complete.
5363         *
5364         * @param telephonyManager the TelephonyManager the callback is registered to.
5365         * @param request the USSD request sent to the mobile network.
5366         * @param failureCode failure code indicating why the request failed.  Will be either
5367         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
5368         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
5369         **/
5370        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
5371                                                String request, int failureCode) {};
5372     }
5373
5374     /**
5375      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
5376      * informs the caller of the response via the supplied {@code callback}.
5377      * <p>Carriers define USSD codes which can be sent by the user to request information such as
5378      * the user's current data balance or minutes balance.
5379      * <p>Requires permission:
5380      * {@link android.Manifest.permission#CALL_PHONE}
5381      * @param ussdRequest the USSD command to be executed.
5382      * @param callback called by the framework to inform the caller of the result of executing the
5383      *                 USSD request (see {@link UssdResponseCallback}).
5384      * @param handler the {@link Handler} to run the request on.
5385      */
5386     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
5387     public void sendUssdRequest(String ussdRequest,
5388                                 final UssdResponseCallback callback, Handler handler) {
5389         checkNotNull(callback, "UssdResponseCallback cannot be null.");
5390         final TelephonyManager telephonyManager = this;
5391
5392         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
5393             @Override
5394             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
5395                 Rlog.d(TAG, "USSD:" + resultCode);
5396                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
5397                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE);
5398
5399                 if (resultCode == USSD_RETURN_SUCCESS) {
5400                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
5401                             response.getReturnMessage());
5402                 } else {
5403                     callback.onReceiveUssdResponseFailed(telephonyManager,
5404                             response.getUssdRequest(), resultCode);
5405                 }
5406             }
5407         };
5408
5409         try {
5410             ITelephony telephony = getITelephony();
5411             if (telephony != null) {
5412                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
5413             }
5414         } catch (RemoteException e) {
5415             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
5416             UssdResponse response = new UssdResponse(ussdRequest, "");
5417             Bundle returnData = new Bundle();
5418             returnData.putParcelable(USSD_RESPONSE, response);
5419             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
5420         }
5421     }
5422
5423     /**
5424      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
5425      * voice and data simultaneously. This can change based on location or network condition.
5426      *
5427      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
5428      */
5429     public boolean isConcurrentVoiceAndDataSupported() {
5430         try {
5431             ITelephony telephony = getITelephony();
5432             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
5433                     getSubId()));
5434         } catch (RemoteException e) {
5435             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
5436         }
5437         return false;
5438     }
5439
5440     /** @hide */
5441     @SystemApi
5442     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5443     public boolean handlePinMmi(String dialString) {
5444         try {
5445             ITelephony telephony = getITelephony();
5446             if (telephony != null)
5447                 return telephony.handlePinMmi(dialString);
5448         } catch (RemoteException e) {
5449             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
5450         }
5451         return false;
5452     }
5453
5454     /** @hide */
5455     @SystemApi
5456     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5457     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
5458         try {
5459             ITelephony telephony = getITelephony();
5460             if (telephony != null)
5461                 return telephony.handlePinMmiForSubscriber(subId, dialString);
5462         } catch (RemoteException e) {
5463             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
5464         }
5465         return false;
5466     }
5467
5468     /** @hide */
5469     @SystemApi
5470     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5471     public void toggleRadioOnOff() {
5472         try {
5473             ITelephony telephony = getITelephony();
5474             if (telephony != null)
5475                 telephony.toggleRadioOnOff();
5476         } catch (RemoteException e) {
5477             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
5478         }
5479     }
5480
5481     /** @hide */
5482     @SystemApi
5483     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5484     public boolean setRadio(boolean turnOn) {
5485         try {
5486             ITelephony telephony = getITelephony();
5487             if (telephony != null)
5488                 return telephony.setRadio(turnOn);
5489         } catch (RemoteException e) {
5490             Log.e(TAG, "Error calling ITelephony#setRadio", e);
5491         }
5492         return false;
5493     }
5494
5495     /** @hide */
5496     @SystemApi
5497     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5498     public boolean setRadioPower(boolean turnOn) {
5499         try {
5500             ITelephony telephony = getITelephony();
5501             if (telephony != null)
5502                 return telephony.setRadioPower(turnOn);
5503         } catch (RemoteException e) {
5504             Log.e(TAG, "Error calling ITelephony#setRadioPower", e);
5505         }
5506         return false;
5507     }
5508
5509     /** @hide */
5510     @SystemApi
5511     @SuppressLint("Doclava125")
5512     public void updateServiceLocation() {
5513         try {
5514             ITelephony telephony = getITelephony();
5515             if (telephony != null)
5516                 telephony.updateServiceLocation();
5517         } catch (RemoteException e) {
5518             Log.e(TAG, "Error calling ITelephony#updateServiceLocation", e);
5519         }
5520     }
5521
5522     /** @hide */
5523     @SystemApi
5524     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5525     public boolean enableDataConnectivity() {
5526         try {
5527             ITelephony telephony = getITelephony();
5528             if (telephony != null)
5529                 return telephony.enableDataConnectivity();
5530         } catch (RemoteException e) {
5531             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
5532         }
5533         return false;
5534     }
5535
5536     /** @hide */
5537     @SystemApi
5538     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5539     public boolean disableDataConnectivity() {
5540         try {
5541             ITelephony telephony = getITelephony();
5542             if (telephony != null)
5543                 return telephony.disableDataConnectivity();
5544         } catch (RemoteException e) {
5545             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
5546         }
5547         return false;
5548     }
5549
5550     /** @hide */
5551     @SystemApi
5552     public boolean isDataConnectivityPossible() {
5553         try {
5554             ITelephony telephony = getITelephony();
5555             if (telephony != null)
5556                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
5557                         .getDefaultDataSubscriptionId()));
5558         } catch (RemoteException e) {
5559             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
5560         }
5561         return false;
5562     }
5563
5564     /** @hide */
5565     @SystemApi
5566     public boolean needsOtaServiceProvisioning() {
5567         try {
5568             ITelephony telephony = getITelephony();
5569             if (telephony != null)
5570                 return telephony.needsOtaServiceProvisioning();
5571         } catch (RemoteException e) {
5572             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
5573         }
5574         return false;
5575     }
5576
5577     /**
5578      * Turns mobile data on or off.
5579      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
5580      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
5581      *
5582      * <p>Requires Permission:
5583      *     {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5584      *     calling app has carrier privileges.
5585      *
5586      * @param enable Whether to enable mobile data.
5587      *
5588      * @see #hasCarrierPrivileges
5589      */
5590     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5591     public void setDataEnabled(boolean enable) {
5592         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
5593     }
5594
5595     /** @hide */
5596     @SystemApi
5597     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5598     public void setDataEnabled(int subId, boolean enable) {
5599         try {
5600             Log.d(TAG, "setDataEnabled: enabled=" + enable);
5601             ITelephony telephony = getITelephony();
5602             if (telephony != null)
5603                 telephony.setDataEnabled(subId, enable);
5604         } catch (RemoteException e) {
5605             Log.e(TAG, "Error calling ITelephony#setDataEnabled", e);
5606         }
5607     }
5608
5609
5610     /**
5611      * @deprecated use {@link #isDataEnabled()} instead.
5612      * @hide
5613      */
5614     @SystemApi
5615     @Deprecated
5616     public boolean getDataEnabled() {
5617         return isDataEnabled();
5618     }
5619
5620     /**
5621      * Returns whether mobile data is enabled or not.
5622      *
5623      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
5624      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
5625      *
5626      * <p>Requires one of the following permissions:
5627      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE ACCESS_NETWORK_STATE},
5628      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}, or that the
5629      * calling app has carrier privileges.
5630      *
5631      * <p>Note that this does not take into account any data restrictions that may be present on the
5632      * calling app. Such restrictions may be inspected with
5633      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
5634      *
5635      * @return true if mobile data is enabled.
5636      *
5637      * @see #hasCarrierPrivileges
5638      */
5639     @SuppressWarnings("deprecation")
5640     public boolean isDataEnabled() {
5641         return getDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
5642     }
5643
5644     /**
5645      * @deprecated use {@link #isDataEnabled(int)} instead.
5646      * @hide
5647      */
5648     @SystemApi
5649     public boolean getDataEnabled(int subId) {
5650         boolean retVal = false;
5651         try {
5652             ITelephony telephony = getITelephony();
5653             if (telephony != null)
5654                 retVal = telephony.getDataEnabled(subId);
5655         } catch (RemoteException e) {
5656             Log.e(TAG, "Error calling ITelephony#getDataEnabled", e);
5657         } catch (NullPointerException e) {
5658         }
5659         return retVal;
5660     }
5661
5662     /**
5663      * Returns the result and response from RIL for oem request
5664      *
5665      * @param oemReq the data is sent to ril.
5666      * @param oemResp the respose data from RIL.
5667      * @return negative value request was not handled or get error
5668      *         0 request was handled succesfully, but no response data
5669      *         positive value success, data length of response
5670      * @hide
5671      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
5672      */
5673     @Deprecated
5674     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
5675         try {
5676             ITelephony telephony = getITelephony();
5677             if (telephony != null)
5678                 return telephony.invokeOemRilRequestRaw(oemReq, oemResp);
5679         } catch (RemoteException ex) {
5680         } catch (NullPointerException ex) {
5681         }
5682         return -1;
5683     }
5684
5685     /** @hide */
5686     @SystemApi
5687     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5688     public void enableVideoCalling(boolean enable) {
5689         try {
5690             ITelephony telephony = getITelephony();
5691             if (telephony != null)
5692                 telephony.enableVideoCalling(enable);
5693         } catch (RemoteException e) {
5694             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
5695         }
5696     }
5697
5698     /** @hide */
5699     @SystemApi
5700     @RequiresPermission(anyOf = {
5701             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
5702             android.Manifest.permission.READ_PHONE_STATE
5703     })
5704     public boolean isVideoCallingEnabled() {
5705         try {
5706             ITelephony telephony = getITelephony();
5707             if (telephony != null)
5708                 return telephony.isVideoCallingEnabled(getOpPackageName());
5709         } catch (RemoteException e) {
5710             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
5711         }
5712         return false;
5713     }
5714
5715     /**
5716      * Whether the device supports configuring the DTMF tone length.
5717      *
5718      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
5719      */
5720     public boolean canChangeDtmfToneLength() {
5721         try {
5722             ITelephony telephony = getITelephony();
5723             if (telephony != null) {
5724                 return telephony.canChangeDtmfToneLength();
5725             }
5726         } catch (RemoteException e) {
5727             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
5728         } catch (SecurityException e) {
5729             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
5730         }
5731         return false;
5732     }
5733
5734     /**
5735      * Whether the device is a world phone.
5736      *
5737      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
5738      */
5739     public boolean isWorldPhone() {
5740         try {
5741             ITelephony telephony = getITelephony();
5742             if (telephony != null) {
5743                 return telephony.isWorldPhone();
5744             }
5745         } catch (RemoteException e) {
5746             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
5747         } catch (SecurityException e) {
5748             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
5749         }
5750         return false;
5751     }
5752
5753     /**
5754      * Whether the phone supports TTY mode.
5755      *
5756      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
5757      */
5758     public boolean isTtyModeSupported() {
5759         try {
5760             ITelephony telephony = getITelephony();
5761             if (telephony != null) {
5762                 return telephony.isTtyModeSupported();
5763             }
5764         } catch (RemoteException e) {
5765             Log.e(TAG, "Error calling ITelephony#isTtyModeSupported", e);
5766         } catch (SecurityException e) {
5767             Log.e(TAG, "Permission error calling ITelephony#isTtyModeSupported", e);
5768         }
5769         return false;
5770     }
5771
5772     /**
5773      * Whether the phone supports hearing aid compatibility.
5774      *
5775      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
5776      * otherwise.
5777      */
5778     public boolean isHearingAidCompatibilitySupported() {
5779         try {
5780             ITelephony telephony = getITelephony();
5781             if (telephony != null) {
5782                 return telephony.isHearingAidCompatibilitySupported();
5783             }
5784         } catch (RemoteException e) {
5785             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
5786         } catch (SecurityException e) {
5787             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
5788         }
5789         return false;
5790     }
5791
5792     /**
5793      * This function retrieves value for setting "name+subId", and if that is not found
5794      * retrieves value for setting "name", and if that is not found throws
5795      * SettingNotFoundException
5796      *
5797      * @hide
5798      */
5799     public static int getIntWithSubId(ContentResolver cr, String name, int subId)
5800             throws SettingNotFoundException {
5801         try {
5802             return Settings.Global.getInt(cr, name + subId);
5803         } catch (SettingNotFoundException e) {
5804             try {
5805                 int val = Settings.Global.getInt(cr, name);
5806                 Settings.Global.putInt(cr, name + subId, val);
5807
5808                 /* We are now moving from 'setting' to 'setting+subId', and using the value stored
5809                  * for 'setting' as default. Reset the default (since it may have a user set
5810                  * value). */
5811                 int default_val = val;
5812                 if (name.equals(Settings.Global.MOBILE_DATA)) {
5813                     default_val = "true".equalsIgnoreCase(
5814                             SystemProperties.get("ro.com.android.mobiledata", "true")) ? 1 : 0;
5815                 } else if (name.equals(Settings.Global.DATA_ROAMING)) {
5816                     default_val = "true".equalsIgnoreCase(
5817                             SystemProperties.get("ro.com.android.dataroaming", "false")) ? 1 : 0;
5818                 }
5819
5820                 if (default_val != val) {
5821                     Settings.Global.putInt(cr, name, default_val);
5822                 }
5823
5824                 return val;
5825             } catch (SettingNotFoundException exc) {
5826                 throw new SettingNotFoundException(name);
5827             }
5828         }
5829     }
5830
5831    /**
5832     * Returns the IMS Registration Status
5833     * @hide
5834     */
5835    public boolean isImsRegistered() {
5836        try {
5837            ITelephony telephony = getITelephony();
5838            if (telephony == null)
5839                return false;
5840            return telephony.isImsRegistered();
5841        } catch (RemoteException ex) {
5842            return false;
5843        } catch (NullPointerException ex) {
5844            return false;
5845        }
5846    }
5847
5848     /**
5849      * Returns the Status of Volte
5850      * @hide
5851      */
5852     public boolean isVolteAvailable() {
5853        try {
5854            return getITelephony().isVolteAvailable();
5855        } catch (RemoteException ex) {
5856            return false;
5857        } catch (NullPointerException ex) {
5858            return false;
5859        }
5860    }
5861
5862     /**
5863      * Returns the Status of video telephony (VT)
5864      * @hide
5865      */
5866     public boolean isVideoTelephonyAvailable() {
5867         try {
5868             return getITelephony().isVideoTelephonyAvailable();
5869         } catch (RemoteException ex) {
5870             return false;
5871         } catch (NullPointerException ex) {
5872             return false;
5873         }
5874     }
5875
5876     /**
5877      * Returns the Status of Wi-Fi Calling
5878      * @hide
5879      */
5880     public boolean isWifiCallingAvailable() {
5881        try {
5882            return getITelephony().isWifiCallingAvailable();
5883        } catch (RemoteException ex) {
5884            return false;
5885        } catch (NullPointerException ex) {
5886            return false;
5887        }
5888    }
5889
5890    /**
5891     * Set TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC for the default phone.
5892     *
5893     * @hide
5894     */
5895     public void setSimOperatorNumeric(String numeric) {
5896         int phoneId = getPhoneId();
5897         setSimOperatorNumericForPhone(phoneId, numeric);
5898     }
5899
5900    /**
5901     * Set TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC for the given phone.
5902     *
5903     * @hide
5904     */
5905     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
5906         setTelephonyProperty(phoneId,
5907                 TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, numeric);
5908     }
5909
5910     /**
5911      * Set TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC for the default phone.
5912      *
5913      * @hide
5914      */
5915     public void setSimOperatorName(String name) {
5916         int phoneId = getPhoneId();
5917         setSimOperatorNameForPhone(phoneId, name);
5918     }
5919
5920     /**
5921      * Set TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC for the given phone.
5922      *
5923      * @hide
5924      */
5925     public void setSimOperatorNameForPhone(int phoneId, String name) {
5926         setTelephonyProperty(phoneId,
5927                 TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA, name);
5928     }
5929
5930    /**
5931     * Set TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY for the default phone.
5932     *
5933     * @hide
5934     */
5935     public void setSimCountryIso(String iso) {
5936         int phoneId = getPhoneId();
5937         setSimCountryIsoForPhone(phoneId, iso);
5938     }
5939
5940    /**
5941     * Set TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY for the given phone.
5942     *
5943     * @hide
5944     */
5945     public void setSimCountryIsoForPhone(int phoneId, String iso) {
5946         setTelephonyProperty(phoneId,
5947                 TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY, iso);
5948     }
5949
5950     /**
5951      * Set TelephonyProperties.PROPERTY_SIM_STATE for the default phone.
5952      *
5953      * @hide
5954      */
5955     public void setSimState(String state) {
5956         int phoneId = getPhoneId();
5957         setSimStateForPhone(phoneId, state);
5958     }
5959
5960     /**
5961      * Set TelephonyProperties.PROPERTY_SIM_STATE for the given phone.
5962      *
5963      * @hide
5964      */
5965     public void setSimStateForPhone(int phoneId, String state) {
5966         setTelephonyProperty(phoneId,
5967                 TelephonyProperties.PROPERTY_SIM_STATE, state);
5968     }
5969
5970     /**
5971      * Requested state of SIM
5972      *
5973      * CARD_POWER_DOWN
5974      * Powers down the SIM. SIM must be up prior.
5975      *
5976      * CARD_POWER_UP
5977      * Powers up the SIM normally. SIM must be down prior.
5978      *
5979      * CARD_POWER_UP_PASS_THROUGH
5980      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
5981      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
5982      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
5983      * and the SIM card is controlled completely by Telephony sending APDUs
5984      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
5985      * number of card apps will be 0.
5986      * No new error code is generated. Emergency calls are supported in the
5987      * same way as if the SIM card is absent.
5988      * The PASS_THROUGH mode is valid only for the specific card session where it
5989      * is activated, and normal behavior occurs at the next SIM initialization,
5990      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
5991      * is NOT persistent across boots. On reboot, SIM will power up normally.
5992      */
5993     /** @hide */
5994     public static final int CARD_POWER_DOWN = 0;
5995     /** @hide */
5996     public static final int CARD_POWER_UP = 1;
5997     /** @hide */
5998     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
5999
6000     /**
6001      * Set SIM card power state.
6002      *
6003      * @param state  State of SIM (power down, power up, pass through)
6004      * @see #CARD_POWER_DOWN
6005      * @see #CARD_POWER_UP
6006      * @see #CARD_POWER_UP_PASS_THROUGH
6007      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
6008      * broadcasts to determine success or failure and timeout if needed.
6009      *
6010      * <p>Requires Permission:
6011      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
6012      *
6013      * @hide
6014      **/
6015     public void setSimPowerState(int state) {
6016         setSimPowerStateForSlot(getSlotIndex(), state);
6017     }
6018
6019     /**
6020      * Set SIM card power state.
6021      *
6022      * @param slotIndex SIM slot id
6023      * @param state  State of SIM (power down, power up, pass through)
6024      * @see #CARD_POWER_DOWN
6025      * @see #CARD_POWER_UP
6026      * @see #CARD_POWER_UP_PASS_THROUGH
6027      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
6028      * broadcasts to determine success or failure and timeout if needed.
6029      *
6030      * <p>Requires Permission:
6031      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
6032      *
6033      * @hide
6034      **/
6035     public void setSimPowerStateForSlot(int slotIndex, int state) {
6036         try {
6037             ITelephony telephony = getITelephony();
6038             if (telephony != null) {
6039                 telephony.setSimPowerStateForSlot(slotIndex, state);
6040             }
6041         } catch (RemoteException e) {
6042             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
6043         } catch (SecurityException e) {
6044             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
6045         }
6046     }
6047
6048     /**
6049      * Set baseband version for the default phone.
6050      *
6051      * @param version baseband version
6052      * @hide
6053      */
6054     public void setBasebandVersion(String version) {
6055         int phoneId = getPhoneId();
6056         setBasebandVersionForPhone(phoneId, version);
6057     }
6058
6059     /**
6060      * Set baseband version by phone id.
6061      *
6062      * @param phoneId for which baseband version is set
6063      * @param version baseband version
6064      * @hide
6065      */
6066     public void setBasebandVersionForPhone(int phoneId, String version) {
6067         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6068             String prop = TelephonyProperties.PROPERTY_BASEBAND_VERSION +
6069                     ((phoneId == 0) ? "" : Integer.toString(phoneId));
6070             SystemProperties.set(prop, version);
6071         }
6072     }
6073
6074     /**
6075      * Set phone type for the default phone.
6076      *
6077      * @param type phone type
6078      *
6079      * @hide
6080      */
6081     public void setPhoneType(int type) {
6082         int phoneId = getPhoneId();
6083         setPhoneType(phoneId, type);
6084     }
6085
6086     /**
6087      * Set phone type by phone id.
6088      *
6089      * @param phoneId for which phone type is set
6090      * @param type phone type
6091      *
6092      * @hide
6093      */
6094     public void setPhoneType(int phoneId, int type) {
6095         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6096             TelephonyManager.setTelephonyProperty(phoneId,
6097                     TelephonyProperties.CURRENT_ACTIVE_PHONE, String.valueOf(type));
6098         }
6099     }
6100
6101     /**
6102      * Get OTASP number schema for the default phone.
6103      *
6104      * @param defaultValue default value
6105      * @return OTA SP number schema
6106      *
6107      * @hide
6108      */
6109     public String getOtaSpNumberSchema(String defaultValue) {
6110         int phoneId = getPhoneId();
6111         return getOtaSpNumberSchemaForPhone(phoneId, defaultValue);
6112     }
6113
6114     /**
6115      * Get OTASP number schema by phone id.
6116      *
6117      * @param phoneId for which OTA SP number schema is get
6118      * @param defaultValue default value
6119      * @return OTA SP number schema
6120      *
6121      * @hide
6122      */
6123     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
6124         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6125             return TelephonyManager.getTelephonyProperty(phoneId,
6126                     TelephonyProperties.PROPERTY_OTASP_NUM_SCHEMA, defaultValue);
6127         }
6128
6129         return defaultValue;
6130     }
6131
6132     /**
6133      * Get SMS receive capable from system property for the default phone.
6134      *
6135      * @param defaultValue default value
6136      * @return SMS receive capable
6137      *
6138      * @hide
6139      */
6140     public boolean getSmsReceiveCapable(boolean defaultValue) {
6141         int phoneId = getPhoneId();
6142         return getSmsReceiveCapableForPhone(phoneId, defaultValue);
6143     }
6144
6145     /**
6146      * Get SMS receive capable from system property by phone id.
6147      *
6148      * @param phoneId for which SMS receive capable is get
6149      * @param defaultValue default value
6150      * @return SMS receive capable
6151      *
6152      * @hide
6153      */
6154     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
6155         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6156             return Boolean.parseBoolean(TelephonyManager.getTelephonyProperty(phoneId,
6157                     TelephonyProperties.PROPERTY_SMS_RECEIVE, String.valueOf(defaultValue)));
6158         }
6159
6160         return defaultValue;
6161     }
6162
6163     /**
6164      * Get SMS send capable from system property for the default phone.
6165      *
6166      * @param defaultValue default value
6167      * @return SMS send capable
6168      *
6169      * @hide
6170      */
6171     public boolean getSmsSendCapable(boolean defaultValue) {
6172         int phoneId = getPhoneId();
6173         return getSmsSendCapableForPhone(phoneId, defaultValue);
6174     }
6175
6176     /**
6177      * Get SMS send capable from system property by phone id.
6178      *
6179      * @param phoneId for which SMS send capable is get
6180      * @param defaultValue default value
6181      * @return SMS send capable
6182      *
6183      * @hide
6184      */
6185     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
6186         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6187             return Boolean.parseBoolean(TelephonyManager.getTelephonyProperty(phoneId,
6188                     TelephonyProperties.PROPERTY_SMS_SEND, String.valueOf(defaultValue)));
6189         }
6190
6191         return defaultValue;
6192     }
6193
6194     /**
6195      * Set the alphabetic name of current registered operator.
6196      * @param name the alphabetic name of current registered operator.
6197      * @hide
6198      */
6199     public void setNetworkOperatorName(String name) {
6200         int phoneId = getPhoneId();
6201         setNetworkOperatorNameForPhone(phoneId, name);
6202     }
6203
6204     /**
6205      * Set the alphabetic name of current registered operator.
6206      * @param phoneId which phone you want to set
6207      * @param name the alphabetic name of current registered operator.
6208      * @hide
6209      */
6210     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
6211         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6212             setTelephonyProperty(phoneId, TelephonyProperties.PROPERTY_OPERATOR_ALPHA, name);
6213         }
6214     }
6215
6216     /**
6217      * Set the numeric name (MCC+MNC) of current registered operator.
6218      * @param operator the numeric name (MCC+MNC) of current registered operator
6219      * @hide
6220      */
6221     public void setNetworkOperatorNumeric(String numeric) {
6222         int phoneId = getPhoneId();
6223         setNetworkOperatorNumericForPhone(phoneId, numeric);
6224     }
6225
6226     /**
6227      * Set the numeric name (MCC+MNC) of current registered operator.
6228      * @param phoneId for which phone type is set
6229      * @param operator the numeric name (MCC+MNC) of current registered operator
6230      * @hide
6231      */
6232     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
6233         setTelephonyProperty(phoneId, TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, numeric);
6234     }
6235
6236     /**
6237      * Set roaming state of the current network, for GSM purposes.
6238      * @param isRoaming is network in romaing state or not
6239      * @hide
6240      */
6241     public void setNetworkRoaming(boolean isRoaming) {
6242         int phoneId = getPhoneId();
6243         setNetworkRoamingForPhone(phoneId, isRoaming);
6244     }
6245
6246     /**
6247      * Set roaming state of the current network, for GSM purposes.
6248      * @param phoneId which phone you want to set
6249      * @param isRoaming is network in romaing state or not
6250      * @hide
6251      */
6252     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
6253         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6254             setTelephonyProperty(phoneId, TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
6255                     isRoaming ? "true" : "false");
6256         }
6257     }
6258
6259     /**
6260      * Set the ISO country code equivalent of the current registered
6261      * operator's MCC (Mobile Country Code).
6262      * @param iso the ISO country code equivalent of the current registered
6263      * @hide
6264      */
6265     public void setNetworkCountryIso(String iso) {
6266         int phoneId = getPhoneId();
6267         setNetworkCountryIsoForPhone(phoneId, iso);
6268     }
6269
6270     /**
6271      * Set the ISO country code equivalent of the current registered
6272      * operator's MCC (Mobile Country Code).
6273      * @param phoneId which phone you want to set
6274      * @param iso the ISO country code equivalent of the current registered
6275      * @hide
6276      */
6277     public void setNetworkCountryIsoForPhone(int phoneId, String iso) {
6278         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6279             setTelephonyProperty(phoneId,
6280                     TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
6281         }
6282     }
6283
6284     /**
6285      * Set the network type currently in use on the device for data transmission.
6286      *
6287      * If this object has been created with {@link #createForSubscriptionId}, applies to the
6288      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
6289      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
6290      * @param type the network type currently in use on the device for data transmission
6291      * @hide
6292      */
6293     public void setDataNetworkType(int type) {
6294         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
6295         setDataNetworkTypeForPhone(phoneId, type);
6296     }
6297
6298     /**
6299      * Set the network type currently in use on the device for data transmission.
6300      * @param phoneId which phone you want to set
6301      * @param type the network type currently in use on the device for data transmission
6302      * @hide
6303      */
6304     public void setDataNetworkTypeForPhone(int phoneId, int type) {
6305         if (SubscriptionManager.isValidPhoneId(phoneId)) {
6306             setTelephonyProperty(phoneId,
6307                     TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
6308                     ServiceState.rilRadioTechnologyToString(type));
6309         }
6310     }
6311
6312     /**
6313      * Returns the subscription ID for the given phone account.
6314      * @hide
6315      */
6316     public int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
6317         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
6318         try {
6319             ITelephony service = getITelephony();
6320             if (service != null) {
6321                 retval = service.getSubIdForPhoneAccount(phoneAccount);
6322             }
6323         } catch (RemoteException e) {
6324         }
6325
6326         return retval;
6327     }
6328
6329     private int getSubIdForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
6330         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
6331         try {
6332             ITelecomService service = getTelecomService();
6333             if (service != null) {
6334                 retval = getSubIdForPhoneAccount(service.getPhoneAccount(phoneAccountHandle));
6335             }
6336         } catch (RemoteException e) {
6337         }
6338
6339         return retval;
6340     }
6341
6342     /**
6343      * Resets telephony manager settings back to factory defaults.
6344      *
6345      * @hide
6346      */
6347     public void factoryReset(int subId) {
6348         try {
6349             Log.d(TAG, "factoryReset: subId=" + subId);
6350             ITelephony telephony = getITelephony();
6351             if (telephony != null)
6352                 telephony.factoryReset(subId);
6353         } catch (RemoteException e) {
6354         }
6355     }
6356
6357
6358     /** @hide */
6359     public String getLocaleFromDefaultSim() {
6360         try {
6361             final ITelephony telephony = getITelephony();
6362             if (telephony != null) {
6363                 return telephony.getLocaleFromDefaultSim();
6364             }
6365         } catch (RemoteException ex) {
6366         }
6367         return null;
6368     }
6369
6370     /**
6371      * Requests the modem activity info. The recipient will place the result
6372      * in `result`.
6373      * @param result The object on which the recipient will send the resulting
6374      * {@link android.telephony.ModemActivityInfo} object.
6375      * @hide
6376      */
6377     public void requestModemActivityInfo(ResultReceiver result) {
6378         try {
6379             ITelephony service = getITelephony();
6380             if (service != null) {
6381                 service.requestModemActivityInfo(result);
6382                 return;
6383             }
6384         } catch (RemoteException e) {
6385             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
6386         }
6387         result.send(0, null);
6388     }
6389
6390     /**
6391      * Returns the current {@link ServiceState} information.
6392      */
6393     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6394     public ServiceState getServiceState() {
6395         return getServiceStateForSubscriber(getSubId());
6396     }
6397
6398     /**
6399      * Returns the service state information on specified subscription. Callers require
6400      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
6401      * @hide
6402      */
6403     public ServiceState getServiceStateForSubscriber(int subId) {
6404         try {
6405             ITelephony service = getITelephony();
6406             if (service != null) {
6407                 return service.getServiceStateForSubscriber(subId, getOpPackageName());
6408             }
6409         } catch (RemoteException e) {
6410             Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
6411         }
6412         return null;
6413     }
6414
6415     /**
6416      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
6417      *
6418      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
6419      * voicemail ringtone.
6420      * @return The URI for the ringtone to play when receiving a voicemail from a specific
6421      * PhoneAccount.
6422      */
6423     public Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
6424         try {
6425             ITelephony service = getITelephony();
6426             if (service != null) {
6427                 return service.getVoicemailRingtoneUri(accountHandle);
6428             }
6429         } catch (RemoteException e) {
6430             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
6431         }
6432         return null;
6433     }
6434
6435     /**
6436      * Sets the per-account voicemail ringtone.
6437      *
6438      * <p>Requires that the calling app is the default dialer, or has carrier privileges, or has
6439      * permission {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6440      *
6441      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
6442      * voicemail ringtone.
6443      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
6444      * PhoneAccount.
6445      * @see #hasCarrierPrivileges
6446      */
6447     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
6448         try {
6449             ITelephony service = getITelephony();
6450             if (service != null) {
6451                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
6452             }
6453         } catch (RemoteException e) {
6454             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
6455         }
6456     }
6457
6458     /**
6459      * Returns whether vibration is set for voicemail notification in Phone settings.
6460      *
6461      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
6462      * voicemail vibration setting.
6463      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
6464      */
6465     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
6466         try {
6467             ITelephony service = getITelephony();
6468             if (service != null) {
6469                 return service.isVoicemailVibrationEnabled(accountHandle);
6470             }
6471         } catch (RemoteException e) {
6472             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
6473         }
6474         return false;
6475     }
6476
6477     /**
6478      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
6479      *
6480      * <p>Requires that the calling app is the default dialer, or has carrier privileges, or has
6481      * permission {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6482      *
6483      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
6484      * voicemail vibration setting.
6485      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
6486      * specific PhoneAccount.
6487      * @see #hasCarrierPrivileges
6488      */
6489     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
6490             boolean enabled) {
6491         try {
6492             ITelephony service = getITelephony();
6493             if (service != null) {
6494                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
6495                         enabled);
6496             }
6497         } catch (RemoteException e) {
6498             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
6499         }
6500     }
6501
6502     /**
6503      * Return the application ID for the app type like {@link APPTYPE_CSIM}.
6504      *
6505      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
6506      *
6507      * @param appType the uicc app type like {@link APPTYPE_CSIM}
6508      * @return Application ID for specificied app type or null if no uicc or error.
6509      * @hide
6510      */
6511     public String getAidForAppType(int appType) {
6512         return getAidForAppType(getSubId(), appType);
6513     }
6514
6515     /**
6516      * Return the application ID for the app type like {@link APPTYPE_CSIM}.
6517      *
6518      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
6519      *
6520      * @param subId the subscription ID that this request applies to.
6521      * @param appType the uicc app type, like {@link APPTYPE_CSIM}
6522      * @return Application ID for specificied app type or null if no uicc or error.
6523      * @hide
6524      */
6525     public String getAidForAppType(int subId, int appType) {
6526         try {
6527             ITelephony service = getITelephony();
6528             if (service != null) {
6529                 return service.getAidForAppType(subId, appType);
6530             }
6531         } catch (RemoteException e) {
6532             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
6533         }
6534         return null;
6535     }
6536
6537     /**
6538      * Return the Electronic Serial Number.
6539      *
6540      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
6541      *
6542      * @return ESN or null if error.
6543      * @hide
6544      */
6545     public String getEsn() {
6546         return getEsn(getSubId());
6547     }
6548
6549     /**
6550      * Return the Electronic Serial Number.
6551      *
6552      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
6553      *
6554      * @param subId the subscription ID that this request applies to.
6555      * @return ESN or null if error.
6556      * @hide
6557      */
6558     public String getEsn(int subId) {
6559         try {
6560             ITelephony service = getITelephony();
6561             if (service != null) {
6562                 return service.getEsn(subId);
6563             }
6564         } catch (RemoteException e) {
6565             Log.e(TAG, "Error calling ITelephony#getEsn", e);
6566         }
6567         return null;
6568     }
6569
6570     /**
6571      * Return the Preferred Roaming List Version
6572      *
6573      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
6574      *
6575      * @return PRLVersion or null if error.
6576      * @hide
6577      */
6578     public String getCdmaPrlVersion() {
6579         return getCdmaPrlVersion(getSubId());
6580     }
6581
6582     /**
6583      * Return the Preferred Roaming List Version
6584      *
6585      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
6586      *
6587      * @param subId the subscription ID that this request applies to.
6588      * @return PRLVersion or null if error.
6589      * @hide
6590      */
6591     public String getCdmaPrlVersion(int subId) {
6592         try {
6593             ITelephony service = getITelephony();
6594             if (service != null) {
6595                 return service.getCdmaPrlVersion(subId);
6596             }
6597         } catch (RemoteException e) {
6598             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
6599         }
6600         return null;
6601     }
6602
6603     /**
6604      * Get snapshot of Telephony histograms
6605      * @return List of Telephony histograms
6606      * Requires Permission:
6607      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
6608      * Or the calling app has carrier privileges.
6609      * @hide
6610      */
6611     @SystemApi
6612     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
6613     public List<TelephonyHistogram> getTelephonyHistograms() {
6614         try {
6615             ITelephony service = getITelephony();
6616             if (service != null) {
6617                 return service.getTelephonyHistograms();
6618             }
6619         } catch (RemoteException e) {
6620             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
6621         }
6622         return null;
6623     }
6624
6625     /**
6626      * Set the allowed carrier list for slotIndex
6627      * Require system privileges. In the future we may add this to carrier APIs.
6628      *
6629      * <p>Requires Permission:
6630      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
6631      *
6632      * <p>This method works only on devices with {@link
6633      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
6634      *
6635      * @return The number of carriers set successfully. Should be length of
6636      * carrierList on success; -1 if carrierList null or on error.
6637      * @hide
6638      */
6639     @SystemApi
6640     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
6641     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
6642         try {
6643             ITelephony service = getITelephony();
6644             if (service != null) {
6645                 return service.setAllowedCarriers(slotIndex, carriers);
6646             }
6647         } catch (RemoteException e) {
6648             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
6649         } catch (NullPointerException e) {
6650             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
6651         }
6652         return -1;
6653     }
6654
6655     /**
6656      * Get the allowed carrier list for slotIndex.
6657      * Require system privileges. In the future we may add this to carrier APIs.
6658      *
6659      * <p>This method returns valid data on devices with {@link
6660      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
6661      *
6662      * @return List of {@link android.telephony.CarrierIdentifier}; empty list
6663      * means all carriers are allowed.
6664      * @hide
6665      */
6666     @SystemApi
6667     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6668     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
6669         try {
6670             ITelephony service = getITelephony();
6671             if (service != null) {
6672                 return service.getAllowedCarriers(slotIndex);
6673             }
6674         } catch (RemoteException e) {
6675             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
6676         } catch (NullPointerException e) {
6677             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
6678         }
6679         return new ArrayList<CarrierIdentifier>(0);
6680     }
6681
6682     /**
6683      * Action set from carrier signalling broadcast receivers to enable/disable metered apns
6684      * Permissions android.Manifest.permission.MODIFY_PHONE_STATE is required
6685      * @param subId the subscription ID that this action applies to.
6686      * @param enabled control enable or disable metered apns.
6687      * @hide
6688      */
6689     public void carrierActionSetMeteredApnsEnabled(int subId, boolean enabled) {
6690         try {
6691             ITelephony service = getITelephony();
6692             if (service != null) {
6693                 service.carrierActionSetMeteredApnsEnabled(subId, enabled);
6694             }
6695         } catch (RemoteException e) {
6696             Log.e(TAG, "Error calling ITelephony#carrierActionSetMeteredApnsEnabled", e);
6697         }
6698     }
6699
6700     /**
6701      * Action set from carrier signalling broadcast receivers to enable/disable radio
6702      * Permissions android.Manifest.permission.MODIFY_PHONE_STATE is required
6703      * @param subId the subscription ID that this action applies to.
6704      * @param enabled control enable or disable radio.
6705      * @hide
6706      */
6707     public void carrierActionSetRadioEnabled(int subId, boolean enabled) {
6708         try {
6709             ITelephony service = getITelephony();
6710             if (service != null) {
6711                 service.carrierActionSetRadioEnabled(subId, enabled);
6712             }
6713         } catch (RemoteException e) {
6714             Log.e(TAG, "Error calling ITelephony#carrierActionSetRadioEnabled", e);
6715         }
6716     }
6717
6718     /**
6719      * Action set from carrier signalling broadcast receivers to start/stop reporting default
6720      * network available events
6721      * Permissions android.Manifest.permission.MODIFY_PHONE_STATE is required
6722      * @param subId the subscription ID that this action applies to.
6723      * @param report control start/stop reporting network status.
6724      * @hide
6725      */
6726     public void carrierActionReportDefaultNetworkStatus(int subId, boolean report) {
6727         try {
6728             ITelephony service = getITelephony();
6729             if (service != null) {
6730                 service.carrierActionReportDefaultNetworkStatus(subId, report);
6731             }
6732         } catch (RemoteException e) {
6733             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
6734         }
6735     }
6736
6737     /**
6738      * Get aggregated video call data usage since boot.
6739      * Permissions android.Manifest.permission.READ_NETWORK_USAGE_HISTORY is required.
6740      *
6741      * @param how one of the NetworkStats.STATS_PER_* constants depending on whether the request is
6742      * for data usage per uid or overall usage.
6743      * @return Snapshot of video call data usage
6744      * @hide
6745      */
6746     public NetworkStats getVtDataUsage(int how) {
6747         boolean perUidStats = (how == NetworkStats.STATS_PER_UID);
6748         try {
6749             ITelephony service = getITelephony();
6750             if (service != null) {
6751                 return service.getVtDataUsage(getSubId(), perUidStats);
6752             }
6753         } catch (RemoteException e) {
6754             Log.e(TAG, "Error calling ITelephony#getVtDataUsage", e);
6755         }
6756         return null;
6757     }
6758
6759     /**
6760      * Policy control of data connection. Usually used when data limit is passed.
6761      * @param enabled True if enabling the data, otherwise disabling.
6762      * @param subId sub id
6763      * @hide
6764      */
6765     public void setPolicyDataEnabled(boolean enabled, int subId) {
6766         try {
6767             ITelephony service = getITelephony();
6768             if (service != null) {
6769                 service.setPolicyDataEnabled(enabled, subId);
6770             }
6771         } catch (RemoteException e) {
6772             Log.e(TAG, "Error calling ITelephony#setPolicyDataEnabled", e);
6773         }
6774     }
6775
6776     /**
6777      * Get Client request stats which will contain statistical information
6778      * on each request made by client.
6779      * Callers require either READ_PRIVILEGED_PHONE_STATE or
6780      * READ_PHONE_STATE to retrieve the information.
6781      * @param subId sub id
6782      * @return List of Client Request Stats
6783      * @hide
6784      */
6785     public List<ClientRequestStats> getClientRequestStats(int subId) {
6786         try {
6787             ITelephony service = getITelephony();
6788             if (service != null) {
6789                 return service.getClientRequestStats(getOpPackageName(), subId);
6790             }
6791         } catch (RemoteException e) {
6792             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
6793         }
6794
6795         return null;
6796     }
6797
6798     /**
6799      * Check if phone is in emergency callback mode
6800      * @return true if phone is in emergency callback mode
6801      * @hide
6802      */
6803     public boolean getEmergencyCallbackMode() {
6804         return getEmergencyCallbackMode(getSubId());
6805     }
6806
6807     /**
6808      * Check if phone is in emergency callback mode
6809      * @return true if phone is in emergency callback mode
6810      * @param subId the subscription ID that this action applies to.
6811      * @hide
6812      */
6813     public boolean getEmergencyCallbackMode(int subId) {
6814         try {
6815             ITelephony telephony = getITelephony();
6816             if (telephony == null) {
6817                 return false;
6818             }
6819             return telephony.getEmergencyCallbackMode(subId);
6820         } catch (RemoteException e) {
6821             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
6822         }
6823         return false;
6824     }
6825
6826     /**
6827      * Get the most recently available signal strength information.
6828      *
6829      * Get the most recent SignalStrength information reported by the modem. Due
6830      * to power saving this information may not always be current.
6831      * @return the most recent cached signal strength info from the modem
6832      * @hide
6833      */
6834     @Nullable
6835     public SignalStrength getSignalStrength() {
6836         try {
6837             ITelephony service = getITelephony();
6838             if (service != null) {
6839                 return service.getSignalStrength(getSubId());
6840             }
6841         } catch (RemoteException e) {
6842             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
6843         }
6844         return null;
6845     }
6846 }