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