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