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