CDMAPhone.java revision 2351b17aba5350004fc76707f3b3d2859ce773c8
1/*
2 * Copyright (C) 2006 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 com.android.internal.telephony.cdma;
18
19import android.app.ActivityManagerNative;
20import android.content.ContentValues;
21import android.content.Context;
22import android.content.Intent;
23import android.content.SharedPreferences;
24import android.database.SQLException;
25import android.net.Uri;
26import android.os.AsyncResult;
27import android.os.Handler;
28import android.os.Message;
29import android.os.PowerManager;
30import android.os.PowerManager.WakeLock;
31import android.os.Registrant;
32import android.os.RegistrantList;
33import android.os.SystemProperties;
34import android.os.UserHandle;
35import android.preference.PreferenceManager;
36import android.provider.Settings;
37import android.provider.Telephony;
38import android.telephony.CellLocation;
39import android.telephony.PhoneNumberUtils;
40import android.telephony.ServiceState;
41import android.telephony.SubscriptionManager;
42import android.telephony.cdma.CdmaCellLocation;
43import android.text.TextUtils;
44import android.telephony.Rlog;
45
46import com.android.ims.ImsManager;
47import com.android.internal.telephony.Call;
48import com.android.internal.telephony.CallStateException;
49import com.android.internal.telephony.CallTracker;
50import com.android.internal.telephony.CommandException;
51import com.android.internal.telephony.CommandsInterface;
52import com.android.internal.telephony.Connection;
53import com.android.internal.telephony.IccPhoneBookInterfaceManager;
54import com.android.internal.telephony.MccTable;
55import com.android.internal.telephony.MmiCode;
56import com.android.internal.telephony.PhoneBase;
57import com.android.internal.telephony.PhoneConstants;
58import com.android.internal.telephony.PhoneNotifier;
59import com.android.internal.telephony.PhoneProxy;
60import com.android.internal.telephony.PhoneSubInfo;
61import com.android.internal.telephony.ServiceStateTracker;
62import com.android.internal.telephony.SubscriptionController;
63import com.android.internal.telephony.TelephonyIntents;
64import com.android.internal.telephony.TelephonyProperties;
65import com.android.internal.telephony.UUSInfo;
66import com.android.internal.telephony.dataconnection.DcTracker;
67import com.android.internal.telephony.imsphone.ImsPhone;
68import com.android.internal.telephony.uicc.IccException;
69import com.android.internal.telephony.uicc.IccRecords;
70import com.android.internal.telephony.uicc.RuimRecords;
71import com.android.internal.telephony.uicc.UiccCard;
72import com.android.internal.telephony.uicc.UiccCardApplication;
73import com.android.internal.telephony.uicc.UiccController;
74
75import java.io.FileDescriptor;
76import java.io.PrintWriter;
77import java.util.ArrayList;
78import java.util.List;
79import java.util.regex.Matcher;
80import java.util.regex.Pattern;
81
82import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA;
83import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY;
84import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC;
85
86/**
87 * {@hide}
88 */
89public class CDMAPhone extends PhoneBase {
90    static final String LOG_TAG = "CDMAPhone";
91    private static final boolean DBG = true;
92    private static final boolean VDBG = false; /* STOP SHIP if true */
93
94    // Default Emergency Callback Mode exit timer
95    private static final int DEFAULT_ECM_EXIT_TIMER_VALUE = 300000;
96
97    static final String VM_COUNT_CDMA = "vm_count_key_cdma";
98    private static final String VM_NUMBER_CDMA = "vm_number_key_cdma";
99    private String mVmNumber = null;
100
101    static final int RESTART_ECM_TIMER = 0; // restart Ecm timer
102    static final int CANCEL_ECM_TIMER = 1; // cancel Ecm timer
103
104    // Instance Variables
105    CdmaCallTracker mCT;
106    CdmaServiceStateTracker mSST;
107    CdmaSubscriptionSourceManager mCdmaSSM;
108    ArrayList <CdmaMmiCode> mPendingMmis = new ArrayList<CdmaMmiCode>();
109    RuimPhoneBookInterfaceManager mRuimPhoneBookInterfaceManager;
110    int mCdmaSubscriptionSource =
111            CdmaSubscriptionSourceManager.SUBSCRIPTION_SOURCE_UNKNOWN;
112    PhoneSubInfo mSubInfo;
113    EriManager mEriManager;
114    WakeLock mWakeLock;
115
116    // mEriFileLoadedRegistrants are informed after the ERI text has been loaded
117    private final RegistrantList mEriFileLoadedRegistrants = new RegistrantList();
118
119    // mEcmTimerResetRegistrants are informed after Ecm timer is canceled or re-started
120    private final RegistrantList mEcmTimerResetRegistrants = new RegistrantList();
121
122    // mEcmExitRespRegistrant is informed after the phone has been exited
123    //the emergency callback mode
124    //keep track of if phone is in emergency callback mode
125    protected boolean mIsPhoneInEcmState;
126    private Registrant mEcmExitRespRegistrant;
127    protected String mImei;
128    protected String mImeiSv;
129    private String mEsn;
130    private String mMeid;
131    // string to define how the carrier specifies its own ota sp number
132    protected String mCarrierOtaSpNumSchema;
133
134    // A runnable which is used to automatically exit from Ecm after a period of time.
135    private Runnable mExitEcmRunnable = new Runnable() {
136        @Override
137        public void run() {
138            exitEmergencyCallbackMode();
139        }
140    };
141
142    Registrant mPostDialHandler;
143
144    static String PROPERTY_CDMA_HOME_OPERATOR_NUMERIC = "ro.cdma.home.operator.numeric";
145
146    // Constructors
147    public CDMAPhone(Context context, CommandsInterface ci, PhoneNotifier notifier) {
148        super("CDMA", notifier, context, ci, false);
149        initSstIcc();
150        init(context, notifier);
151    }
152
153    public CDMAPhone(Context context, CommandsInterface ci, PhoneNotifier notifier,
154            int phoneId) {
155        super("CDMA", notifier, context, ci, false, phoneId);
156        initSstIcc();
157        init(context, notifier);
158    }
159
160    public CDMAPhone(Context context, CommandsInterface ci, PhoneNotifier notifier,
161            boolean unitTestMode) {
162        super("CDMA", notifier, context, ci, unitTestMode);
163        initSstIcc();
164        init(context, notifier);
165    }
166
167    protected void initSstIcc() {
168        mSST = new CdmaServiceStateTracker(this);
169    }
170
171    protected void init(Context context, PhoneNotifier notifier) {
172        mCi.setPhoneType(PhoneConstants.PHONE_TYPE_CDMA);
173        mCT = new CdmaCallTracker(this);
174        mCdmaSSM = CdmaSubscriptionSourceManager.getInstance(context, mCi, this,
175                EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED, null);
176        mDcTracker = new DcTracker(this);
177        mRuimPhoneBookInterfaceManager = new RuimPhoneBookInterfaceManager(this);
178        mSubInfo = new PhoneSubInfo(this);
179        mEriManager = new EriManager(this, context, EriManager.ERI_FROM_XML);
180
181        mCi.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null);
182        mCi.registerForOffOrNotAvailable(this, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
183        mCi.registerForOn(this, EVENT_RADIO_ON, null);
184        mCi.setOnSuppServiceNotification(this, EVENT_SSN, null);
185        mSST.registerForNetworkAttached(this, EVENT_REGISTERED_TO_NETWORK, null);
186        mCi.setEmergencyCallbackMode(this, EVENT_EMERGENCY_CALLBACK_MODE_ENTER, null);
187        mCi.registerForExitEmergencyCallbackMode(this, EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE,
188                null);
189
190        PowerManager pm
191            = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
192        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,LOG_TAG);
193
194        //Change the system setting
195        SystemProperties.set(TelephonyProperties.CURRENT_ACTIVE_PHONE,
196                Integer.toString(PhoneConstants.PHONE_TYPE_CDMA));
197
198        // This is needed to handle phone process crashes
199        String inEcm=SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE, "false");
200        mIsPhoneInEcmState = inEcm.equals("true");
201        if (mIsPhoneInEcmState) {
202            // Send a message which will invoke handleExitEmergencyCallbackMode
203            mCi.exitEmergencyCallbackMode(obtainMessage(EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE));
204        }
205
206        // get the string that specifies the carrier OTA Sp number
207        mCarrierOtaSpNumSchema = SystemProperties.get(
208                TelephonyProperties.PROPERTY_OTASP_NUM_SCHEMA,"");
209
210        // Sets operator properties by retrieving from build-time system property
211        String operatorAlpha = SystemProperties.get("ro.cdma.home.operator.alpha");
212        String operatorNumeric = SystemProperties.get(PROPERTY_CDMA_HOME_OPERATOR_NUMERIC);
213        log("init: operatorAlpha='" + operatorAlpha
214                + "' operatorNumeric='" + operatorNumeric + "'");
215        if (mUiccController.getUiccCardApplication(mPhoneId, UiccController.APP_FAM_3GPP) == null) {
216            log("init: APP_FAM_3GPP == NULL");
217            if (!TextUtils.isEmpty(operatorAlpha)) {
218                log("init: set 'gsm.sim.operator.alpha' to operator='" + operatorAlpha + "'");
219                setSystemProperty(PROPERTY_ICC_OPERATOR_ALPHA, operatorAlpha);
220            }
221            if (!TextUtils.isEmpty(operatorNumeric)) {
222                log("init: set 'gsm.sim.operator.numeric' to operator='" + operatorNumeric + "'");
223                log("update icc_operator_numeric=" + operatorNumeric);
224                setSystemProperty(PROPERTY_ICC_OPERATOR_NUMERIC, operatorNumeric);
225
226                SubscriptionController.getInstance().setMccMnc(operatorNumeric, getSubId());
227            }
228            setIsoCountryProperty(operatorNumeric);
229        }
230
231        // Sets current entry in the telephony carrier table
232        updateCurrentCarrierInProvider(operatorNumeric);
233    }
234
235    @Override
236    public void dispose() {
237        synchronized(PhoneProxy.lockForRadioTechnologyChange) {
238            super.dispose();
239            log("dispose");
240
241            //Unregister from all former registered events
242            unregisterForRuimRecordEvents();
243            mCi.unregisterForAvailable(this); //EVENT_RADIO_AVAILABLE
244            mCi.unregisterForOffOrNotAvailable(this); //EVENT_RADIO_OFF_OR_NOT_AVAILABLE
245            mCi.unregisterForOn(this); //EVENT_RADIO_ON
246            mSST.unregisterForNetworkAttached(this); //EVENT_REGISTERED_TO_NETWORK
247            mCi.unSetOnSuppServiceNotification(this);
248            mCi.unregisterForExitEmergencyCallbackMode(this);
249            removeCallbacks(mExitEcmRunnable);
250
251            mPendingMmis.clear();
252
253            //Force all referenced classes to unregister their former registered events
254            mCT.dispose();
255            mDcTracker.dispose();
256            mSST.dispose();
257            mCdmaSSM.dispose(this);
258            mRuimPhoneBookInterfaceManager.dispose();
259            mSubInfo.dispose();
260            mEriManager.dispose();
261        }
262    }
263
264    @Override
265    public void removeReferences() {
266        log("removeReferences");
267        mRuimPhoneBookInterfaceManager = null;
268        mSubInfo = null;
269        mCT = null;
270        mSST = null;
271        mEriManager = null;
272        mExitEcmRunnable = null;
273
274        super.removeReferences();
275    }
276
277    @Override
278    protected void finalize() {
279        if(DBG) Rlog.d(LOG_TAG, "CDMAPhone finalized");
280        if (mWakeLock.isHeld()) {
281            Rlog.e(LOG_TAG, "UNEXPECTED; mWakeLock is held when finalizing.");
282            mWakeLock.release();
283        }
284    }
285
286    @Override
287    public ServiceState getServiceState() {
288        if (mSST == null || mSST.mSS.getState() != ServiceState.STATE_IN_SERVICE) {
289            if (mImsPhone != null) {
290                return ServiceState.mergeServiceStates(
291                        (mSST == null) ? new ServiceState() : mSST.mSS,
292                        mImsPhone.getServiceState());
293            }
294        }
295
296        if (mSST != null) {
297            return mSST.mSS;
298        } else {
299            // avoid potential NPE in EmergencyCallHelper during Phone switch
300            return new ServiceState();
301        }
302    }
303
304
305    @Override
306    public CallTracker getCallTracker() {
307        return mCT;
308    }
309
310    @Override
311    public PhoneConstants.State getState() {
312        return mCT.mState;
313    }
314
315    @Override
316    public ServiceStateTracker getServiceStateTracker() {
317        return mSST;
318    }
319
320    @Override
321    public int getPhoneType() {
322        return PhoneConstants.PHONE_TYPE_CDMA;
323    }
324
325    @Override
326    public boolean canTransfer() {
327        Rlog.e(LOG_TAG, "canTransfer: not possible in CDMA");
328        return false;
329    }
330
331    @Override
332    public Call getRingingCall() {
333        ImsPhone imPhone = mImsPhone;
334        if ( mCT.mRingingCall != null && mCT.mRingingCall.isRinging() ) {
335            return mCT.mRingingCall;
336        } else if ( imPhone != null ) {
337            return imPhone.getRingingCall();
338        }
339        return mCT.mRingingCall;
340    }
341
342    @Override
343    public void setUiTTYMode(int uiTtyMode, Message onComplete) {
344       if (mImsPhone != null) {
345           mImsPhone.setUiTTYMode(uiTtyMode, onComplete);
346       }
347    }
348
349    @Override
350    public void setMute(boolean muted) {
351        mCT.setMute(muted);
352    }
353
354    @Override
355    public boolean getMute() {
356        return mCT.getMute();
357    }
358
359    @Override
360    public void conference() {
361        if (mImsPhone != null && mImsPhone.canConference()) {
362            log("conference() - delegated to IMS phone");
363            mImsPhone.conference();
364            return;
365        }
366        // three way calls in CDMA will be handled by feature codes
367        Rlog.e(LOG_TAG, "conference: not possible in CDMA");
368    }
369
370    @Override
371    public void enableEnhancedVoicePrivacy(boolean enable, Message onComplete) {
372        mCi.setPreferredVoicePrivacy(enable, onComplete);
373    }
374
375    @Override
376    public void getEnhancedVoicePrivacy(Message onComplete) {
377        mCi.getPreferredVoicePrivacy(onComplete);
378    }
379
380    @Override
381    public void clearDisconnected() {
382        mCT.clearDisconnected();
383    }
384
385    @Override
386    public DataActivityState getDataActivityState() {
387        DataActivityState ret = DataActivityState.NONE;
388
389        if (mSST.getCurrentDataConnectionState() == ServiceState.STATE_IN_SERVICE) {
390
391            switch (mDcTracker.getActivity()) {
392                case DATAIN:
393                    ret = DataActivityState.DATAIN;
394                break;
395
396                case DATAOUT:
397                    ret = DataActivityState.DATAOUT;
398                break;
399
400                case DATAINANDOUT:
401                    ret = DataActivityState.DATAINANDOUT;
402                break;
403
404                case DORMANT:
405                    ret = DataActivityState.DORMANT;
406                break;
407
408                default:
409                    ret = DataActivityState.NONE;
410                break;
411            }
412        }
413        return ret;
414    }
415
416    @Override
417    public Connection
418    dial (String dialString, int videoState) throws CallStateException {
419        ImsPhone imsPhone = mImsPhone;
420
421        boolean imsUseEnabled =
422                ImsManager.isEnhanced4gLteModeSettingEnabledByPlatform(mContext) &&
423                ImsManager.isEnhanced4gLteModeSettingEnabledByUser(mContext);
424        if (!imsUseEnabled) {
425            Rlog.w(LOG_TAG, "IMS is disabled: forced to CS");
426        }
427
428        if (imsUseEnabled && imsPhone != null && imsPhone.isVolteEnabled()
429                && ((imsPhone.getServiceState().getState() == ServiceState.STATE_IN_SERVICE
430                && !PhoneNumberUtils.isEmergencyNumber(dialString))
431                || (PhoneNumberUtils.isEmergencyNumber(dialString)
432                && mContext.getResources().getBoolean(
433                        com.android.internal.R.bool.useImsAlwaysForEmergencyCall))) ) {
434            try {
435                if (DBG) Rlog.d(LOG_TAG, "Trying IMS PS call");
436                return imsPhone.dial(dialString, videoState);
437            } catch (CallStateException e) {
438                if (DBG) Rlog.d(LOG_TAG, "IMS PS call exception " + e +
439                        "imsUseEnabled =" + imsUseEnabled + ", imsPhone =" + imsPhone);
440                if (!ImsPhone.CS_FALLBACK.equals(e.getMessage())) {
441                    CallStateException ce = new CallStateException(e.getMessage());
442                    ce.setStackTrace(e.getStackTrace());
443                    throw ce;
444                }
445            }
446        }
447
448        if (DBG) Rlog.d(LOG_TAG, "Trying (non-IMS) CS call");
449        return dialInternal(dialString, null, videoState);
450    }
451
452
453    @Override
454    protected Connection
455    dialInternal (String dialString, UUSInfo uusInfo,
456            int videoState) throws CallStateException {
457        // Need to make sure dialString gets parsed properly
458        String newDialString = PhoneNumberUtils.stripSeparators(dialString);
459        return mCT.dial(newDialString);
460    }
461
462    @Override
463    public Connection dial(String dialString, UUSInfo uusInfo, int videoState)
464            throws CallStateException {
465        throw new CallStateException("Sending UUS information NOT supported in CDMA!");
466    }
467
468    @Override
469    public boolean
470    getMessageWaitingIndicator() {
471        return (getVoiceMessageCount() > 0);
472    }
473
474    @Override
475    public List<? extends MmiCode>
476    getPendingMmiCodes() {
477        return mPendingMmis;
478    }
479
480    @Override
481    public void registerForSuppServiceNotification(
482            Handler h, int what, Object obj) {
483        Rlog.e(LOG_TAG, "method registerForSuppServiceNotification is NOT supported in CDMA!");
484    }
485
486    @Override
487    public CdmaCall getBackgroundCall() {
488        return mCT.mBackgroundCall;
489    }
490
491    @Override
492    public boolean handleInCallMmiCommands(String dialString) {
493        Rlog.e(LOG_TAG, "method handleInCallMmiCommands is NOT supported in CDMA!");
494        return false;
495    }
496
497    boolean isInCall() {
498        CdmaCall.State foregroundCallState = getForegroundCall().getState();
499        CdmaCall.State backgroundCallState = getBackgroundCall().getState();
500        CdmaCall.State ringingCallState = getRingingCall().getState();
501
502        return (foregroundCallState.isAlive() || backgroundCallState.isAlive() || ringingCallState
503                .isAlive());
504    }
505
506    @Override
507    public void unregisterForSuppServiceNotification(Handler h) {
508        Rlog.e(LOG_TAG, "method unregisterForSuppServiceNotification is NOT supported in CDMA!");
509    }
510
511    @Override
512    public void
513    acceptCall(int videoState) throws CallStateException {
514        ImsPhone imsPhone = mImsPhone;
515        if ( imsPhone != null && imsPhone.getRingingCall().isRinging() ) {
516            imsPhone.acceptCall(videoState);
517        } else {
518            mCT.acceptCall();
519        }
520    }
521
522    @Override
523    public void
524    rejectCall() throws CallStateException {
525        mCT.rejectCall();
526    }
527
528    @Override
529    public void
530    switchHoldingAndActive() throws CallStateException {
531        mCT.switchWaitingOrHoldingAndActive();
532    }
533
534    @Override
535    public String getIccSerialNumber() {
536        IccRecords r = mIccRecords.get();
537        if (r == null) {
538            // to get ICCID form SIMRecords because it is on MF.
539            r = mUiccController.getIccRecords(mPhoneId, UiccController.APP_FAM_3GPP);
540        }
541        return (r != null) ? r.getIccId() : null;
542    }
543
544    @Override
545    public String getLine1Number() {
546        return mSST.getMdnNumber();
547    }
548
549    @Override
550    public String getCdmaPrlVersion(){
551        return mSST.getPrlVersion();
552    }
553
554    @Override
555    public String getCdmaMin() {
556        return mSST.getCdmaMin();
557    }
558
559    @Override
560    public boolean isMinInfoReady() {
561        return mSST.isMinInfoReady();
562    }
563
564    @Override
565    public void getCallWaiting(Message onComplete) {
566        mCi.queryCallWaiting(CommandsInterface.SERVICE_CLASS_VOICE, onComplete);
567    }
568
569    @Override
570    public void
571    setRadioPower(boolean power) {
572        mSST.setRadioPower(power);
573    }
574
575    @Override
576    public String getEsn() {
577        return mEsn;
578    }
579
580    @Override
581    public String getMeid() {
582        return mMeid;
583    }
584
585    @Override
586    public String getNai() {
587        IccRecords r = mIccRecords.get();
588        return (r != null) ? r.getNAI() : null;
589    }
590
591    //returns MEID or ESN in CDMA
592    @Override
593    public String getDeviceId() {
594        String id = getMeid();
595        if ((id == null) || id.matches("^0*$")) {
596            Rlog.d(LOG_TAG, "getDeviceId(): MEID is not initialized use ESN");
597            id = getEsn();
598        }
599        return id;
600    }
601
602    @Override
603    public String getDeviceSvn() {
604        Rlog.d(LOG_TAG, "getDeviceSvn(): return 0");
605        return "0";
606    }
607
608    @Override
609    public String getSubscriberId() {
610        return mSST.getImsi();
611    }
612
613    @Override
614    public String getGroupIdLevel1() {
615        Rlog.e(LOG_TAG, "GID1 is not available in CDMA");
616        return null;
617    }
618
619    @Override
620    public String getImei() {
621        Rlog.e(LOG_TAG, "getImei() called for CDMAPhone");
622        return mImei;
623    }
624
625    @Override
626    public boolean canConference() {
627        if (mImsPhone != null && mImsPhone.canConference()) {
628            return true;
629        }
630        Rlog.e(LOG_TAG, "canConference: not possible in CDMA");
631        return false;
632    }
633
634    @Override
635    public CellLocation getCellLocation() {
636        CdmaCellLocation loc = mSST.mCellLoc;
637
638        int mode = Settings.Secure.getInt(getContext().getContentResolver(),
639                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
640        if (mode == Settings.Secure.LOCATION_MODE_OFF) {
641            // clear lat/long values for location privacy
642            CdmaCellLocation privateLoc = new CdmaCellLocation();
643            privateLoc.setCellLocationData(loc.getBaseStationId(),
644                    CdmaCellLocation.INVALID_LAT_LONG,
645                    CdmaCellLocation.INVALID_LAT_LONG,
646                    loc.getSystemId(), loc.getNetworkId());
647            loc = privateLoc;
648        }
649        return loc;
650    }
651
652    @Override
653    public CdmaCall getForegroundCall() {
654        return mCT.mForegroundCall;
655    }
656
657    @Override
658    public void setOnPostDialCharacter(Handler h, int what, Object obj) {
659        mPostDialHandler = new Registrant(h, what, obj);
660    }
661
662    @Override
663    public boolean handlePinMmi(String dialString) {
664        CdmaMmiCode mmi = CdmaMmiCode.newFromDialString(dialString, this, mUiccApplication.get());
665
666        if (mmi == null) {
667            Rlog.e(LOG_TAG, "Mmi is NULL!");
668            return false;
669        } else if (mmi.isPinPukCommand()) {
670            mPendingMmis.add(mmi);
671            mMmiRegistrants.notifyRegistrants(new AsyncResult(null, mmi, null));
672            mmi.processCode();
673            return true;
674        }
675        Rlog.e(LOG_TAG, "Unrecognized mmi!");
676        return false;
677    }
678
679    /**
680     * Removes the given MMI from the pending list and notifies registrants that
681     * it is complete.
682     *
683     * @param mmi MMI that is done
684     */
685    void onMMIDone(CdmaMmiCode mmi) {
686        /*
687         * Only notify complete if it's on the pending list. Otherwise, it's
688         * already been handled (eg, previously canceled).
689         */
690        if (mPendingMmis.remove(mmi)) {
691            mMmiCompleteRegistrants.notifyRegistrants(new AsyncResult(null, mmi, null));
692        }
693    }
694
695    @Override
696    public void setLine1Number(String alphaTag, String number, Message onComplete) {
697        Rlog.e(LOG_TAG, "setLine1Number: not possible in CDMA");
698    }
699
700    @Override
701    public void setCallWaiting(boolean enable, Message onComplete) {
702        Rlog.e(LOG_TAG, "method setCallWaiting is NOT supported in CDMA!");
703    }
704
705    @Override
706    public void updateServiceLocation() {
707        mSST.enableSingleLocationUpdate();
708    }
709
710    @Override
711    public void setDataRoamingEnabled(boolean enable) {
712        mDcTracker.setDataOnRoamingEnabled(enable);
713    }
714
715    @Override
716    public void registerForCdmaOtaStatusChange(Handler h, int what, Object obj) {
717        mCi.registerForCdmaOtaProvision(h, what, obj);
718    }
719
720    @Override
721    public void unregisterForCdmaOtaStatusChange(Handler h) {
722        mCi.unregisterForCdmaOtaProvision(h);
723    }
724
725    @Override
726    public void registerForSubscriptionInfoReady(Handler h, int what, Object obj) {
727        mSST.registerForSubscriptionInfoReady(h, what, obj);
728    }
729
730    @Override
731    public void unregisterForSubscriptionInfoReady(Handler h) {
732        mSST.unregisterForSubscriptionInfoReady(h);
733    }
734
735    @Override
736    public void setOnEcbModeExitResponse(Handler h, int what, Object obj) {
737        mEcmExitRespRegistrant = new Registrant (h, what, obj);
738    }
739
740    @Override
741    public void unsetOnEcbModeExitResponse(Handler h) {
742        mEcmExitRespRegistrant.clear();
743    }
744
745    @Override
746    public void registerForCallWaiting(Handler h, int what, Object obj) {
747        mCT.registerForCallWaiting(h, what, obj);
748    }
749
750    @Override
751    public void unregisterForCallWaiting(Handler h) {
752        mCT.unregisterForCallWaiting(h);
753    }
754
755    @Override
756    public void
757    getNeighboringCids(Message response) {
758        /*
759         * This is currently not implemented.  At least as of June
760         * 2009, there is no neighbor cell information available for
761         * CDMA because some party is resisting making this
762         * information readily available.  Consequently, calling this
763         * function can have no useful effect.  This situation may
764         * (and hopefully will) change in the future.
765         */
766        if (response != null) {
767            CommandException ce = new CommandException(
768                    CommandException.Error.REQUEST_NOT_SUPPORTED);
769            AsyncResult.forMessage(response).exception = ce;
770            response.sendToTarget();
771        }
772    }
773
774    @Override
775    public PhoneConstants.DataState getDataConnectionState(String apnType) {
776        PhoneConstants.DataState ret = PhoneConstants.DataState.DISCONNECTED;
777
778        if (mSST == null) {
779             // Radio Technology Change is ongoning, dispose() and removeReferences() have
780             // already been called
781
782             ret = PhoneConstants.DataState.DISCONNECTED;
783        } else if (mSST.getCurrentDataConnectionState() != ServiceState.STATE_IN_SERVICE) {
784            // If we're out of service, open TCP sockets may still work
785            // but no data will flow
786            ret = PhoneConstants.DataState.DISCONNECTED;
787        } else if (mDcTracker.isApnTypeEnabled(apnType) == false ||
788                mDcTracker.isApnTypeActive(apnType) == false) {
789            ret = PhoneConstants.DataState.DISCONNECTED;
790        } else {
791            switch (mDcTracker.getState(apnType)) {
792                case RETRYING:
793                case FAILED:
794                case IDLE:
795                    ret = PhoneConstants.DataState.DISCONNECTED;
796                break;
797
798                case CONNECTED:
799                case DISCONNECTING:
800                    if ( mCT.mState != PhoneConstants.State.IDLE
801                            && !mSST.isConcurrentVoiceAndDataAllowed()) {
802                        ret = PhoneConstants.DataState.SUSPENDED;
803                    } else {
804                        ret = PhoneConstants.DataState.CONNECTED;
805                    }
806                break;
807
808                case CONNECTING:
809                case SCANNING:
810                    ret = PhoneConstants.DataState.CONNECTING;
811                break;
812            }
813        }
814
815        log("getDataConnectionState apnType=" + apnType + " ret=" + ret);
816        return ret;
817    }
818
819    @Override
820    public void sendUssdResponse(String ussdMessge) {
821        Rlog.e(LOG_TAG, "sendUssdResponse: not possible in CDMA");
822    }
823
824    @Override
825    public void sendDtmf(char c) {
826        if (!PhoneNumberUtils.is12Key(c)) {
827            Rlog.e(LOG_TAG,
828                    "sendDtmf called with invalid character '" + c + "'");
829        } else {
830            if (mCT.mState ==  PhoneConstants.State.OFFHOOK) {
831                mCi.sendDtmf(c, null);
832            }
833        }
834    }
835
836    @Override
837    public void startDtmf(char c) {
838        if (!PhoneNumberUtils.is12Key(c)) {
839            Rlog.e(LOG_TAG,
840                    "startDtmf called with invalid character '" + c + "'");
841        } else {
842            mCi.startDtmf(c, null);
843        }
844    }
845
846    @Override
847    public void stopDtmf() {
848        mCi.stopDtmf(null);
849    }
850
851    @Override
852    public void sendBurstDtmf(String dtmfString, int on, int off, Message onComplete) {
853        boolean check = true;
854        for (int itr = 0;itr < dtmfString.length(); itr++) {
855            if (!PhoneNumberUtils.is12Key(dtmfString.charAt(itr))) {
856                Rlog.e(LOG_TAG,
857                        "sendDtmf called with invalid character '" + dtmfString.charAt(itr)+ "'");
858                check = false;
859                break;
860            }
861        }
862        if ((mCT.mState ==  PhoneConstants.State.OFFHOOK)&&(check)) {
863            mCi.sendBurstDtmf(dtmfString, on, off, onComplete);
864        }
865     }
866
867    @Override
868    public void getAvailableNetworks(Message response) {
869        Rlog.e(LOG_TAG, "getAvailableNetworks: not possible in CDMA");
870    }
871
872    @Override
873    public void setOutgoingCallerIdDisplay(int commandInterfaceCLIRMode, Message onComplete) {
874        Rlog.e(LOG_TAG, "setOutgoingCallerIdDisplay: not possible in CDMA");
875    }
876
877    @Override
878    public void enableLocationUpdates() {
879        mSST.enableLocationUpdates();
880    }
881
882    @Override
883    public void disableLocationUpdates() {
884        mSST.disableLocationUpdates();
885    }
886
887    @Override
888    public void getDataCallList(Message response) {
889        mCi.getDataCallList(response);
890    }
891
892    @Override
893    public boolean getDataRoamingEnabled() {
894        return mDcTracker.getDataOnRoamingEnabled();
895    }
896
897    @Override
898    public void setDataEnabled(boolean enable) {
899        mDcTracker.setDataEnabled(enable);
900    }
901
902    @Override
903    public boolean getDataEnabled() {
904        return mDcTracker.getDataEnabled();
905    }
906
907    @Override
908    public void setVoiceMailNumber(String alphaTag,
909                                   String voiceMailNumber,
910                                   Message onComplete) {
911        Message resp;
912        mVmNumber = voiceMailNumber;
913        resp = obtainMessage(EVENT_SET_VM_NUMBER_DONE, 0, 0, onComplete);
914        IccRecords r = mIccRecords.get();
915        if (r != null) {
916            r.setVoiceMailNumber(alphaTag, mVmNumber, resp);
917        }
918    }
919
920    @Override
921    public String getVoiceMailNumber() {
922        String number = null;
923        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
924        number = sp.getString(VM_NUMBER_CDMA + getPhoneId(), null);
925        if (TextUtils.isEmpty(number)) {
926            String[] listArray = getContext().getResources()
927                .getStringArray(com.android.internal.R.array.config_default_vm_number);
928            if (listArray != null && listArray.length > 0) {
929                for (int i=0; i<listArray.length; i++) {
930                    if (!TextUtils.isEmpty(listArray[i])) {
931                        String[] defaultVMNumberArray = listArray[i].split(";");
932                        if (defaultVMNumberArray != null && defaultVMNumberArray.length > 0) {
933                            if (defaultVMNumberArray.length == 1) {
934                                number = defaultVMNumberArray[0];
935                            } else if (defaultVMNumberArray.length == 2 &&
936                                    !TextUtils.isEmpty(defaultVMNumberArray[1]) &&
937                                    defaultVMNumberArray[1].equalsIgnoreCase(getGroupIdLevel1())) {
938                                number = defaultVMNumberArray[0];
939                                break;
940                            }
941                        }
942                    }
943                }
944            }
945        }
946        if (TextUtils.isEmpty(number)) {
947            // Read platform settings for dynamic voicemail number
948            if (getContext().getResources().getBoolean(com.android.internal
949                    .R.bool.config_telephony_use_own_number_for_voicemail)) {
950                number = getLine1Number();
951            } else {
952                number = "*86";
953            }
954        }
955        return number;
956    }
957
958    /* Returns Number of Voicemails
959     * @hide
960     */
961    @Override
962    public int getVoiceMessageCount() {
963        IccRecords r = mIccRecords.get();
964        int voicemailCount =  (r != null) ? r.getVoiceMessageCount() : 0;
965        // If mRuimRecords.getVoiceMessageCount returns zero, then there is possibility
966        // that phone was power cycled and would have lost the voicemail count.
967        // So get the count from preferences.
968        if (voicemailCount == 0) {
969            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
970            voicemailCount = sp.getInt(VM_COUNT_CDMA + getPhoneId(), 0);
971        }
972        return voicemailCount;
973    }
974
975    @Override
976    public String getVoiceMailAlphaTag() {
977        // TODO: Where can we get this value has to be clarified with QC.
978        String ret = "";//TODO: Remove = "", if we know where to get this value.
979
980        //ret = mSIMRecords.getVoiceMailAlphaTag();
981
982        if (ret == null || ret.length() == 0) {
983            return mContext.getText(
984                com.android.internal.R.string.defaultVoiceMailAlphaTag).toString();
985        }
986
987        return ret;
988    }
989
990    @Override
991    public void getCallForwardingOption(int commandInterfaceCFReason, Message onComplete) {
992        Rlog.e(LOG_TAG, "getCallForwardingOption: not possible in CDMA");
993    }
994
995    @Override
996    public void setCallForwardingOption(int commandInterfaceCFAction,
997            int commandInterfaceCFReason,
998            String dialingNumber,
999            int timerSeconds,
1000            Message onComplete) {
1001        Rlog.e(LOG_TAG, "setCallForwardingOption: not possible in CDMA");
1002    }
1003
1004    @Override
1005    public void
1006    getOutgoingCallerIdDisplay(Message onComplete) {
1007        Rlog.e(LOG_TAG, "getOutgoingCallerIdDisplay: not possible in CDMA");
1008    }
1009
1010    @Override
1011    public boolean
1012    getCallForwardingIndicator() {
1013        Rlog.e(LOG_TAG, "getCallForwardingIndicator: not possible in CDMA");
1014        return false;
1015    }
1016
1017    @Override
1018    public void explicitCallTransfer() {
1019        Rlog.e(LOG_TAG, "explicitCallTransfer: not possible in CDMA");
1020    }
1021
1022    @Override
1023    public String getLine1AlphaTag() {
1024        Rlog.e(LOG_TAG, "getLine1AlphaTag: not possible in CDMA");
1025        return null;
1026    }
1027
1028    /**
1029     * Notify any interested party of a Phone state change
1030     * {@link com.android.internal.telephony.PhoneConstants.State}
1031     */
1032    /*package*/ void notifyPhoneStateChanged() {
1033        mNotifier.notifyPhoneState(this);
1034    }
1035
1036    /**
1037     * Notify registrants of a change in the call state. This notifies changes in
1038     * {@link com.android.internal.telephony.Call.State}. Use this when changes
1039     * in the precise call state are needed, else use notifyPhoneStateChanged.
1040     */
1041    /*package*/ void notifyPreciseCallStateChanged() {
1042        /* we'd love it if this was package-scoped*/
1043        super.notifyPreciseCallStateChangedP();
1044    }
1045
1046     void notifyServiceStateChanged(ServiceState ss) {
1047         super.notifyServiceStateChangedP(ss);
1048     }
1049
1050     void notifyLocationChanged() {
1051         mNotifier.notifyCellLocation(this);
1052     }
1053
1054    public void notifyNewRingingConnection(Connection c) {
1055        super.notifyNewRingingConnectionP(c);
1056    }
1057
1058    /*package*/ void notifyDisconnect(Connection cn) {
1059        mDisconnectRegistrants.notifyResult(cn);
1060
1061        mNotifier.notifyDisconnectCause(cn.getDisconnectCause(), cn.getPreciseDisconnectCause());
1062    }
1063
1064    void notifyUnknownConnection(Connection connection) {
1065        mUnknownConnectionRegistrants.notifyResult(connection);
1066    }
1067
1068    @Override
1069    public boolean isInEmergencyCall() {
1070        return mCT.isInEmergencyCall();
1071    }
1072
1073    @Override
1074    public boolean isInEcm() {
1075        return mIsPhoneInEcmState;
1076    }
1077
1078    void sendEmergencyCallbackModeChange(){
1079        //Send an Intent
1080        Intent intent = new Intent(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
1081        intent.putExtra(PhoneConstants.PHONE_IN_ECM_STATE, mIsPhoneInEcmState);
1082        SubscriptionManager.putPhoneIdAndSubIdExtra(intent, getPhoneId());
1083        ActivityManagerNative.broadcastStickyIntent(intent,null,UserHandle.USER_ALL);
1084        if (DBG) Rlog.d(LOG_TAG, "sendEmergencyCallbackModeChange");
1085    }
1086
1087    @Override
1088    public void exitEmergencyCallbackMode() {
1089        if (mWakeLock.isHeld()) {
1090            mWakeLock.release();
1091        }
1092        // Send a message which will invoke handleExitEmergencyCallbackMode
1093        mCi.exitEmergencyCallbackMode(obtainMessage(EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE));
1094    }
1095
1096    private void handleEnterEmergencyCallbackMode(Message msg) {
1097        if (DBG) {
1098            Rlog.d(LOG_TAG, "handleEnterEmergencyCallbackMode,mIsPhoneInEcmState= "
1099                    + mIsPhoneInEcmState);
1100        }
1101        // if phone is not in Ecm mode, and it's changed to Ecm mode
1102        if (mIsPhoneInEcmState == false) {
1103            mIsPhoneInEcmState = true;
1104            // notify change
1105            sendEmergencyCallbackModeChange();
1106            setSystemProperty(TelephonyProperties.PROPERTY_INECM_MODE, "true");
1107
1108            // Post this runnable so we will automatically exit
1109            // if no one invokes exitEmergencyCallbackMode() directly.
1110            long delayInMillis = SystemProperties.getLong(
1111                    TelephonyProperties.PROPERTY_ECM_EXIT_TIMER, DEFAULT_ECM_EXIT_TIMER_VALUE);
1112            postDelayed(mExitEcmRunnable, delayInMillis);
1113            // We don't want to go to sleep while in Ecm
1114            mWakeLock.acquire();
1115        }
1116    }
1117
1118    private void handleExitEmergencyCallbackMode(Message msg) {
1119        AsyncResult ar = (AsyncResult)msg.obj;
1120        if (DBG) {
1121            Rlog.d(LOG_TAG, "handleExitEmergencyCallbackMode,ar.exception , mIsPhoneInEcmState "
1122                    + ar.exception + mIsPhoneInEcmState);
1123        }
1124        // Remove pending exit Ecm runnable, if any
1125        removeCallbacks(mExitEcmRunnable);
1126
1127        if (mEcmExitRespRegistrant != null) {
1128            mEcmExitRespRegistrant.notifyRegistrant(ar);
1129        }
1130        // if exiting ecm success
1131        if (ar.exception == null) {
1132            if (mIsPhoneInEcmState) {
1133                mIsPhoneInEcmState = false;
1134                setSystemProperty(TelephonyProperties.PROPERTY_INECM_MODE, "false");
1135            }
1136            // send an Intent
1137            sendEmergencyCallbackModeChange();
1138            // Re-initiate data connection
1139            mDcTracker.setInternalDataEnabled(true);
1140        }
1141    }
1142
1143    /**
1144     * Handle to cancel or restart Ecm timer in emergency call back mode
1145     * if action is CANCEL_ECM_TIMER, cancel Ecm timer and notify apps the timer is canceled;
1146     * otherwise, restart Ecm timer and notify apps the timer is restarted.
1147     */
1148    void handleTimerInEmergencyCallbackMode(int action) {
1149        switch(action) {
1150        case CANCEL_ECM_TIMER:
1151            removeCallbacks(mExitEcmRunnable);
1152            mEcmTimerResetRegistrants.notifyResult(Boolean.TRUE);
1153            break;
1154        case RESTART_ECM_TIMER:
1155            long delayInMillis = SystemProperties.getLong(
1156                    TelephonyProperties.PROPERTY_ECM_EXIT_TIMER, DEFAULT_ECM_EXIT_TIMER_VALUE);
1157            postDelayed(mExitEcmRunnable, delayInMillis);
1158            mEcmTimerResetRegistrants.notifyResult(Boolean.FALSE);
1159            break;
1160        default:
1161            Rlog.e(LOG_TAG, "handleTimerInEmergencyCallbackMode, unsupported action " + action);
1162        }
1163    }
1164
1165    public void notifyEcbmTimerReset(Boolean flag) {
1166        mEcmTimerResetRegistrants.notifyResult(flag);
1167    }
1168
1169    /**
1170     * Registration point for Ecm timer reset
1171     * @param h handler to notify
1172     * @param what User-defined message code
1173     * @param obj placed in Message.obj
1174     */
1175    @Override
1176    public void registerForEcmTimerReset(Handler h, int what, Object obj) {
1177        mEcmTimerResetRegistrants.addUnique(h, what, obj);
1178    }
1179
1180    @Override
1181    public void unregisterForEcmTimerReset(Handler h) {
1182        mEcmTimerResetRegistrants.remove(h);
1183    }
1184
1185    @Override
1186    public void handleMessage(Message msg) {
1187        AsyncResult ar;
1188        Message     onComplete;
1189
1190        // messages to be handled whether or not the phone is being destroyed
1191        // should only include messages which are being re-directed and do not use
1192        // resources of the phone being destroyed
1193        switch (msg.what) {
1194            // handle the select network completion callbacks.
1195            case EVENT_SET_NETWORK_MANUAL_COMPLETE:
1196            case EVENT_SET_NETWORK_AUTOMATIC_COMPLETE:
1197                super.handleMessage(msg);
1198                return;
1199        }
1200
1201        if (!mIsTheCurrentActivePhone) {
1202            Rlog.e(LOG_TAG, "Received message " + msg +
1203                    "[" + msg.what + "] while being destroyed. Ignoring.");
1204            return;
1205        }
1206        switch(msg.what) {
1207            case EVENT_RADIO_AVAILABLE: {
1208                mCi.getBasebandVersion(obtainMessage(EVENT_GET_BASEBAND_VERSION_DONE));
1209
1210                mCi.getDeviceIdentity(obtainMessage(EVENT_GET_DEVICE_IDENTITY_DONE));
1211            }
1212            break;
1213
1214            case EVENT_GET_BASEBAND_VERSION_DONE:{
1215                ar = (AsyncResult)msg.obj;
1216
1217                if (ar.exception != null) {
1218                    break;
1219                }
1220
1221                if (DBG) Rlog.d(LOG_TAG, "Baseband version: " + ar.result);
1222                setSystemProperty(TelephonyProperties.PROPERTY_BASEBAND_VERSION, (String)ar.result);
1223            }
1224            break;
1225
1226            case EVENT_GET_DEVICE_IDENTITY_DONE:{
1227                ar = (AsyncResult)msg.obj;
1228
1229                if (ar.exception != null) {
1230                    break;
1231                }
1232                String[] respId = (String[])ar.result;
1233                mImei = respId[0];
1234                mImeiSv = respId[1];
1235                mEsn  =  respId[2];
1236                mMeid =  respId[3];
1237            }
1238            break;
1239
1240            case EVENT_EMERGENCY_CALLBACK_MODE_ENTER:{
1241                handleEnterEmergencyCallbackMode(msg);
1242            }
1243            break;
1244
1245            case EVENT_ICC_RECORD_EVENTS:
1246                ar = (AsyncResult)msg.obj;
1247                processIccRecordEvents((Integer)ar.result);
1248                break;
1249
1250            case  EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE:{
1251                handleExitEmergencyCallbackMode(msg);
1252            }
1253            break;
1254
1255            case EVENT_RUIM_RECORDS_LOADED:{
1256                Rlog.d(LOG_TAG, "Event EVENT_RUIM_RECORDS_LOADED Received");
1257                updateCurrentCarrierInProvider();
1258                // Notify voicemails.
1259                log("notifyMessageWaitingChanged");
1260                mNotifier.notifyMessageWaitingChanged(this);
1261            }
1262            break;
1263
1264            case EVENT_RADIO_OFF_OR_NOT_AVAILABLE:{
1265                Rlog.d(LOG_TAG, "Event EVENT_RADIO_OFF_OR_NOT_AVAILABLE Received");
1266                ImsPhone imsPhone = mImsPhone;
1267                if (imsPhone != null) {
1268                    imsPhone.getServiceState().setStateOff();
1269                }
1270            }
1271            break;
1272
1273            case EVENT_RADIO_ON:{
1274                Rlog.d(LOG_TAG, "Event EVENT_RADIO_ON Received");
1275                handleCdmaSubscriptionSource(mCdmaSSM.getCdmaSubscriptionSource());
1276            }
1277            break;
1278
1279            case EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED:{
1280                Rlog.d(LOG_TAG, "EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED");
1281                handleCdmaSubscriptionSource(mCdmaSSM.getCdmaSubscriptionSource());
1282            }
1283            break;
1284
1285            case EVENT_SSN:{
1286                Rlog.d(LOG_TAG, "Event EVENT_SSN Received");
1287            }
1288            break;
1289
1290            case EVENT_REGISTERED_TO_NETWORK:{
1291                Rlog.d(LOG_TAG, "Event EVENT_REGISTERED_TO_NETWORK Received");
1292            }
1293            break;
1294
1295            case EVENT_NV_READY:{
1296                Rlog.d(LOG_TAG, "Event EVENT_NV_READY Received");
1297                prepareEri();
1298                // Notify voicemails.
1299                log("notifyMessageWaitingChanged");
1300                mNotifier.notifyMessageWaitingChanged(this);
1301            }
1302            break;
1303
1304            case EVENT_SET_VM_NUMBER_DONE:{
1305                ar = (AsyncResult)msg.obj;
1306                if (IccException.class.isInstance(ar.exception)) {
1307                    storeVoiceMailNumber(mVmNumber);
1308                    ar.exception = null;
1309                }
1310                onComplete = (Message) ar.userObj;
1311                if (onComplete != null) {
1312                    AsyncResult.forMessage(onComplete, ar.result, ar.exception);
1313                    onComplete.sendToTarget();
1314                }
1315            }
1316            break;
1317
1318            default:{
1319                super.handleMessage(msg);
1320            }
1321        }
1322    }
1323
1324    protected UiccCardApplication getUiccCardApplication() {
1325        return  mUiccController.getUiccCardApplication(mPhoneId, UiccController.APP_FAM_3GPP2);
1326    }
1327
1328    @Override
1329    protected void onUpdateIccAvailability() {
1330        if (mUiccController == null ) {
1331            return;
1332        }
1333
1334        UiccCardApplication newUiccApplication = getUiccCardApplication();
1335
1336        if (newUiccApplication == null) {
1337            log("can't find 3GPP2 application; trying APP_FAM_3GPP");
1338            newUiccApplication =
1339                    mUiccController.getUiccCardApplication(mPhoneId, UiccController.APP_FAM_3GPP);
1340        }
1341
1342        UiccCardApplication app = mUiccApplication.get();
1343        if (app != newUiccApplication) {
1344            if (app != null) {
1345                log("Removing stale icc objects.");
1346                if (mIccRecords.get() != null) {
1347                    unregisterForRuimRecordEvents();
1348                }
1349                mIccRecords.set(null);
1350                mUiccApplication.set(null);
1351            }
1352            if (newUiccApplication != null) {
1353                log("New Uicc application found");
1354                mUiccApplication.set(newUiccApplication);
1355                mIccRecords.set(newUiccApplication.getIccRecords());
1356                registerForRuimRecordEvents();
1357            }
1358        }
1359    }
1360
1361    private void processIccRecordEvents(int eventCode) {
1362        switch (eventCode) {
1363            case RuimRecords.EVENT_MWI:
1364                notifyMessageWaitingIndicator();
1365                break;
1366
1367            default:
1368                Rlog.e(LOG_TAG,"Unknown icc records event code " + eventCode);
1369                break;
1370        }
1371    }
1372
1373    /**
1374     * Handles the call to get the subscription source
1375     *
1376     * @param newSubscriptionSource holds the new CDMA subscription source value
1377     */
1378    private void handleCdmaSubscriptionSource(int newSubscriptionSource) {
1379        if (newSubscriptionSource != mCdmaSubscriptionSource) {
1380             mCdmaSubscriptionSource = newSubscriptionSource;
1381             if (newSubscriptionSource == CDMA_SUBSCRIPTION_NV) {
1382                 // NV is ready when subscription source is NV
1383                 sendMessage(obtainMessage(EVENT_NV_READY));
1384             }
1385        }
1386    }
1387
1388    /**
1389     * Retrieves the PhoneSubInfo of the CDMAPhone
1390     */
1391    @Override
1392    public PhoneSubInfo getPhoneSubInfo() {
1393        return mSubInfo;
1394    }
1395
1396    /**
1397     * Retrieves the IccPhoneBookInterfaceManager of the CDMAPhone
1398     */
1399    @Override
1400    public IccPhoneBookInterfaceManager getIccPhoneBookInterfaceManager() {
1401        return mRuimPhoneBookInterfaceManager;
1402    }
1403
1404    public void registerForEriFileLoaded(Handler h, int what, Object obj) {
1405        Registrant r = new Registrant (h, what, obj);
1406        mEriFileLoadedRegistrants.add(r);
1407    }
1408
1409    public void unregisterForEriFileLoaded(Handler h) {
1410        mEriFileLoadedRegistrants.remove(h);
1411    }
1412
1413    // override for allowing access from other classes of this package
1414    /**
1415     * {@inheritDoc}
1416     */
1417    @Override
1418    public void setSystemProperty(String property, String value) {
1419        super.setSystemProperty(property, value);
1420    }
1421
1422    // override for allowing access from other classes of this package
1423    /**
1424     * {@inheritDoc}
1425     */
1426    @Override
1427    public String getSystemProperty(String property, String defValue) {
1428        return super.getSystemProperty(property, defValue);
1429    }
1430
1431    /**
1432     * Activate or deactivate cell broadcast SMS.
1433     *
1434     * @param activate 0 = activate, 1 = deactivate
1435     * @param response Callback message is empty on completion
1436     */
1437    @Override
1438    public void activateCellBroadcastSms(int activate, Message response) {
1439        Rlog.e(LOG_TAG, "[CDMAPhone] activateCellBroadcastSms() is obsolete; use SmsManager");
1440        response.sendToTarget();
1441    }
1442
1443    /**
1444     * Query the current configuration of cdma cell broadcast SMS.
1445     *
1446     * @param response Callback message is empty on completion
1447     */
1448    @Override
1449    public void getCellBroadcastSmsConfig(Message response) {
1450        Rlog.e(LOG_TAG, "[CDMAPhone] getCellBroadcastSmsConfig() is obsolete; use SmsManager");
1451        response.sendToTarget();
1452    }
1453
1454    /**
1455     * Configure cdma cell broadcast SMS.
1456     *
1457     * @param response Callback message is empty on completion
1458     */
1459    @Override
1460    public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response) {
1461        Rlog.e(LOG_TAG, "[CDMAPhone] setCellBroadcastSmsConfig() is obsolete; use SmsManager");
1462        response.sendToTarget();
1463    }
1464
1465    /**
1466     * Returns true if OTA Service Provisioning needs to be performed.
1467     */
1468    @Override
1469    public boolean needsOtaServiceProvisioning() {
1470        return mSST.getOtasp() != ServiceStateTracker.OTASP_NOT_NEEDED;
1471    }
1472
1473    private static final String IS683A_FEATURE_CODE = "*228";
1474    private static final int IS683A_FEATURE_CODE_NUM_DIGITS = 4;
1475    private static final int IS683A_SYS_SEL_CODE_NUM_DIGITS = 2;
1476    private static final int IS683A_SYS_SEL_CODE_OFFSET = 4;
1477
1478    private static final int IS683_CONST_800MHZ_A_BAND = 0;
1479    private static final int IS683_CONST_800MHZ_B_BAND = 1;
1480    private static final int IS683_CONST_1900MHZ_A_BLOCK = 2;
1481    private static final int IS683_CONST_1900MHZ_B_BLOCK = 3;
1482    private static final int IS683_CONST_1900MHZ_C_BLOCK = 4;
1483    private static final int IS683_CONST_1900MHZ_D_BLOCK = 5;
1484    private static final int IS683_CONST_1900MHZ_E_BLOCK = 6;
1485    private static final int IS683_CONST_1900MHZ_F_BLOCK = 7;
1486    private static final int INVALID_SYSTEM_SELECTION_CODE = -1;
1487
1488    private static boolean isIs683OtaSpDialStr(String dialStr) {
1489        int sysSelCodeInt;
1490        boolean isOtaspDialString = false;
1491        int dialStrLen = dialStr.length();
1492
1493        if (dialStrLen == IS683A_FEATURE_CODE_NUM_DIGITS) {
1494            if (dialStr.equals(IS683A_FEATURE_CODE)) {
1495                isOtaspDialString = true;
1496            }
1497        } else {
1498            sysSelCodeInt = extractSelCodeFromOtaSpNum(dialStr);
1499            switch (sysSelCodeInt) {
1500                case IS683_CONST_800MHZ_A_BAND:
1501                case IS683_CONST_800MHZ_B_BAND:
1502                case IS683_CONST_1900MHZ_A_BLOCK:
1503                case IS683_CONST_1900MHZ_B_BLOCK:
1504                case IS683_CONST_1900MHZ_C_BLOCK:
1505                case IS683_CONST_1900MHZ_D_BLOCK:
1506                case IS683_CONST_1900MHZ_E_BLOCK:
1507                case IS683_CONST_1900MHZ_F_BLOCK:
1508                    isOtaspDialString = true;
1509                    break;
1510                default:
1511                    break;
1512            }
1513        }
1514        return isOtaspDialString;
1515    }
1516    /**
1517     * This function extracts the system selection code from the dial string.
1518     */
1519    private static int extractSelCodeFromOtaSpNum(String dialStr) {
1520        int dialStrLen = dialStr.length();
1521        int sysSelCodeInt = INVALID_SYSTEM_SELECTION_CODE;
1522
1523        if ((dialStr.regionMatches(0, IS683A_FEATURE_CODE,
1524                                   0, IS683A_FEATURE_CODE_NUM_DIGITS)) &&
1525            (dialStrLen >= (IS683A_FEATURE_CODE_NUM_DIGITS +
1526                            IS683A_SYS_SEL_CODE_NUM_DIGITS))) {
1527                // Since we checked the condition above, the system selection code
1528                // extracted from dialStr will not cause any exception
1529                sysSelCodeInt = Integer.parseInt (
1530                                dialStr.substring (IS683A_FEATURE_CODE_NUM_DIGITS,
1531                                IS683A_FEATURE_CODE_NUM_DIGITS + IS683A_SYS_SEL_CODE_NUM_DIGITS));
1532        }
1533        if (DBG) Rlog.d(LOG_TAG, "extractSelCodeFromOtaSpNum " + sysSelCodeInt);
1534        return sysSelCodeInt;
1535    }
1536
1537    /**
1538     * This function checks if the system selection code extracted from
1539     * the dial string "sysSelCodeInt' is the system selection code specified
1540     * in the carrier ota sp number schema "sch".
1541     */
1542    private static boolean
1543    checkOtaSpNumBasedOnSysSelCode (int sysSelCodeInt, String sch[]) {
1544        boolean isOtaSpNum = false;
1545        try {
1546            // Get how many number of system selection code ranges
1547            int selRc = Integer.parseInt(sch[1]);
1548            for (int i = 0; i < selRc; i++) {
1549                if (!TextUtils.isEmpty(sch[i+2]) && !TextUtils.isEmpty(sch[i+3])) {
1550                    int selMin = Integer.parseInt(sch[i+2]);
1551                    int selMax = Integer.parseInt(sch[i+3]);
1552                    // Check if the selection code extracted from the dial string falls
1553                    // within any of the range pairs specified in the schema.
1554                    if ((sysSelCodeInt >= selMin) && (sysSelCodeInt <= selMax)) {
1555                        isOtaSpNum = true;
1556                        break;
1557                    }
1558                }
1559            }
1560        } catch (NumberFormatException ex) {
1561            // If the carrier ota sp number schema is not correct, we still allow dial
1562            // and only log the error:
1563            Rlog.e(LOG_TAG, "checkOtaSpNumBasedOnSysSelCode, error", ex);
1564        }
1565        return isOtaSpNum;
1566    }
1567
1568    // Define the pattern/format for carrier specified OTASP number schema.
1569    // It separates by comma and/or whitespace.
1570    private static Pattern pOtaSpNumSchema = Pattern.compile("[,\\s]+");
1571
1572    /**
1573     * The following function checks if a dial string is a carrier specified
1574     * OTASP number or not by checking against the OTASP number schema stored
1575     * in PROPERTY_OTASP_NUM_SCHEMA.
1576     *
1577     * Currently, there are 2 schemas for carriers to specify the OTASP number:
1578     * 1) Use system selection code:
1579     *    The schema is:
1580     *    SELC,the # of code pairs,min1,max1,min2,max2,...
1581     *    e.g "SELC,3,10,20,30,40,60,70" indicates that there are 3 pairs of
1582     *    selection codes, and they are {10,20}, {30,40} and {60,70} respectively.
1583     *
1584     * 2) Use feature code:
1585     *    The schema is:
1586     *    "FC,length of feature code,feature code".
1587     *     e.g "FC,2,*2" indicates that the length of the feature code is 2,
1588     *     and the code itself is "*2".
1589     */
1590    private boolean isCarrierOtaSpNum(String dialStr) {
1591        boolean isOtaSpNum = false;
1592        int sysSelCodeInt = extractSelCodeFromOtaSpNum(dialStr);
1593        if (sysSelCodeInt == INVALID_SYSTEM_SELECTION_CODE) {
1594            return isOtaSpNum;
1595        }
1596        // mCarrierOtaSpNumSchema is retrieved from PROPERTY_OTASP_NUM_SCHEMA:
1597        if (!TextUtils.isEmpty(mCarrierOtaSpNumSchema)) {
1598            Matcher m = pOtaSpNumSchema.matcher(mCarrierOtaSpNumSchema);
1599            if (DBG) {
1600                Rlog.d(LOG_TAG, "isCarrierOtaSpNum,schema" + mCarrierOtaSpNumSchema);
1601            }
1602
1603            if (m.find()) {
1604                String sch[] = pOtaSpNumSchema.split(mCarrierOtaSpNumSchema);
1605                // If carrier uses system selection code mechanism
1606                if (!TextUtils.isEmpty(sch[0]) && sch[0].equals("SELC")) {
1607                    if (sysSelCodeInt!=INVALID_SYSTEM_SELECTION_CODE) {
1608                        isOtaSpNum=checkOtaSpNumBasedOnSysSelCode(sysSelCodeInt,sch);
1609                    } else {
1610                        if (DBG) {
1611                            Rlog.d(LOG_TAG, "isCarrierOtaSpNum,sysSelCodeInt is invalid");
1612                        }
1613                    }
1614                } else if (!TextUtils.isEmpty(sch[0]) && sch[0].equals("FC")) {
1615                    int fcLen =  Integer.parseInt(sch[1]);
1616                    String fc = sch[2];
1617                    if (dialStr.regionMatches(0,fc,0,fcLen)) {
1618                        isOtaSpNum = true;
1619                    } else {
1620                        if (DBG) Rlog.d(LOG_TAG, "isCarrierOtaSpNum,not otasp number");
1621                    }
1622                } else {
1623                    if (DBG) {
1624                        Rlog.d(LOG_TAG, "isCarrierOtaSpNum,ota schema not supported" + sch[0]);
1625                    }
1626                }
1627            } else {
1628                if (DBG) {
1629                    Rlog.d(LOG_TAG, "isCarrierOtaSpNum,ota schema pattern not right" +
1630                          mCarrierOtaSpNumSchema);
1631                }
1632            }
1633        } else {
1634            if (DBG) Rlog.d(LOG_TAG, "isCarrierOtaSpNum,ota schema pattern empty");
1635        }
1636        return isOtaSpNum;
1637    }
1638
1639    /**
1640     * isOTASPNumber: checks a given number against the IS-683A OTASP dial string and carrier
1641     * OTASP dial string.
1642     *
1643     * @param dialStr the number to look up.
1644     * @return true if the number is in IS-683A OTASP dial string or carrier OTASP dial string
1645     */
1646    @Override
1647    public  boolean isOtaSpNumber(String dialStr){
1648        boolean isOtaSpNum = false;
1649        String dialableStr = PhoneNumberUtils.extractNetworkPortionAlt(dialStr);
1650        if (dialableStr != null) {
1651            isOtaSpNum = isIs683OtaSpDialStr(dialableStr);
1652            if (isOtaSpNum == false) {
1653                isOtaSpNum = isCarrierOtaSpNum(dialableStr);
1654            }
1655        }
1656        if (DBG) Rlog.d(LOG_TAG, "isOtaSpNumber " + isOtaSpNum);
1657        return isOtaSpNum;
1658    }
1659
1660    @Override
1661    public int getCdmaEriIconIndex() {
1662        return getServiceState().getCdmaEriIconIndex();
1663    }
1664
1665    /**
1666     * Returns the CDMA ERI icon mode,
1667     * 0 - ON
1668     * 1 - FLASHING
1669     */
1670    @Override
1671    public int getCdmaEriIconMode() {
1672        return getServiceState().getCdmaEriIconMode();
1673    }
1674
1675    /**
1676     * Returns the CDMA ERI text,
1677     */
1678    @Override
1679    public String getCdmaEriText() {
1680        int roamInd = getServiceState().getCdmaRoamingIndicator();
1681        int defRoamInd = getServiceState().getCdmaDefaultRoamingIndicator();
1682        return mEriManager.getCdmaEriText(roamInd, defRoamInd);
1683    }
1684
1685    /**
1686     * Store the voicemail number in preferences
1687     */
1688    private void storeVoiceMailNumber(String number) {
1689        // Update the preference value of voicemail number
1690        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
1691        SharedPreferences.Editor editor = sp.edit();
1692        editor.putString(VM_NUMBER_CDMA + getPhoneId(), number);
1693        editor.apply();
1694    }
1695
1696    /**
1697     * Sets PROPERTY_ICC_OPERATOR_ISO_COUNTRY property
1698     *
1699     */
1700    protected void setIsoCountryProperty(String operatorNumeric) {
1701        if (TextUtils.isEmpty(operatorNumeric)) {
1702            log("setIsoCountryProperty: clear 'gsm.sim.operator.iso-country'");
1703            setSystemProperty(PROPERTY_ICC_OPERATOR_ISO_COUNTRY, "");
1704        } else {
1705            String iso = "";
1706            try {
1707                iso = MccTable.countryCodeForMcc(Integer.parseInt(
1708                        operatorNumeric.substring(0,3)));
1709            } catch (NumberFormatException ex) {
1710                loge("setIsoCountryProperty: countryCodeForMcc error", ex);
1711            } catch (StringIndexOutOfBoundsException ex) {
1712                loge("setIsoCountryProperty: countryCodeForMcc error", ex);
1713            }
1714
1715            log("setIsoCountryProperty: set 'gsm.sim.operator.iso-country' to iso=" + iso);
1716            setSystemProperty(PROPERTY_ICC_OPERATOR_ISO_COUNTRY, iso);
1717        }
1718    }
1719
1720    /**
1721     * Sets the "current" field in the telephony provider according to the
1722     * build-time operator numeric property
1723     *
1724     * @return true for success; false otherwise.
1725     */
1726    boolean updateCurrentCarrierInProvider(String operatorNumeric) {
1727        log("CDMAPhone: updateCurrentCarrierInProvider called");
1728        if (!TextUtils.isEmpty(operatorNumeric)) {
1729            try {
1730                Uri uri = Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current");
1731                ContentValues map = new ContentValues();
1732                map.put(Telephony.Carriers.NUMERIC, operatorNumeric);
1733                log("updateCurrentCarrierInProvider from system: numeric=" + operatorNumeric);
1734                getContext().getContentResolver().insert(uri, map);
1735
1736                // Updates MCC MNC device configuration information
1737                log("update mccmnc=" + operatorNumeric);
1738                MccTable.updateMccMncConfiguration(mContext, operatorNumeric, false);
1739
1740                return true;
1741            } catch (SQLException e) {
1742                Rlog.e(LOG_TAG, "Can't store current operator", e);
1743            }
1744        }
1745        return false;
1746    }
1747
1748    /**
1749     * Sets the "current" field in the telephony provider according to the SIM's operator.
1750     * Implemented in {@link CDMALTEPhone} for CDMA/LTE devices.
1751     *
1752     * @return true for success; false otherwise.
1753     */
1754    boolean updateCurrentCarrierInProvider() {
1755        return true;
1756    }
1757
1758    public void prepareEri() {
1759        if (mEriManager == null) {
1760            Rlog.e(LOG_TAG, "PrepareEri: Trying to access stale objects");
1761            return;
1762        }
1763        mEriManager.loadEriFile();
1764        if(mEriManager.isEriFileLoaded()) {
1765            // when the ERI file is loaded
1766            log("ERI read, notify registrants");
1767            mEriFileLoadedRegistrants.notifyRegistrants();
1768        }
1769    }
1770
1771    public boolean isEriFileLoaded() {
1772        return mEriManager.isEriFileLoaded();
1773    }
1774
1775    protected void registerForRuimRecordEvents() {
1776        IccRecords r = mIccRecords.get();
1777        if (r == null) {
1778            return;
1779        }
1780        r.registerForRecordsEvents(this, EVENT_ICC_RECORD_EVENTS, null);
1781        r.registerForRecordsLoaded(this, EVENT_RUIM_RECORDS_LOADED, null);
1782    }
1783
1784    protected void unregisterForRuimRecordEvents() {
1785        IccRecords r = mIccRecords.get();
1786        if (r == null) {
1787            return;
1788        }
1789        r.unregisterForRecordsEvents(this);
1790        r.unregisterForRecordsLoaded(this);
1791    }
1792
1793    protected void log(String s) {
1794        if (DBG)
1795            Rlog.d(LOG_TAG, s);
1796    }
1797
1798    protected void loge(String s, Exception e) {
1799        if (DBG)
1800            Rlog.e(LOG_TAG, s, e);
1801    }
1802
1803    @Override
1804    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1805        pw.println("CDMAPhone extends:");
1806        super.dump(fd, pw, args);
1807        pw.println(" mVmNumber=" + mVmNumber);
1808        pw.println(" mCT=" + mCT);
1809        pw.println(" mSST=" + mSST);
1810        pw.println(" mCdmaSSM=" + mCdmaSSM);
1811        pw.println(" mPendingMmis=" + mPendingMmis);
1812        pw.println(" mRuimPhoneBookInterfaceManager=" + mRuimPhoneBookInterfaceManager);
1813        pw.println(" mCdmaSubscriptionSource=" + mCdmaSubscriptionSource);
1814        pw.println(" mSubInfo=" + mSubInfo);
1815        pw.println(" mEriManager=" + mEriManager);
1816        pw.println(" mWakeLock=" + mWakeLock);
1817        pw.println(" mIsPhoneInEcmState=" + mIsPhoneInEcmState);
1818        if (VDBG) pw.println(" mImei=" + mImei);
1819        if (VDBG) pw.println(" mImeiSv=" + mImeiSv);
1820        if (VDBG) pw.println(" mEsn=" + mEsn);
1821        if (VDBG) pw.println(" mMeid=" + mMeid);
1822        pw.println(" mCarrierOtaSpNumSchema=" + mCarrierOtaSpNumSchema);
1823        pw.println(" getCdmaEriIconIndex()=" + getCdmaEriIconIndex());
1824        pw.println(" getCdmaEriIconMode()=" + getCdmaEriIconMode());
1825        pw.println(" getCdmaEriText()=" + getCdmaEriText());
1826        pw.println(" isMinInfoReady()=" + isMinInfoReady());
1827        pw.println(" isCspPlmnEnabled()=" + isCspPlmnEnabled());
1828    }
1829
1830    @Override
1831    public boolean setOperatorBrandOverride(String brand) {
1832        if (mUiccController == null) {
1833            return false;
1834        }
1835
1836        UiccCard card = mUiccController.getUiccCard();
1837        if (card == null) {
1838            return false;
1839        }
1840
1841        boolean status = card.setOperatorBrandOverride(brand);
1842
1843        // Refresh.
1844        if (status) {
1845            IccRecords iccRecords = mIccRecords.get();
1846            if (iccRecords != null) {
1847                SystemProperties.set(TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA,
1848                        iccRecords.getServiceProviderName());
1849            }
1850            if (mSST != null) {
1851                mSST.pollState();
1852            }
1853        }
1854        return status;
1855    }
1856}
1857