CDMAPhone.java revision 474410449d1c576e4731d7018c2579aec7a52e6a
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    //returns MEID or ESN in CDMA
586    @Override
587    public String getDeviceId() {
588        String id = getMeid();
589        if ((id == null) || id.matches("^0*$")) {
590            Rlog.d(LOG_TAG, "getDeviceId(): MEID is not initialized use ESN");
591            id = getEsn();
592        }
593        return id;
594    }
595
596    @Override
597    public String getDeviceSvn() {
598        Rlog.d(LOG_TAG, "getDeviceSvn(): return 0");
599        return "0";
600    }
601
602    @Override
603    public String getSubscriberId() {
604        return mSST.getImsi();
605    }
606
607    @Override
608    public String getGroupIdLevel1() {
609        Rlog.e(LOG_TAG, "GID1 is not available in CDMA");
610        return null;
611    }
612
613    @Override
614    public String getImei() {
615        Rlog.e(LOG_TAG, "getImei() called for CDMAPhone");
616        return mImei;
617    }
618
619    @Override
620    public boolean canConference() {
621        if (mImsPhone != null && mImsPhone.canConference()) {
622            return true;
623        }
624        Rlog.e(LOG_TAG, "canConference: not possible in CDMA");
625        return false;
626    }
627
628    @Override
629    public CellLocation getCellLocation() {
630        CdmaCellLocation loc = mSST.mCellLoc;
631
632        int mode = Settings.Secure.getInt(getContext().getContentResolver(),
633                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
634        if (mode == Settings.Secure.LOCATION_MODE_OFF) {
635            // clear lat/long values for location privacy
636            CdmaCellLocation privateLoc = new CdmaCellLocation();
637            privateLoc.setCellLocationData(loc.getBaseStationId(),
638                    CdmaCellLocation.INVALID_LAT_LONG,
639                    CdmaCellLocation.INVALID_LAT_LONG,
640                    loc.getSystemId(), loc.getNetworkId());
641            loc = privateLoc;
642        }
643        return loc;
644    }
645
646    @Override
647    public CdmaCall getForegroundCall() {
648        return mCT.mForegroundCall;
649    }
650
651    @Override
652    public void setOnPostDialCharacter(Handler h, int what, Object obj) {
653        mPostDialHandler = new Registrant(h, what, obj);
654    }
655
656    @Override
657    public boolean handlePinMmi(String dialString) {
658        CdmaMmiCode mmi = CdmaMmiCode.newFromDialString(dialString, this, mUiccApplication.get());
659
660        if (mmi == null) {
661            Rlog.e(LOG_TAG, "Mmi is NULL!");
662            return false;
663        } else if (mmi.isPinPukCommand()) {
664            mPendingMmis.add(mmi);
665            mMmiRegistrants.notifyRegistrants(new AsyncResult(null, mmi, null));
666            mmi.processCode();
667            return true;
668        }
669        Rlog.e(LOG_TAG, "Unrecognized mmi!");
670        return false;
671    }
672
673    /**
674     * Removes the given MMI from the pending list and notifies registrants that
675     * it is complete.
676     *
677     * @param mmi MMI that is done
678     */
679    void onMMIDone(CdmaMmiCode mmi) {
680        /*
681         * Only notify complete if it's on the pending list. Otherwise, it's
682         * already been handled (eg, previously canceled).
683         */
684        if (mPendingMmis.remove(mmi)) {
685            mMmiCompleteRegistrants.notifyRegistrants(new AsyncResult(null, mmi, null));
686        }
687    }
688
689    @Override
690    public void setLine1Number(String alphaTag, String number, Message onComplete) {
691        Rlog.e(LOG_TAG, "setLine1Number: not possible in CDMA");
692    }
693
694    @Override
695    public void setCallWaiting(boolean enable, Message onComplete) {
696        Rlog.e(LOG_TAG, "method setCallWaiting is NOT supported in CDMA!");
697    }
698
699    @Override
700    public void updateServiceLocation() {
701        mSST.enableSingleLocationUpdate();
702    }
703
704    @Override
705    public void setDataRoamingEnabled(boolean enable) {
706        mDcTracker.setDataOnRoamingEnabled(enable);
707    }
708
709    @Override
710    public void registerForCdmaOtaStatusChange(Handler h, int what, Object obj) {
711        mCi.registerForCdmaOtaProvision(h, what, obj);
712    }
713
714    @Override
715    public void unregisterForCdmaOtaStatusChange(Handler h) {
716        mCi.unregisterForCdmaOtaProvision(h);
717    }
718
719    @Override
720    public void registerForSubscriptionInfoReady(Handler h, int what, Object obj) {
721        mSST.registerForSubscriptionInfoReady(h, what, obj);
722    }
723
724    @Override
725    public void unregisterForSubscriptionInfoReady(Handler h) {
726        mSST.unregisterForSubscriptionInfoReady(h);
727    }
728
729    @Override
730    public void setOnEcbModeExitResponse(Handler h, int what, Object obj) {
731        mEcmExitRespRegistrant = new Registrant (h, what, obj);
732    }
733
734    @Override
735    public void unsetOnEcbModeExitResponse(Handler h) {
736        mEcmExitRespRegistrant.clear();
737    }
738
739    @Override
740    public void registerForCallWaiting(Handler h, int what, Object obj) {
741        mCT.registerForCallWaiting(h, what, obj);
742    }
743
744    @Override
745    public void unregisterForCallWaiting(Handler h) {
746        mCT.unregisterForCallWaiting(h);
747    }
748
749    @Override
750    public void
751    getNeighboringCids(Message response) {
752        /*
753         * This is currently not implemented.  At least as of June
754         * 2009, there is no neighbor cell information available for
755         * CDMA because some party is resisting making this
756         * information readily available.  Consequently, calling this
757         * function can have no useful effect.  This situation may
758         * (and hopefully will) change in the future.
759         */
760        if (response != null) {
761            CommandException ce = new CommandException(
762                    CommandException.Error.REQUEST_NOT_SUPPORTED);
763            AsyncResult.forMessage(response).exception = ce;
764            response.sendToTarget();
765        }
766    }
767
768    @Override
769    public PhoneConstants.DataState getDataConnectionState(String apnType) {
770        PhoneConstants.DataState ret = PhoneConstants.DataState.DISCONNECTED;
771
772        if (mSST == null) {
773             // Radio Technology Change is ongoning, dispose() and removeReferences() have
774             // already been called
775
776             ret = PhoneConstants.DataState.DISCONNECTED;
777        } else if (mSST.getCurrentDataConnectionState() != ServiceState.STATE_IN_SERVICE) {
778            // If we're out of service, open TCP sockets may still work
779            // but no data will flow
780            ret = PhoneConstants.DataState.DISCONNECTED;
781        } else if (mDcTracker.isApnTypeEnabled(apnType) == false ||
782                mDcTracker.isApnTypeActive(apnType) == false) {
783            ret = PhoneConstants.DataState.DISCONNECTED;
784        } else {
785            switch (mDcTracker.getState(apnType)) {
786                case RETRYING:
787                case FAILED:
788                case IDLE:
789                    ret = PhoneConstants.DataState.DISCONNECTED;
790                break;
791
792                case CONNECTED:
793                case DISCONNECTING:
794                    if ( mCT.mState != PhoneConstants.State.IDLE
795                            && !mSST.isConcurrentVoiceAndDataAllowed()) {
796                        ret = PhoneConstants.DataState.SUSPENDED;
797                    } else {
798                        ret = PhoneConstants.DataState.CONNECTED;
799                    }
800                break;
801
802                case CONNECTING:
803                case SCANNING:
804                    ret = PhoneConstants.DataState.CONNECTING;
805                break;
806            }
807        }
808
809        log("getDataConnectionState apnType=" + apnType + " ret=" + ret);
810        return ret;
811    }
812
813    @Override
814    public void sendUssdResponse(String ussdMessge) {
815        Rlog.e(LOG_TAG, "sendUssdResponse: not possible in CDMA");
816    }
817
818    @Override
819    public void sendDtmf(char c) {
820        if (!PhoneNumberUtils.is12Key(c)) {
821            Rlog.e(LOG_TAG,
822                    "sendDtmf called with invalid character '" + c + "'");
823        } else {
824            if (mCT.mState ==  PhoneConstants.State.OFFHOOK) {
825                mCi.sendDtmf(c, null);
826            }
827        }
828    }
829
830    @Override
831    public void startDtmf(char c) {
832        if (!PhoneNumberUtils.is12Key(c)) {
833            Rlog.e(LOG_TAG,
834                    "startDtmf called with invalid character '" + c + "'");
835        } else {
836            mCi.startDtmf(c, null);
837        }
838    }
839
840    @Override
841    public void stopDtmf() {
842        mCi.stopDtmf(null);
843    }
844
845    @Override
846    public void sendBurstDtmf(String dtmfString, int on, int off, Message onComplete) {
847        boolean check = true;
848        for (int itr = 0;itr < dtmfString.length(); itr++) {
849            if (!PhoneNumberUtils.is12Key(dtmfString.charAt(itr))) {
850                Rlog.e(LOG_TAG,
851                        "sendDtmf called with invalid character '" + dtmfString.charAt(itr)+ "'");
852                check = false;
853                break;
854            }
855        }
856        if ((mCT.mState ==  PhoneConstants.State.OFFHOOK)&&(check)) {
857            mCi.sendBurstDtmf(dtmfString, on, off, onComplete);
858        }
859     }
860
861    @Override
862    public void getAvailableNetworks(Message response) {
863        Rlog.e(LOG_TAG, "getAvailableNetworks: not possible in CDMA");
864    }
865
866    @Override
867    public void setOutgoingCallerIdDisplay(int commandInterfaceCLIRMode, Message onComplete) {
868        Rlog.e(LOG_TAG, "setOutgoingCallerIdDisplay: not possible in CDMA");
869    }
870
871    @Override
872    public void enableLocationUpdates() {
873        mSST.enableLocationUpdates();
874    }
875
876    @Override
877    public void disableLocationUpdates() {
878        mSST.disableLocationUpdates();
879    }
880
881    @Override
882    public void getDataCallList(Message response) {
883        mCi.getDataCallList(response);
884    }
885
886    @Override
887    public boolean getDataRoamingEnabled() {
888        return mDcTracker.getDataOnRoamingEnabled();
889    }
890
891    @Override
892    public void setDataEnabled(boolean enable) {
893        mDcTracker.setDataEnabled(enable);
894    }
895
896    @Override
897    public boolean getDataEnabled() {
898        return mDcTracker.getDataEnabled();
899    }
900
901    @Override
902    public void setVoiceMailNumber(String alphaTag,
903                                   String voiceMailNumber,
904                                   Message onComplete) {
905        Message resp;
906        mVmNumber = voiceMailNumber;
907        resp = obtainMessage(EVENT_SET_VM_NUMBER_DONE, 0, 0, onComplete);
908        IccRecords r = mIccRecords.get();
909        if (r != null) {
910            r.setVoiceMailNumber(alphaTag, mVmNumber, resp);
911        }
912    }
913
914    @Override
915    public String getVoiceMailNumber() {
916        String number = null;
917        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
918        number = sp.getString(VM_NUMBER_CDMA + getPhoneId(), null);
919        if (TextUtils.isEmpty(number)) {
920            String[] listArray = getContext().getResources()
921                .getStringArray(com.android.internal.R.array.config_default_vm_number);
922            if (listArray != null && listArray.length > 0) {
923                for (int i=0; i<listArray.length; i++) {
924                    if (!TextUtils.isEmpty(listArray[i])) {
925                        String[] defaultVMNumberArray = listArray[i].split(";");
926                        if (defaultVMNumberArray != null && defaultVMNumberArray.length > 0) {
927                            if (defaultVMNumberArray.length == 1) {
928                                number = defaultVMNumberArray[0];
929                            } else if (defaultVMNumberArray.length == 2 &&
930                                    !TextUtils.isEmpty(defaultVMNumberArray[1]) &&
931                                    defaultVMNumberArray[1].equalsIgnoreCase(getGroupIdLevel1())) {
932                                number = defaultVMNumberArray[0];
933                                break;
934                            }
935                        }
936                    }
937                }
938            }
939        }
940        if (TextUtils.isEmpty(number)) {
941            // Read platform settings for dynamic voicemail number
942            if (getContext().getResources().getBoolean(com.android.internal
943                    .R.bool.config_telephony_use_own_number_for_voicemail)) {
944                number = getLine1Number();
945            } else {
946                number = "*86";
947            }
948        }
949        return number;
950    }
951
952    /* Returns Number of Voicemails
953     * @hide
954     */
955    @Override
956    public int getVoiceMessageCount() {
957        IccRecords r = mIccRecords.get();
958        int voicemailCount =  (r != null) ? r.getVoiceMessageCount() : 0;
959        // If mRuimRecords.getVoiceMessageCount returns zero, then there is possibility
960        // that phone was power cycled and would have lost the voicemail count.
961        // So get the count from preferences.
962        if (voicemailCount == 0) {
963            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
964            voicemailCount = sp.getInt(VM_COUNT_CDMA + getPhoneId(), 0);
965        }
966        return voicemailCount;
967    }
968
969    @Override
970    public String getVoiceMailAlphaTag() {
971        // TODO: Where can we get this value has to be clarified with QC.
972        String ret = "";//TODO: Remove = "", if we know where to get this value.
973
974        //ret = mSIMRecords.getVoiceMailAlphaTag();
975
976        if (ret == null || ret.length() == 0) {
977            return mContext.getText(
978                com.android.internal.R.string.defaultVoiceMailAlphaTag).toString();
979        }
980
981        return ret;
982    }
983
984    @Override
985    public void getCallForwardingOption(int commandInterfaceCFReason, Message onComplete) {
986        Rlog.e(LOG_TAG, "getCallForwardingOption: not possible in CDMA");
987    }
988
989    @Override
990    public void setCallForwardingOption(int commandInterfaceCFAction,
991            int commandInterfaceCFReason,
992            String dialingNumber,
993            int timerSeconds,
994            Message onComplete) {
995        Rlog.e(LOG_TAG, "setCallForwardingOption: not possible in CDMA");
996    }
997
998    @Override
999    public void
1000    getOutgoingCallerIdDisplay(Message onComplete) {
1001        Rlog.e(LOG_TAG, "getOutgoingCallerIdDisplay: not possible in CDMA");
1002    }
1003
1004    @Override
1005    public boolean
1006    getCallForwardingIndicator() {
1007        Rlog.e(LOG_TAG, "getCallForwardingIndicator: not possible in CDMA");
1008        return false;
1009    }
1010
1011    @Override
1012    public void explicitCallTransfer() {
1013        Rlog.e(LOG_TAG, "explicitCallTransfer: not possible in CDMA");
1014    }
1015
1016    @Override
1017    public String getLine1AlphaTag() {
1018        Rlog.e(LOG_TAG, "getLine1AlphaTag: not possible in CDMA");
1019        return null;
1020    }
1021
1022    /**
1023     * Notify any interested party of a Phone state change
1024     * {@link com.android.internal.telephony.PhoneConstants.State}
1025     */
1026    /*package*/ void notifyPhoneStateChanged() {
1027        mNotifier.notifyPhoneState(this);
1028    }
1029
1030    /**
1031     * Notify registrants of a change in the call state. This notifies changes in
1032     * {@link com.android.internal.telephony.Call.State}. Use this when changes
1033     * in the precise call state are needed, else use notifyPhoneStateChanged.
1034     */
1035    /*package*/ void notifyPreciseCallStateChanged() {
1036        /* we'd love it if this was package-scoped*/
1037        super.notifyPreciseCallStateChangedP();
1038    }
1039
1040     void notifyServiceStateChanged(ServiceState ss) {
1041         super.notifyServiceStateChangedP(ss);
1042     }
1043
1044     void notifyLocationChanged() {
1045         mNotifier.notifyCellLocation(this);
1046     }
1047
1048    public void notifyNewRingingConnection(Connection c) {
1049        super.notifyNewRingingConnectionP(c);
1050    }
1051
1052    /*package*/ void notifyDisconnect(Connection cn) {
1053        mDisconnectRegistrants.notifyResult(cn);
1054
1055        mNotifier.notifyDisconnectCause(cn.getDisconnectCause(), cn.getPreciseDisconnectCause());
1056    }
1057
1058    void notifyUnknownConnection(Connection connection) {
1059        mUnknownConnectionRegistrants.notifyResult(connection);
1060    }
1061
1062    @Override
1063    public boolean isInEmergencyCall() {
1064        return mCT.isInEmergencyCall();
1065    }
1066
1067    @Override
1068    public boolean isInEcm() {
1069        return mIsPhoneInEcmState;
1070    }
1071
1072    void sendEmergencyCallbackModeChange(){
1073        //Send an Intent
1074        Intent intent = new Intent(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
1075        intent.putExtra(PhoneConstants.PHONE_IN_ECM_STATE, mIsPhoneInEcmState);
1076        SubscriptionManager.putPhoneIdAndSubIdExtra(intent, getPhoneId());
1077        ActivityManagerNative.broadcastStickyIntent(intent,null,UserHandle.USER_ALL);
1078        if (DBG) Rlog.d(LOG_TAG, "sendEmergencyCallbackModeChange");
1079    }
1080
1081    @Override
1082    public void exitEmergencyCallbackMode() {
1083        if (mWakeLock.isHeld()) {
1084            mWakeLock.release();
1085        }
1086        // Send a message which will invoke handleExitEmergencyCallbackMode
1087        mCi.exitEmergencyCallbackMode(obtainMessage(EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE));
1088    }
1089
1090    private void handleEnterEmergencyCallbackMode(Message msg) {
1091        if (DBG) {
1092            Rlog.d(LOG_TAG, "handleEnterEmergencyCallbackMode,mIsPhoneInEcmState= "
1093                    + mIsPhoneInEcmState);
1094        }
1095        // if phone is not in Ecm mode, and it's changed to Ecm mode
1096        if (mIsPhoneInEcmState == false) {
1097            mIsPhoneInEcmState = true;
1098            // notify change
1099            sendEmergencyCallbackModeChange();
1100            setSystemProperty(TelephonyProperties.PROPERTY_INECM_MODE, "true");
1101
1102            // Post this runnable so we will automatically exit
1103            // if no one invokes exitEmergencyCallbackMode() directly.
1104            long delayInMillis = SystemProperties.getLong(
1105                    TelephonyProperties.PROPERTY_ECM_EXIT_TIMER, DEFAULT_ECM_EXIT_TIMER_VALUE);
1106            postDelayed(mExitEcmRunnable, delayInMillis);
1107            // We don't want to go to sleep while in Ecm
1108            mWakeLock.acquire();
1109        }
1110    }
1111
1112    private void handleExitEmergencyCallbackMode(Message msg) {
1113        AsyncResult ar = (AsyncResult)msg.obj;
1114        if (DBG) {
1115            Rlog.d(LOG_TAG, "handleExitEmergencyCallbackMode,ar.exception , mIsPhoneInEcmState "
1116                    + ar.exception + mIsPhoneInEcmState);
1117        }
1118        // Remove pending exit Ecm runnable, if any
1119        removeCallbacks(mExitEcmRunnable);
1120
1121        if (mEcmExitRespRegistrant != null) {
1122            mEcmExitRespRegistrant.notifyRegistrant(ar);
1123        }
1124        // if exiting ecm success
1125        if (ar.exception == null) {
1126            if (mIsPhoneInEcmState) {
1127                mIsPhoneInEcmState = false;
1128                setSystemProperty(TelephonyProperties.PROPERTY_INECM_MODE, "false");
1129            }
1130            // send an Intent
1131            sendEmergencyCallbackModeChange();
1132            // Re-initiate data connection
1133            mDcTracker.setInternalDataEnabled(true);
1134        }
1135    }
1136
1137    /**
1138     * Handle to cancel or restart Ecm timer in emergency call back mode
1139     * if action is CANCEL_ECM_TIMER, cancel Ecm timer and notify apps the timer is canceled;
1140     * otherwise, restart Ecm timer and notify apps the timer is restarted.
1141     */
1142    void handleTimerInEmergencyCallbackMode(int action) {
1143        switch(action) {
1144        case CANCEL_ECM_TIMER:
1145            removeCallbacks(mExitEcmRunnable);
1146            mEcmTimerResetRegistrants.notifyResult(Boolean.TRUE);
1147            break;
1148        case RESTART_ECM_TIMER:
1149            long delayInMillis = SystemProperties.getLong(
1150                    TelephonyProperties.PROPERTY_ECM_EXIT_TIMER, DEFAULT_ECM_EXIT_TIMER_VALUE);
1151            postDelayed(mExitEcmRunnable, delayInMillis);
1152            mEcmTimerResetRegistrants.notifyResult(Boolean.FALSE);
1153            break;
1154        default:
1155            Rlog.e(LOG_TAG, "handleTimerInEmergencyCallbackMode, unsupported action " + action);
1156        }
1157    }
1158
1159    public void notifyEcbmTimerReset(Boolean flag) {
1160        mEcmTimerResetRegistrants.notifyResult(flag);
1161    }
1162
1163    /**
1164     * Registration point for Ecm timer reset
1165     * @param h handler to notify
1166     * @param what User-defined message code
1167     * @param obj placed in Message.obj
1168     */
1169    @Override
1170    public void registerForEcmTimerReset(Handler h, int what, Object obj) {
1171        mEcmTimerResetRegistrants.addUnique(h, what, obj);
1172    }
1173
1174    @Override
1175    public void unregisterForEcmTimerReset(Handler h) {
1176        mEcmTimerResetRegistrants.remove(h);
1177    }
1178
1179    @Override
1180    public void handleMessage(Message msg) {
1181        AsyncResult ar;
1182        Message     onComplete;
1183
1184        // messages to be handled whether or not the phone is being destroyed
1185        // should only include messages which are being re-directed and do not use
1186        // resources of the phone being destroyed
1187        switch (msg.what) {
1188            // handle the select network completion callbacks.
1189            case EVENT_SET_NETWORK_MANUAL_COMPLETE:
1190            case EVENT_SET_NETWORK_AUTOMATIC_COMPLETE:
1191                super.handleMessage(msg);
1192                return;
1193        }
1194
1195        if (!mIsTheCurrentActivePhone) {
1196            Rlog.e(LOG_TAG, "Received message " + msg +
1197                    "[" + msg.what + "] while being destroyed. Ignoring.");
1198            return;
1199        }
1200        switch(msg.what) {
1201            case EVENT_RADIO_AVAILABLE: {
1202                mCi.getBasebandVersion(obtainMessage(EVENT_GET_BASEBAND_VERSION_DONE));
1203
1204                mCi.getDeviceIdentity(obtainMessage(EVENT_GET_DEVICE_IDENTITY_DONE));
1205            }
1206            break;
1207
1208            case EVENT_GET_BASEBAND_VERSION_DONE:{
1209                ar = (AsyncResult)msg.obj;
1210
1211                if (ar.exception != null) {
1212                    break;
1213                }
1214
1215                if (DBG) Rlog.d(LOG_TAG, "Baseband version: " + ar.result);
1216                setSystemProperty(TelephonyProperties.PROPERTY_BASEBAND_VERSION, (String)ar.result);
1217            }
1218            break;
1219
1220            case EVENT_GET_DEVICE_IDENTITY_DONE:{
1221                ar = (AsyncResult)msg.obj;
1222
1223                if (ar.exception != null) {
1224                    break;
1225                }
1226                String[] respId = (String[])ar.result;
1227                mImei = respId[0];
1228                mImeiSv = respId[1];
1229                mEsn  =  respId[2];
1230                mMeid =  respId[3];
1231            }
1232            break;
1233
1234            case EVENT_EMERGENCY_CALLBACK_MODE_ENTER:{
1235                handleEnterEmergencyCallbackMode(msg);
1236            }
1237            break;
1238
1239            case EVENT_ICC_RECORD_EVENTS:
1240                ar = (AsyncResult)msg.obj;
1241                processIccRecordEvents((Integer)ar.result);
1242                break;
1243
1244            case  EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE:{
1245                handleExitEmergencyCallbackMode(msg);
1246            }
1247            break;
1248
1249            case EVENT_RUIM_RECORDS_LOADED:{
1250                Rlog.d(LOG_TAG, "Event EVENT_RUIM_RECORDS_LOADED Received");
1251                updateCurrentCarrierInProvider();
1252                // Notify voicemails.
1253                log("notifyMessageWaitingChanged");
1254                mNotifier.notifyMessageWaitingChanged(this);
1255            }
1256            break;
1257
1258            case EVENT_RADIO_OFF_OR_NOT_AVAILABLE:{
1259                Rlog.d(LOG_TAG, "Event EVENT_RADIO_OFF_OR_NOT_AVAILABLE Received");
1260                ImsPhone imsPhone = mImsPhone;
1261                if (imsPhone != null) {
1262                    imsPhone.getServiceState().setStateOff();
1263                }
1264            }
1265            break;
1266
1267            case EVENT_RADIO_ON:{
1268                Rlog.d(LOG_TAG, "Event EVENT_RADIO_ON Received");
1269                handleCdmaSubscriptionSource(mCdmaSSM.getCdmaSubscriptionSource());
1270            }
1271            break;
1272
1273            case EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED:{
1274                Rlog.d(LOG_TAG, "EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED");
1275                handleCdmaSubscriptionSource(mCdmaSSM.getCdmaSubscriptionSource());
1276            }
1277            break;
1278
1279            case EVENT_SSN:{
1280                Rlog.d(LOG_TAG, "Event EVENT_SSN Received");
1281            }
1282            break;
1283
1284            case EVENT_REGISTERED_TO_NETWORK:{
1285                Rlog.d(LOG_TAG, "Event EVENT_REGISTERED_TO_NETWORK Received");
1286            }
1287            break;
1288
1289            case EVENT_NV_READY:{
1290                Rlog.d(LOG_TAG, "Event EVENT_NV_READY Received");
1291                prepareEri();
1292                // Notify voicemails.
1293                log("notifyMessageWaitingChanged");
1294                mNotifier.notifyMessageWaitingChanged(this);
1295            }
1296            break;
1297
1298            case EVENT_SET_VM_NUMBER_DONE:{
1299                ar = (AsyncResult)msg.obj;
1300                if (IccException.class.isInstance(ar.exception)) {
1301                    storeVoiceMailNumber(mVmNumber);
1302                    ar.exception = null;
1303                }
1304                onComplete = (Message) ar.userObj;
1305                if (onComplete != null) {
1306                    AsyncResult.forMessage(onComplete, ar.result, ar.exception);
1307                    onComplete.sendToTarget();
1308                }
1309            }
1310            break;
1311
1312            default:{
1313                super.handleMessage(msg);
1314            }
1315        }
1316    }
1317
1318    protected UiccCardApplication getUiccCardApplication() {
1319        return  mUiccController.getUiccCardApplication(mPhoneId, UiccController.APP_FAM_3GPP2);
1320    }
1321
1322    @Override
1323    protected void onUpdateIccAvailability() {
1324        if (mUiccController == null ) {
1325            return;
1326        }
1327
1328        UiccCardApplication newUiccApplication = getUiccCardApplication();
1329
1330        if (newUiccApplication == null) {
1331            log("can't find 3GPP2 application; trying APP_FAM_3GPP");
1332            newUiccApplication =
1333                    mUiccController.getUiccCardApplication(mPhoneId, UiccController.APP_FAM_3GPP);
1334        }
1335
1336        UiccCardApplication app = mUiccApplication.get();
1337        if (app != newUiccApplication) {
1338            if (app != null) {
1339                log("Removing stale icc objects.");
1340                if (mIccRecords.get() != null) {
1341                    unregisterForRuimRecordEvents();
1342                }
1343                mIccRecords.set(null);
1344                mUiccApplication.set(null);
1345            }
1346            if (newUiccApplication != null) {
1347                log("New Uicc application found");
1348                mUiccApplication.set(newUiccApplication);
1349                mIccRecords.set(newUiccApplication.getIccRecords());
1350                registerForRuimRecordEvents();
1351            }
1352        }
1353    }
1354
1355    private void processIccRecordEvents(int eventCode) {
1356        switch (eventCode) {
1357            case RuimRecords.EVENT_MWI:
1358                notifyMessageWaitingIndicator();
1359                break;
1360
1361            default:
1362                Rlog.e(LOG_TAG,"Unknown icc records event code " + eventCode);
1363                break;
1364        }
1365    }
1366
1367    /**
1368     * Handles the call to get the subscription source
1369     *
1370     * @param newSubscriptionSource holds the new CDMA subscription source value
1371     */
1372    private void handleCdmaSubscriptionSource(int newSubscriptionSource) {
1373        if (newSubscriptionSource != mCdmaSubscriptionSource) {
1374             mCdmaSubscriptionSource = newSubscriptionSource;
1375             if (newSubscriptionSource == CDMA_SUBSCRIPTION_NV) {
1376                 // NV is ready when subscription source is NV
1377                 sendMessage(obtainMessage(EVENT_NV_READY));
1378             }
1379        }
1380    }
1381
1382    /**
1383     * Retrieves the PhoneSubInfo of the CDMAPhone
1384     */
1385    @Override
1386    public PhoneSubInfo getPhoneSubInfo() {
1387        return mSubInfo;
1388    }
1389
1390    /**
1391     * Retrieves the IccPhoneBookInterfaceManager of the CDMAPhone
1392     */
1393    @Override
1394    public IccPhoneBookInterfaceManager getIccPhoneBookInterfaceManager() {
1395        return mRuimPhoneBookInterfaceManager;
1396    }
1397
1398    public void registerForEriFileLoaded(Handler h, int what, Object obj) {
1399        Registrant r = new Registrant (h, what, obj);
1400        mEriFileLoadedRegistrants.add(r);
1401    }
1402
1403    public void unregisterForEriFileLoaded(Handler h) {
1404        mEriFileLoadedRegistrants.remove(h);
1405    }
1406
1407    // override for allowing access from other classes of this package
1408    /**
1409     * {@inheritDoc}
1410     */
1411    @Override
1412    public void setSystemProperty(String property, String value) {
1413        super.setSystemProperty(property, value);
1414    }
1415
1416    // override for allowing access from other classes of this package
1417    /**
1418     * {@inheritDoc}
1419     */
1420    @Override
1421    public String getSystemProperty(String property, String defValue) {
1422        return super.getSystemProperty(property, defValue);
1423    }
1424
1425    /**
1426     * Activate or deactivate cell broadcast SMS.
1427     *
1428     * @param activate 0 = activate, 1 = deactivate
1429     * @param response Callback message is empty on completion
1430     */
1431    @Override
1432    public void activateCellBroadcastSms(int activate, Message response) {
1433        Rlog.e(LOG_TAG, "[CDMAPhone] activateCellBroadcastSms() is obsolete; use SmsManager");
1434        response.sendToTarget();
1435    }
1436
1437    /**
1438     * Query the current configuration of cdma cell broadcast SMS.
1439     *
1440     * @param response Callback message is empty on completion
1441     */
1442    @Override
1443    public void getCellBroadcastSmsConfig(Message response) {
1444        Rlog.e(LOG_TAG, "[CDMAPhone] getCellBroadcastSmsConfig() is obsolete; use SmsManager");
1445        response.sendToTarget();
1446    }
1447
1448    /**
1449     * Configure cdma cell broadcast SMS.
1450     *
1451     * @param response Callback message is empty on completion
1452     */
1453    @Override
1454    public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response) {
1455        Rlog.e(LOG_TAG, "[CDMAPhone] setCellBroadcastSmsConfig() is obsolete; use SmsManager");
1456        response.sendToTarget();
1457    }
1458
1459    /**
1460     * Returns true if OTA Service Provisioning needs to be performed.
1461     */
1462    @Override
1463    public boolean needsOtaServiceProvisioning() {
1464        return mSST.getOtasp() != ServiceStateTracker.OTASP_NOT_NEEDED;
1465    }
1466
1467    private static final String IS683A_FEATURE_CODE = "*228";
1468    private static final int IS683A_FEATURE_CODE_NUM_DIGITS = 4;
1469    private static final int IS683A_SYS_SEL_CODE_NUM_DIGITS = 2;
1470    private static final int IS683A_SYS_SEL_CODE_OFFSET = 4;
1471
1472    private static final int IS683_CONST_800MHZ_A_BAND = 0;
1473    private static final int IS683_CONST_800MHZ_B_BAND = 1;
1474    private static final int IS683_CONST_1900MHZ_A_BLOCK = 2;
1475    private static final int IS683_CONST_1900MHZ_B_BLOCK = 3;
1476    private static final int IS683_CONST_1900MHZ_C_BLOCK = 4;
1477    private static final int IS683_CONST_1900MHZ_D_BLOCK = 5;
1478    private static final int IS683_CONST_1900MHZ_E_BLOCK = 6;
1479    private static final int IS683_CONST_1900MHZ_F_BLOCK = 7;
1480    private static final int INVALID_SYSTEM_SELECTION_CODE = -1;
1481
1482    private static boolean isIs683OtaSpDialStr(String dialStr) {
1483        int sysSelCodeInt;
1484        boolean isOtaspDialString = false;
1485        int dialStrLen = dialStr.length();
1486
1487        if (dialStrLen == IS683A_FEATURE_CODE_NUM_DIGITS) {
1488            if (dialStr.equals(IS683A_FEATURE_CODE)) {
1489                isOtaspDialString = true;
1490            }
1491        } else {
1492            sysSelCodeInt = extractSelCodeFromOtaSpNum(dialStr);
1493            switch (sysSelCodeInt) {
1494                case IS683_CONST_800MHZ_A_BAND:
1495                case IS683_CONST_800MHZ_B_BAND:
1496                case IS683_CONST_1900MHZ_A_BLOCK:
1497                case IS683_CONST_1900MHZ_B_BLOCK:
1498                case IS683_CONST_1900MHZ_C_BLOCK:
1499                case IS683_CONST_1900MHZ_D_BLOCK:
1500                case IS683_CONST_1900MHZ_E_BLOCK:
1501                case IS683_CONST_1900MHZ_F_BLOCK:
1502                    isOtaspDialString = true;
1503                    break;
1504                default:
1505                    break;
1506            }
1507        }
1508        return isOtaspDialString;
1509    }
1510    /**
1511     * This function extracts the system selection code from the dial string.
1512     */
1513    private static int extractSelCodeFromOtaSpNum(String dialStr) {
1514        int dialStrLen = dialStr.length();
1515        int sysSelCodeInt = INVALID_SYSTEM_SELECTION_CODE;
1516
1517        if ((dialStr.regionMatches(0, IS683A_FEATURE_CODE,
1518                                   0, IS683A_FEATURE_CODE_NUM_DIGITS)) &&
1519            (dialStrLen >= (IS683A_FEATURE_CODE_NUM_DIGITS +
1520                            IS683A_SYS_SEL_CODE_NUM_DIGITS))) {
1521                // Since we checked the condition above, the system selection code
1522                // extracted from dialStr will not cause any exception
1523                sysSelCodeInt = Integer.parseInt (
1524                                dialStr.substring (IS683A_FEATURE_CODE_NUM_DIGITS,
1525                                IS683A_FEATURE_CODE_NUM_DIGITS + IS683A_SYS_SEL_CODE_NUM_DIGITS));
1526        }
1527        if (DBG) Rlog.d(LOG_TAG, "extractSelCodeFromOtaSpNum " + sysSelCodeInt);
1528        return sysSelCodeInt;
1529    }
1530
1531    /**
1532     * This function checks if the system selection code extracted from
1533     * the dial string "sysSelCodeInt' is the system selection code specified
1534     * in the carrier ota sp number schema "sch".
1535     */
1536    private static boolean
1537    checkOtaSpNumBasedOnSysSelCode (int sysSelCodeInt, String sch[]) {
1538        boolean isOtaSpNum = false;
1539        try {
1540            // Get how many number of system selection code ranges
1541            int selRc = Integer.parseInt(sch[1]);
1542            for (int i = 0; i < selRc; i++) {
1543                if (!TextUtils.isEmpty(sch[i+2]) && !TextUtils.isEmpty(sch[i+3])) {
1544                    int selMin = Integer.parseInt(sch[i+2]);
1545                    int selMax = Integer.parseInt(sch[i+3]);
1546                    // Check if the selection code extracted from the dial string falls
1547                    // within any of the range pairs specified in the schema.
1548                    if ((sysSelCodeInt >= selMin) && (sysSelCodeInt <= selMax)) {
1549                        isOtaSpNum = true;
1550                        break;
1551                    }
1552                }
1553            }
1554        } catch (NumberFormatException ex) {
1555            // If the carrier ota sp number schema is not correct, we still allow dial
1556            // and only log the error:
1557            Rlog.e(LOG_TAG, "checkOtaSpNumBasedOnSysSelCode, error", ex);
1558        }
1559        return isOtaSpNum;
1560    }
1561
1562    // Define the pattern/format for carrier specified OTASP number schema.
1563    // It separates by comma and/or whitespace.
1564    private static Pattern pOtaSpNumSchema = Pattern.compile("[,\\s]+");
1565
1566    /**
1567     * The following function checks if a dial string is a carrier specified
1568     * OTASP number or not by checking against the OTASP number schema stored
1569     * in PROPERTY_OTASP_NUM_SCHEMA.
1570     *
1571     * Currently, there are 2 schemas for carriers to specify the OTASP number:
1572     * 1) Use system selection code:
1573     *    The schema is:
1574     *    SELC,the # of code pairs,min1,max1,min2,max2,...
1575     *    e.g "SELC,3,10,20,30,40,60,70" indicates that there are 3 pairs of
1576     *    selection codes, and they are {10,20}, {30,40} and {60,70} respectively.
1577     *
1578     * 2) Use feature code:
1579     *    The schema is:
1580     *    "FC,length of feature code,feature code".
1581     *     e.g "FC,2,*2" indicates that the length of the feature code is 2,
1582     *     and the code itself is "*2".
1583     */
1584    private boolean isCarrierOtaSpNum(String dialStr) {
1585        boolean isOtaSpNum = false;
1586        int sysSelCodeInt = extractSelCodeFromOtaSpNum(dialStr);
1587        if (sysSelCodeInt == INVALID_SYSTEM_SELECTION_CODE) {
1588            return isOtaSpNum;
1589        }
1590        // mCarrierOtaSpNumSchema is retrieved from PROPERTY_OTASP_NUM_SCHEMA:
1591        if (!TextUtils.isEmpty(mCarrierOtaSpNumSchema)) {
1592            Matcher m = pOtaSpNumSchema.matcher(mCarrierOtaSpNumSchema);
1593            if (DBG) {
1594                Rlog.d(LOG_TAG, "isCarrierOtaSpNum,schema" + mCarrierOtaSpNumSchema);
1595            }
1596
1597            if (m.find()) {
1598                String sch[] = pOtaSpNumSchema.split(mCarrierOtaSpNumSchema);
1599                // If carrier uses system selection code mechanism
1600                if (!TextUtils.isEmpty(sch[0]) && sch[0].equals("SELC")) {
1601                    if (sysSelCodeInt!=INVALID_SYSTEM_SELECTION_CODE) {
1602                        isOtaSpNum=checkOtaSpNumBasedOnSysSelCode(sysSelCodeInt,sch);
1603                    } else {
1604                        if (DBG) {
1605                            Rlog.d(LOG_TAG, "isCarrierOtaSpNum,sysSelCodeInt is invalid");
1606                        }
1607                    }
1608                } else if (!TextUtils.isEmpty(sch[0]) && sch[0].equals("FC")) {
1609                    int fcLen =  Integer.parseInt(sch[1]);
1610                    String fc = sch[2];
1611                    if (dialStr.regionMatches(0,fc,0,fcLen)) {
1612                        isOtaSpNum = true;
1613                    } else {
1614                        if (DBG) Rlog.d(LOG_TAG, "isCarrierOtaSpNum,not otasp number");
1615                    }
1616                } else {
1617                    if (DBG) {
1618                        Rlog.d(LOG_TAG, "isCarrierOtaSpNum,ota schema not supported" + sch[0]);
1619                    }
1620                }
1621            } else {
1622                if (DBG) {
1623                    Rlog.d(LOG_TAG, "isCarrierOtaSpNum,ota schema pattern not right" +
1624                          mCarrierOtaSpNumSchema);
1625                }
1626            }
1627        } else {
1628            if (DBG) Rlog.d(LOG_TAG, "isCarrierOtaSpNum,ota schema pattern empty");
1629        }
1630        return isOtaSpNum;
1631    }
1632
1633    /**
1634     * isOTASPNumber: checks a given number against the IS-683A OTASP dial string and carrier
1635     * OTASP dial string.
1636     *
1637     * @param dialStr the number to look up.
1638     * @return true if the number is in IS-683A OTASP dial string or carrier OTASP dial string
1639     */
1640    @Override
1641    public  boolean isOtaSpNumber(String dialStr){
1642        boolean isOtaSpNum = false;
1643        String dialableStr = PhoneNumberUtils.extractNetworkPortionAlt(dialStr);
1644        if (dialableStr != null) {
1645            isOtaSpNum = isIs683OtaSpDialStr(dialableStr);
1646            if (isOtaSpNum == false) {
1647                isOtaSpNum = isCarrierOtaSpNum(dialableStr);
1648            }
1649        }
1650        if (DBG) Rlog.d(LOG_TAG, "isOtaSpNumber " + isOtaSpNum);
1651        return isOtaSpNum;
1652    }
1653
1654    @Override
1655    public int getCdmaEriIconIndex() {
1656        return getServiceState().getCdmaEriIconIndex();
1657    }
1658
1659    /**
1660     * Returns the CDMA ERI icon mode,
1661     * 0 - ON
1662     * 1 - FLASHING
1663     */
1664    @Override
1665    public int getCdmaEriIconMode() {
1666        return getServiceState().getCdmaEriIconMode();
1667    }
1668
1669    /**
1670     * Returns the CDMA ERI text,
1671     */
1672    @Override
1673    public String getCdmaEriText() {
1674        int roamInd = getServiceState().getCdmaRoamingIndicator();
1675        int defRoamInd = getServiceState().getCdmaDefaultRoamingIndicator();
1676        return mEriManager.getCdmaEriText(roamInd, defRoamInd);
1677    }
1678
1679    /**
1680     * Store the voicemail number in preferences
1681     */
1682    private void storeVoiceMailNumber(String number) {
1683        // Update the preference value of voicemail number
1684        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
1685        SharedPreferences.Editor editor = sp.edit();
1686        editor.putString(VM_NUMBER_CDMA + getPhoneId(), number);
1687        editor.apply();
1688    }
1689
1690    /**
1691     * Sets PROPERTY_ICC_OPERATOR_ISO_COUNTRY property
1692     *
1693     */
1694    protected void setIsoCountryProperty(String operatorNumeric) {
1695        if (TextUtils.isEmpty(operatorNumeric)) {
1696            log("setIsoCountryProperty: clear 'gsm.sim.operator.iso-country'");
1697            setSystemProperty(PROPERTY_ICC_OPERATOR_ISO_COUNTRY, "");
1698        } else {
1699            String iso = "";
1700            try {
1701                iso = MccTable.countryCodeForMcc(Integer.parseInt(
1702                        operatorNumeric.substring(0,3)));
1703            } catch (NumberFormatException ex) {
1704                loge("setIsoCountryProperty: countryCodeForMcc error", ex);
1705            } catch (StringIndexOutOfBoundsException ex) {
1706                loge("setIsoCountryProperty: countryCodeForMcc error", ex);
1707            }
1708
1709            log("setIsoCountryProperty: set 'gsm.sim.operator.iso-country' to iso=" + iso);
1710            setSystemProperty(PROPERTY_ICC_OPERATOR_ISO_COUNTRY, iso);
1711        }
1712    }
1713
1714    /**
1715     * Sets the "current" field in the telephony provider according to the
1716     * build-time operator numeric property
1717     *
1718     * @return true for success; false otherwise.
1719     */
1720    boolean updateCurrentCarrierInProvider(String operatorNumeric) {
1721        log("CDMAPhone: updateCurrentCarrierInProvider called");
1722        if (!TextUtils.isEmpty(operatorNumeric)) {
1723            try {
1724                Uri uri = Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current");
1725                ContentValues map = new ContentValues();
1726                map.put(Telephony.Carriers.NUMERIC, operatorNumeric);
1727                log("updateCurrentCarrierInProvider from system: numeric=" + operatorNumeric);
1728                getContext().getContentResolver().insert(uri, map);
1729
1730                // Updates MCC MNC device configuration information
1731                log("update mccmnc=" + operatorNumeric);
1732                MccTable.updateMccMncConfiguration(mContext, operatorNumeric, false);
1733
1734                return true;
1735            } catch (SQLException e) {
1736                Rlog.e(LOG_TAG, "Can't store current operator", e);
1737            }
1738        }
1739        return false;
1740    }
1741
1742    /**
1743     * Sets the "current" field in the telephony provider according to the SIM's operator.
1744     * Implemented in {@link CDMALTEPhone} for CDMA/LTE devices.
1745     *
1746     * @return true for success; false otherwise.
1747     */
1748    boolean updateCurrentCarrierInProvider() {
1749        return true;
1750    }
1751
1752    public void prepareEri() {
1753        if (mEriManager == null) {
1754            Rlog.e(LOG_TAG, "PrepareEri: Trying to access stale objects");
1755            return;
1756        }
1757        mEriManager.loadEriFile();
1758        if(mEriManager.isEriFileLoaded()) {
1759            // when the ERI file is loaded
1760            log("ERI read, notify registrants");
1761            mEriFileLoadedRegistrants.notifyRegistrants();
1762        }
1763    }
1764
1765    public boolean isEriFileLoaded() {
1766        return mEriManager.isEriFileLoaded();
1767    }
1768
1769    protected void registerForRuimRecordEvents() {
1770        IccRecords r = mIccRecords.get();
1771        if (r == null) {
1772            return;
1773        }
1774        r.registerForRecordsEvents(this, EVENT_ICC_RECORD_EVENTS, null);
1775        r.registerForRecordsLoaded(this, EVENT_RUIM_RECORDS_LOADED, null);
1776    }
1777
1778    protected void unregisterForRuimRecordEvents() {
1779        IccRecords r = mIccRecords.get();
1780        if (r == null) {
1781            return;
1782        }
1783        r.unregisterForRecordsEvents(this);
1784        r.unregisterForRecordsLoaded(this);
1785    }
1786
1787    protected void log(String s) {
1788        if (DBG)
1789            Rlog.d(LOG_TAG, s);
1790    }
1791
1792    protected void loge(String s, Exception e) {
1793        if (DBG)
1794            Rlog.e(LOG_TAG, s, e);
1795    }
1796
1797    @Override
1798    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1799        pw.println("CDMAPhone extends:");
1800        super.dump(fd, pw, args);
1801        pw.println(" mVmNumber=" + mVmNumber);
1802        pw.println(" mCT=" + mCT);
1803        pw.println(" mSST=" + mSST);
1804        pw.println(" mCdmaSSM=" + mCdmaSSM);
1805        pw.println(" mPendingMmis=" + mPendingMmis);
1806        pw.println(" mRuimPhoneBookInterfaceManager=" + mRuimPhoneBookInterfaceManager);
1807        pw.println(" mCdmaSubscriptionSource=" + mCdmaSubscriptionSource);
1808        pw.println(" mSubInfo=" + mSubInfo);
1809        pw.println(" mEriManager=" + mEriManager);
1810        pw.println(" mWakeLock=" + mWakeLock);
1811        pw.println(" mIsPhoneInEcmState=" + mIsPhoneInEcmState);
1812        if (VDBG) pw.println(" mImei=" + mImei);
1813        if (VDBG) pw.println(" mImeiSv=" + mImeiSv);
1814        if (VDBG) pw.println(" mEsn=" + mEsn);
1815        if (VDBG) pw.println(" mMeid=" + mMeid);
1816        pw.println(" mCarrierOtaSpNumSchema=" + mCarrierOtaSpNumSchema);
1817        pw.println(" getCdmaEriIconIndex()=" + getCdmaEriIconIndex());
1818        pw.println(" getCdmaEriIconMode()=" + getCdmaEriIconMode());
1819        pw.println(" getCdmaEriText()=" + getCdmaEriText());
1820        pw.println(" isMinInfoReady()=" + isMinInfoReady());
1821        pw.println(" isCspPlmnEnabled()=" + isCspPlmnEnabled());
1822    }
1823
1824    @Override
1825    public boolean setOperatorBrandOverride(String brand) {
1826        if (mUiccController == null) {
1827            return false;
1828        }
1829
1830        UiccCard card = mUiccController.getUiccCard();
1831        if (card == null) {
1832            return false;
1833        }
1834
1835        boolean status = card.setOperatorBrandOverride(brand);
1836
1837        // Refresh.
1838        if (status) {
1839            IccRecords iccRecords = mIccRecords.get();
1840            if (iccRecords != null) {
1841                SystemProperties.set(TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA,
1842                        iccRecords.getServiceProviderName());
1843            }
1844            if (mSST != null) {
1845                mSST.pollState();
1846            }
1847        }
1848        return status;
1849    }
1850}
1851