ServiceStateTracker.java revision bed429d6d0a0dbc6384b04e0641aa1e03e406f42
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;
18
19import android.app.PendingIntent;
20import android.content.Context;
21import android.content.IntentFilter;
22import android.os.AsyncResult;
23import android.os.Handler;
24import android.os.Message;
25import android.os.Registrant;
26import android.os.RegistrantList;
27import android.os.SystemClock;
28import android.telephony.CellInfo;
29import android.telephony.ServiceState;
30import android.telephony.SignalStrength;
31import android.telephony.TelephonyManager;
32import android.text.TextUtils;
33import android.util.Pair;
34import android.util.TimeUtils;
35
36import java.io.FileDescriptor;
37import java.io.PrintWriter;
38import java.util.ArrayList;
39import java.util.List;
40
41import com.android.internal.telephony.dataconnection.DcTrackerBase;
42import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState;
43import com.android.internal.telephony.uicc.IccRecords;
44import com.android.internal.telephony.uicc.UiccCardApplication;
45import com.android.internal.telephony.uicc.UiccController;
46
47/**
48 * {@hide}
49 */
50public abstract class ServiceStateTracker extends Handler {
51    protected  static final boolean DBG = true;
52    protected static final boolean VDBG = false;
53
54    protected static final String PROP_FORCE_ROAMING = "telephony.test.forceRoaming";
55
56    protected CommandsInterface mCi;
57    protected UiccController mUiccController = null;
58    protected UiccCardApplication mUiccApplcation = null;
59    protected IccRecords mIccRecords = null;
60
61    protected PhoneBase mPhoneBase;
62
63    protected boolean mVoiceCapable;
64
65    public ServiceState mSS = new ServiceState();
66    protected ServiceState mNewSS = new ServiceState();
67
68    private static final long LAST_CELL_INFO_LIST_MAX_AGE_MS = 2000;
69    protected long mLastCellInfoListTime;
70    protected List<CellInfo> mLastCellInfoList = null;
71
72    // This is final as subclasses alias to a more specific type
73    // so we don't want the reference to change.
74    protected final CellInfo mCellInfo;
75
76    protected SignalStrength mSignalStrength = new SignalStrength();
77
78    // TODO - this should not be public, right now used externally GsmConnetion.
79    public RestrictedState mRestrictedState = new RestrictedState();
80
81    /* The otaspMode passed to PhoneStateListener#onOtaspChanged */
82    static public final int OTASP_UNINITIALIZED = 0;
83    static public final int OTASP_UNKNOWN = 1;
84    static public final int OTASP_NEEDED = 2;
85    static public final int OTASP_NOT_NEEDED = 3;
86
87    /**
88     * A unique identifier to track requests associated with a poll
89     * and ignore stale responses.  The value is a count-down of
90     * expected responses in this pollingContext.
91     */
92    protected int[] mPollingContext;
93    protected boolean mDesiredPowerState;
94
95    /**
96     * By default, strength polling is enabled.  However, if we're
97     * getting unsolicited signal strength updates from the radio, set
98     * value to true and don't bother polling any more.
99     */
100    protected boolean mDontPollSignalStrength = false;
101
102    protected RegistrantList mRoamingOnRegistrants = new RegistrantList();
103    protected RegistrantList mRoamingOffRegistrants = new RegistrantList();
104    protected RegistrantList mAttachedRegistrants = new RegistrantList();
105    protected RegistrantList mDetachedRegistrants = new RegistrantList();
106    protected RegistrantList mDataRegStateOrRatChangedRegistrants = new RegistrantList();
107    protected RegistrantList mNetworkAttachedRegistrants = new RegistrantList();
108    protected RegistrantList mPsRestrictEnabledRegistrants = new RegistrantList();
109    protected RegistrantList mPsRestrictDisabledRegistrants = new RegistrantList();
110
111    /* Radio power off pending flag and tag counter */
112    protected boolean mPendingRadioPowerOffAfterDataOff = false;
113    protected int mPendingRadioPowerOffAfterDataOffTag = 0;
114
115    /** Signal strength poll rate. */
116    protected static final int POLL_PERIOD_MILLIS = 20 * 1000;
117
118    /** Waiting period before recheck gprs and voice registration. */
119    public static final int DEFAULT_GPRS_CHECK_PERIOD_MILLIS = 60 * 1000;
120
121    /** GSM events */
122    protected static final int EVENT_RADIO_STATE_CHANGED               = 1;
123    protected static final int EVENT_NETWORK_STATE_CHANGED             = 2;
124    protected static final int EVENT_GET_SIGNAL_STRENGTH               = 3;
125    protected static final int EVENT_POLL_STATE_REGISTRATION           = 4;
126    protected static final int EVENT_POLL_STATE_GPRS                   = 5;
127    protected static final int EVENT_POLL_STATE_OPERATOR               = 6;
128    protected static final int EVENT_POLL_SIGNAL_STRENGTH              = 10;
129    protected static final int EVENT_NITZ_TIME                         = 11;
130    protected static final int EVENT_SIGNAL_STRENGTH_UPDATE            = 12;
131    protected static final int EVENT_RADIO_AVAILABLE                   = 13;
132    protected static final int EVENT_POLL_STATE_NETWORK_SELECTION_MODE = 14;
133    protected static final int EVENT_GET_LOC_DONE                      = 15;
134    protected static final int EVENT_SIM_RECORDS_LOADED                = 16;
135    protected static final int EVENT_SIM_READY                         = 17;
136    protected static final int EVENT_LOCATION_UPDATES_ENABLED          = 18;
137    protected static final int EVENT_GET_PREFERRED_NETWORK_TYPE        = 19;
138    protected static final int EVENT_SET_PREFERRED_NETWORK_TYPE        = 20;
139    protected static final int EVENT_RESET_PREFERRED_NETWORK_TYPE      = 21;
140    protected static final int EVENT_CHECK_REPORT_GPRS                 = 22;
141    protected static final int EVENT_RESTRICTED_STATE_CHANGED          = 23;
142
143    /** CDMA events */
144    protected static final int EVENT_POLL_STATE_REGISTRATION_CDMA      = 24;
145    protected static final int EVENT_POLL_STATE_OPERATOR_CDMA          = 25;
146    protected static final int EVENT_RUIM_READY                        = 26;
147    protected static final int EVENT_RUIM_RECORDS_LOADED               = 27;
148    protected static final int EVENT_POLL_SIGNAL_STRENGTH_CDMA         = 28;
149    protected static final int EVENT_GET_SIGNAL_STRENGTH_CDMA          = 29;
150    protected static final int EVENT_NETWORK_STATE_CHANGED_CDMA        = 30;
151    protected static final int EVENT_GET_LOC_DONE_CDMA                 = 31;
152    //protected static final int EVENT_UNUSED                            = 32;
153    protected static final int EVENT_NV_LOADED                         = 33;
154    protected static final int EVENT_POLL_STATE_CDMA_SUBSCRIPTION      = 34;
155    protected static final int EVENT_NV_READY                          = 35;
156    protected static final int EVENT_ERI_FILE_LOADED                   = 36;
157    protected static final int EVENT_OTA_PROVISION_STATUS_CHANGE       = 37;
158    protected static final int EVENT_SET_RADIO_POWER_OFF               = 38;
159    protected static final int EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED  = 39;
160    protected static final int EVENT_CDMA_PRL_VERSION_CHANGED          = 40;
161    protected static final int EVENT_RADIO_ON                          = 41;
162    public static final int EVENT_ICC_CHANGED                          = 42;
163    protected static final int EVENT_GET_CELL_INFO_LIST                = 43;
164    protected static final int EVENT_UNSOL_CELL_INFO_LIST              = 44;
165    protected static final int EVENT_CHANGE_IMS_STATE                  = 45;
166
167    protected static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
168
169    /**
170     * List of ISO codes for countries that can have an offset of
171     * GMT+0 when not in daylight savings time.  This ignores some
172     * small places such as the Canary Islands (Spain) and
173     * Danmarkshavn (Denmark).  The list must be sorted by code.
174    */
175    protected static final String[] GMT_COUNTRY_CODES = {
176        "bf", // Burkina Faso
177        "ci", // Cote d'Ivoire
178        "eh", // Western Sahara
179        "fo", // Faroe Islands, Denmark
180        "gb", // United Kingdom of Great Britain and Northern Ireland
181        "gh", // Ghana
182        "gm", // Gambia
183        "gn", // Guinea
184        "gw", // Guinea Bissau
185        "ie", // Ireland
186        "lr", // Liberia
187        "is", // Iceland
188        "ma", // Morocco
189        "ml", // Mali
190        "mr", // Mauritania
191        "pt", // Portugal
192        "sl", // Sierra Leone
193        "sn", // Senegal
194        "st", // Sao Tome and Principe
195        "tg", // Togo
196    };
197
198    private class CellInfoResult {
199        List<CellInfo> list;
200        Object lockObj = new Object();
201    }
202
203    /** Reason for registration denial. */
204    protected static final String REGISTRATION_DENIED_GEN  = "General";
205    protected static final String REGISTRATION_DENIED_AUTH = "Authentication Failure";
206
207    protected boolean mImsRegistrationOnOff = false;
208    protected boolean mAlarmSwitch = false;
209    protected IntentFilter mIntentFilter = null;
210    protected PendingIntent mRadioOffIntent = null;
211    protected static final String ACTION_RADIO_OFF = "android.intent.action.ACTION_RADIO_OFF";
212    protected boolean mPowerOffDelayNeed = true;
213    protected boolean mDeviceShuttingDown = false;
214
215
216    protected ServiceStateTracker(PhoneBase phoneBase, CommandsInterface ci, CellInfo cellInfo) {
217        mPhoneBase = phoneBase;
218        mCellInfo = cellInfo;
219        mCi = ci;
220        mVoiceCapable = mPhoneBase.getContext().getResources().getBoolean(
221                com.android.internal.R.bool.config_voice_capable);
222        mUiccController = UiccController.getInstance();
223        mUiccController.registerForIccChanged(this, EVENT_ICC_CHANGED, null);
224        mCi.setOnSignalStrengthUpdate(this, EVENT_SIGNAL_STRENGTH_UPDATE, null);
225        mCi.registerForCellInfoList(this, EVENT_UNSOL_CELL_INFO_LIST, null);
226
227        mPhoneBase.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
228            ServiceState.rilRadioTechnologyToString(ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN));
229    }
230
231    void requestShutdown() {
232        if (mDeviceShuttingDown == true) return;
233        mDeviceShuttingDown = true;
234        mDesiredPowerState = false;
235        setPowerStateToDesired();
236    }
237
238    public void dispose() {
239        mCi.unSetOnSignalStrengthUpdate(this);
240        mUiccController.unregisterForIccChanged(this);
241        mCi.unregisterForCellInfoList(this);
242    }
243
244    public boolean getDesiredPowerState() {
245        return mDesiredPowerState;
246    }
247
248    private SignalStrength mLastSignalStrength = null;
249    protected boolean notifySignalStrength() {
250        boolean notified = false;
251        synchronized(mCellInfo) {
252            if (!mSignalStrength.equals(mLastSignalStrength)) {
253                try {
254                    mPhoneBase.notifySignalStrength();
255                    notified = true;
256                } catch (NullPointerException ex) {
257                    loge("updateSignalStrength() Phone already destroyed: " + ex
258                            + "SignalStrength not notified");
259                }
260            }
261        }
262        return notified;
263    }
264
265    /**
266     * Notify all mDataConnectionRatChangeRegistrants using an
267     * AsyncResult in msg.obj where AsyncResult#result contains the
268     * new RAT as an Integer Object.
269     */
270    protected void notifyDataRegStateRilRadioTechnologyChanged() {
271        int rat = mSS.getRilDataRadioTechnology();
272        int drs = mSS.getDataRegState();
273        if (DBG) log("notifyDataRegStateRilRadioTechnologyChanged: drs=" + drs + " rat=" + rat);
274        mPhoneBase.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
275                ServiceState.rilRadioTechnologyToString(rat));
276        mDataRegStateOrRatChangedRegistrants.notifyResult(new Pair<Integer, Integer>(drs, rat));
277    }
278
279    /**
280     * Some operators have been known to report registration failure
281     * data only devices, to fix that use DataRegState.
282     */
283    protected void useDataRegStateForDataOnlyDevices() {
284        if (mVoiceCapable == false) {
285            if (DBG) {
286                log("useDataRegStateForDataOnlyDevice: VoiceRegState=" + mNewSS.getVoiceRegState()
287                    + " DataRegState=" + mNewSS.getDataRegState());
288            }
289            // TODO: Consider not lying and instead have callers know the difference.
290            mNewSS.setVoiceRegState(mNewSS.getDataRegState());
291        }
292    }
293
294    protected void updatePhoneObject() {
295        mPhoneBase.updatePhoneObject(mSS.getRilVoiceRadioTechnology());
296    }
297
298    /**
299     * Registration point for combined roaming on
300     * combined roaming is true when roaming is true and ONS differs SPN
301     *
302     * @param h handler to notify
303     * @param what what code of message when delivered
304     * @param obj placed in Message.obj
305     */
306    public  void registerForRoamingOn(Handler h, int what, Object obj) {
307        Registrant r = new Registrant(h, what, obj);
308        mRoamingOnRegistrants.add(r);
309
310        if (mSS.getRoaming()) {
311            r.notifyRegistrant();
312        }
313    }
314
315    public  void unregisterForRoamingOn(Handler h) {
316        mRoamingOnRegistrants.remove(h);
317    }
318
319    /**
320     * Registration point for combined roaming off
321     * combined roaming is true when roaming is true and ONS differs SPN
322     *
323     * @param h handler to notify
324     * @param what what code of message when delivered
325     * @param obj placed in Message.obj
326     */
327    public  void registerForRoamingOff(Handler h, int what, Object obj) {
328        Registrant r = new Registrant(h, what, obj);
329        mRoamingOffRegistrants.add(r);
330
331        if (!mSS.getRoaming()) {
332            r.notifyRegistrant();
333        }
334    }
335
336    public  void unregisterForRoamingOff(Handler h) {
337        mRoamingOffRegistrants.remove(h);
338    }
339
340    /**
341     * Re-register network by toggling preferred network type.
342     * This is a work-around to deregister and register network since there is
343     * no ril api to set COPS=2 (deregister) only.
344     *
345     * @param onComplete is dispatched when this is complete.  it will be
346     * an AsyncResult, and onComplete.obj.exception will be non-null
347     * on failure.
348     */
349    public void reRegisterNetwork(Message onComplete) {
350        mCi.getPreferredNetworkType(
351                obtainMessage(EVENT_GET_PREFERRED_NETWORK_TYPE, onComplete));
352    }
353
354    public void
355    setRadioPower(boolean power) {
356        mDesiredPowerState = power;
357
358        setPowerStateToDesired();
359    }
360
361    /**
362     * These two flags manage the behavior of the cell lock -- the
363     * lock should be held if either flag is true.  The intention is
364     * to allow temporary acquisition of the lock to get a single
365     * update.  Such a lock grab and release can thus be made to not
366     * interfere with more permanent lock holds -- in other words, the
367     * lock will only be released if both flags are false, and so
368     * releases by temporary users will only affect the lock state if
369     * there is no continuous user.
370     */
371    private boolean mWantContinuousLocationUpdates;
372    private boolean mWantSingleLocationUpdate;
373
374    public void enableSingleLocationUpdate() {
375        if (mWantSingleLocationUpdate || mWantContinuousLocationUpdates) return;
376        mWantSingleLocationUpdate = true;
377        mCi.setLocationUpdates(true, obtainMessage(EVENT_LOCATION_UPDATES_ENABLED));
378    }
379
380    public void enableLocationUpdates() {
381        if (mWantSingleLocationUpdate || mWantContinuousLocationUpdates) return;
382        mWantContinuousLocationUpdates = true;
383        mCi.setLocationUpdates(true, obtainMessage(EVENT_LOCATION_UPDATES_ENABLED));
384    }
385
386    protected void disableSingleLocationUpdate() {
387        mWantSingleLocationUpdate = false;
388        if (!mWantSingleLocationUpdate && !mWantContinuousLocationUpdates) {
389            mCi.setLocationUpdates(false, null);
390        }
391    }
392
393    public void disableLocationUpdates() {
394        mWantContinuousLocationUpdates = false;
395        if (!mWantSingleLocationUpdate && !mWantContinuousLocationUpdates) {
396            mCi.setLocationUpdates(false, null);
397        }
398    }
399
400    @Override
401    public void handleMessage(Message msg) {
402        switch (msg.what) {
403            case EVENT_SET_RADIO_POWER_OFF:
404                synchronized(this) {
405                    if (mPendingRadioPowerOffAfterDataOff &&
406                            (msg.arg1 == mPendingRadioPowerOffAfterDataOffTag)) {
407                        if (DBG) log("EVENT_SET_RADIO_OFF, turn radio off now.");
408                        hangupAndPowerOff();
409                        mPendingRadioPowerOffAfterDataOffTag += 1;
410                        mPendingRadioPowerOffAfterDataOff = false;
411                    } else {
412                        log("EVENT_SET_RADIO_OFF is stale arg1=" + msg.arg1 +
413                                "!= tag=" + mPendingRadioPowerOffAfterDataOffTag);
414                    }
415                }
416                break;
417
418            case EVENT_ICC_CHANGED:
419                onUpdateIccAvailability();
420                break;
421
422            case EVENT_GET_CELL_INFO_LIST: {
423                AsyncResult ar = (AsyncResult) msg.obj;
424                CellInfoResult result = (CellInfoResult) ar.userObj;
425                synchronized(result.lockObj) {
426                    if (ar.exception != null) {
427                        log("EVENT_GET_CELL_INFO_LIST: error ret null, e=" + ar.exception);
428                        result.list = null;
429                    } else {
430                        result.list = (List<CellInfo>) ar.result;
431
432                        if (VDBG) {
433                            log("EVENT_GET_CELL_INFO_LIST: size=" + result.list.size()
434                                    + " list=" + result.list);
435                        }
436                    }
437                    mLastCellInfoListTime = SystemClock.elapsedRealtime();
438                    mLastCellInfoList = result.list;
439                    result.lockObj.notify();
440                }
441                break;
442            }
443
444            case EVENT_UNSOL_CELL_INFO_LIST: {
445                AsyncResult ar = (AsyncResult) msg.obj;
446                if (ar.exception != null) {
447                    log("EVENT_UNSOL_CELL_INFO_LIST: error ignoring, e=" + ar.exception);
448                } else {
449                    List<CellInfo> list = (List<CellInfo>) ar.result;
450                    if (DBG) {
451                        log("EVENT_UNSOL_CELL_INFO_LIST: size=" + list.size()
452                                + " list=" + list);
453                    }
454                    mLastCellInfoListTime = SystemClock.elapsedRealtime();
455                    mLastCellInfoList = list;
456                    mPhoneBase.notifyCellInfo(list);
457                }
458                break;
459            }
460
461            default:
462                log("Unhandled message with number: " + msg.what);
463                break;
464        }
465    }
466
467    protected abstract Phone getPhone();
468    protected abstract void handlePollStateResult(int what, AsyncResult ar);
469    protected abstract void updateSpnDisplay();
470    protected abstract void setPowerStateToDesired();
471    protected abstract void onUpdateIccAvailability();
472    protected abstract void log(String s);
473    protected abstract void loge(String s);
474
475    public abstract int getCurrentDataConnectionState();
476    public abstract boolean isConcurrentVoiceAndDataAllowed();
477
478    public abstract void setImsRegistrationState(boolean registered);
479    public abstract void pollState();
480
481    /**
482     * Registration point for transition into DataConnection attached.
483     * @param h handler to notify
484     * @param what what code of message when delivered
485     * @param obj placed in Message.obj
486     */
487    public void registerForDataConnectionAttached(Handler h, int what, Object obj) {
488        Registrant r = new Registrant(h, what, obj);
489        mAttachedRegistrants.add(r);
490
491        if (getCurrentDataConnectionState() == ServiceState.STATE_IN_SERVICE) {
492            r.notifyRegistrant();
493        }
494    }
495    public void unregisterForDataConnectionAttached(Handler h) {
496        mAttachedRegistrants.remove(h);
497    }
498
499    /**
500     * Registration point for transition into DataConnection detached.
501     * @param h handler to notify
502     * @param what what code of message when delivered
503     * @param obj placed in Message.obj
504     */
505    public void registerForDataConnectionDetached(Handler h, int what, Object obj) {
506        Registrant r = new Registrant(h, what, obj);
507        mDetachedRegistrants.add(r);
508
509        if (getCurrentDataConnectionState() != ServiceState.STATE_IN_SERVICE) {
510            r.notifyRegistrant();
511        }
512    }
513    public void unregisterForDataConnectionDetached(Handler h) {
514        mDetachedRegistrants.remove(h);
515    }
516
517    /**
518     * Registration for DataConnection RIL Data Radio Technology changing. The
519     * new radio technology will be returned AsyncResult#result as an Integer Object.
520     * The AsyncResult will be in the notification Message#obj.
521     *
522     * @param h handler to notify
523     * @param what what code of message when delivered
524     * @param obj placed in Message.obj
525     */
526    public void registerForDataRegStateOrRatChanged(Handler h, int what, Object obj) {
527        Registrant r = new Registrant(h, what, obj);
528        mDataRegStateOrRatChangedRegistrants.add(r);
529        notifyDataRegStateRilRadioTechnologyChanged();
530    }
531    public void unregisterForDataRegStateOrRatChanged(Handler h) {
532        mDataRegStateOrRatChangedRegistrants.remove(h);
533    }
534
535    /**
536     * Registration point for transition into network attached.
537     * @param h handler to notify
538     * @param what what code of message when delivered
539     * @param obj in Message.obj
540     */
541    public void registerForNetworkAttached(Handler h, int what, Object obj) {
542        Registrant r = new Registrant(h, what, obj);
543
544        mNetworkAttachedRegistrants.add(r);
545        if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE) {
546            r.notifyRegistrant();
547        }
548    }
549    public void unregisterForNetworkAttached(Handler h) {
550        mNetworkAttachedRegistrants.remove(h);
551    }
552
553    /**
554     * Registration point for transition into packet service restricted zone.
555     * @param h handler to notify
556     * @param what what code of message when delivered
557     * @param obj placed in Message.obj
558     */
559    public void registerForPsRestrictedEnabled(Handler h, int what, Object obj) {
560        Registrant r = new Registrant(h, what, obj);
561        mPsRestrictEnabledRegistrants.add(r);
562
563        if (mRestrictedState.isPsRestricted()) {
564            r.notifyRegistrant();
565        }
566    }
567
568    public void unregisterForPsRestrictedEnabled(Handler h) {
569        mPsRestrictEnabledRegistrants.remove(h);
570    }
571
572    /**
573     * Registration point for transition out of packet service restricted zone.
574     * @param h handler to notify
575     * @param what what code of message when delivered
576     * @param obj placed in Message.obj
577     */
578    public void registerForPsRestrictedDisabled(Handler h, int what, Object obj) {
579        Registrant r = new Registrant(h, what, obj);
580        mPsRestrictDisabledRegistrants.add(r);
581
582        if (mRestrictedState.isPsRestricted()) {
583            r.notifyRegistrant();
584        }
585    }
586
587    public void unregisterForPsRestrictedDisabled(Handler h) {
588        mPsRestrictDisabledRegistrants.remove(h);
589    }
590
591    /**
592     * Clean up existing voice and data connection then turn off radio power.
593     *
594     * Hang up the existing voice calls to decrease call drop rate.
595     */
596    public void powerOffRadioSafely(DcTrackerBase dcTracker) {
597        synchronized (this) {
598            if (!mPendingRadioPowerOffAfterDataOff) {
599                // To minimize race conditions we call cleanUpAllConnections on
600                // both if else paths instead of before this isDisconnected test.
601                if (dcTracker.isDisconnected()) {
602                    // To minimize race conditions we do this after isDisconnected
603                    dcTracker.cleanUpAllConnections(Phone.REASON_RADIO_TURNED_OFF);
604                    if (DBG) log("Data disconnected, turn off radio right away.");
605                    hangupAndPowerOff();
606                } else {
607                    dcTracker.cleanUpAllConnections(Phone.REASON_RADIO_TURNED_OFF);
608                    Message msg = Message.obtain(this);
609                    msg.what = EVENT_SET_RADIO_POWER_OFF;
610                    msg.arg1 = ++mPendingRadioPowerOffAfterDataOffTag;
611                    if (sendMessageDelayed(msg, 30000)) {
612                        if (DBG) log("Wait upto 30s for data to disconnect, then turn off radio.");
613                        mPendingRadioPowerOffAfterDataOff = true;
614                    } else {
615                        log("Cannot send delayed Msg, turn off radio right away.");
616                        hangupAndPowerOff();
617                    }
618                }
619            }
620        }
621    }
622
623    /**
624     * process the pending request to turn radio off after data is disconnected
625     *
626     * return true if there is pending request to process; false otherwise.
627     */
628    public boolean processPendingRadioPowerOffAfterDataOff() {
629        synchronized(this) {
630            if (mPendingRadioPowerOffAfterDataOff) {
631                if (DBG) log("Process pending request to turn radio off.");
632                mPendingRadioPowerOffAfterDataOffTag += 1;
633                hangupAndPowerOff();
634                mPendingRadioPowerOffAfterDataOff = false;
635                return true;
636            }
637            return false;
638        }
639    }
640
641    /**
642     * send signal-strength-changed notification if changed Called both for
643     * solicited and unsolicited signal strength updates
644     *
645     * @return true if the signal strength changed and a notification was sent.
646     */
647    protected boolean onSignalStrengthResult(AsyncResult ar, boolean isGsm) {
648        SignalStrength oldSignalStrength = mSignalStrength;
649
650        // This signal is used for both voice and data radio signal so parse
651        // all fields
652
653        if ((ar.exception == null) && (ar.result != null)) {
654            mSignalStrength = (SignalStrength) ar.result;
655            mSignalStrength.validateInput();
656            mSignalStrength.setGsm(isGsm);
657        } else {
658            log("onSignalStrengthResult() Exception from RIL : " + ar.exception);
659            mSignalStrength = new SignalStrength(isGsm);
660        }
661
662        return notifySignalStrength();
663    }
664
665    /**
666     * Hang up all voice call and turn off radio. Implemented by derived class.
667     */
668    protected abstract void hangupAndPowerOff();
669
670    /** Cancel a pending (if any) pollState() operation */
671    protected void cancelPollState() {
672        // This will effectively cancel the rest of the poll requests.
673        mPollingContext = new int[1];
674    }
675
676    /**
677     * Return true if time zone needs fixing.
678     *
679     * @param phoneBase
680     * @param operatorNumeric
681     * @param prevOperatorNumeric
682     * @param needToFixTimeZone
683     * @return true if time zone needs to be fixed
684     */
685    protected boolean shouldFixTimeZoneNow(PhoneBase phoneBase, String operatorNumeric,
686            String prevOperatorNumeric, boolean needToFixTimeZone) {
687        // Return false if the mcc isn't valid as we don't know where we are.
688        // Return true if we have an IccCard and the mcc changed or we
689        // need to fix it because when the NITZ time came in we didn't
690        // know the country code.
691
692        // If mcc is invalid then we'll return false
693        int mcc;
694        try {
695            mcc = Integer.parseInt(operatorNumeric.substring(0, 3));
696        } catch (Exception e) {
697            if (DBG) {
698                log("shouldFixTimeZoneNow: no mcc, operatorNumeric=" + operatorNumeric +
699                        " retVal=false");
700            }
701            return false;
702        }
703
704        // If prevMcc is invalid will make it different from mcc
705        // so we'll return true if the card exists.
706        int prevMcc;
707        try {
708            prevMcc = Integer.parseInt(prevOperatorNumeric.substring(0, 3));
709        } catch (Exception e) {
710            prevMcc = mcc + 1;
711        }
712
713        // Determine if the Icc card exists
714        boolean iccCardExist = false;
715        if (mUiccApplcation != null) {
716            iccCardExist = mUiccApplcation.getState() != AppState.APPSTATE_UNKNOWN;
717        }
718
719        // Determine retVal
720        boolean retVal = ((iccCardExist && (mcc != prevMcc)) || needToFixTimeZone);
721        if (DBG) {
722            long ctm = System.currentTimeMillis();
723            log("shouldFixTimeZoneNow: retVal=" + retVal +
724                    " iccCardExist=" + iccCardExist +
725                    " operatorNumeric=" + operatorNumeric + " mcc=" + mcc +
726                    " prevOperatorNumeric=" + prevOperatorNumeric + " prevMcc=" + prevMcc +
727                    " needToFixTimeZone=" + needToFixTimeZone +
728                    " ltod=" + TimeUtils.logTimeOfDay(ctm));
729        }
730        return retVal;
731    }
732
733    public String getSystemProperty(String property, String defValue) {
734        return TelephonyManager.getTelephonyProperty(property, mPhoneBase.getSubId(), defValue);
735    }
736
737    /**
738     * @return all available cell information or null if none.
739     */
740    public List<CellInfo> getAllCellInfo() {
741        CellInfoResult result = new CellInfoResult();
742        if (VDBG) log("SST.getAllCellInfo(): E");
743        int ver = mCi.getRilVersion();
744        if (ver >= 8) {
745            if (isCallerOnDifferentThread()) {
746                if ((SystemClock.elapsedRealtime() - mLastCellInfoListTime)
747                        > LAST_CELL_INFO_LIST_MAX_AGE_MS) {
748                    Message msg = obtainMessage(EVENT_GET_CELL_INFO_LIST, result);
749                    synchronized(result.lockObj) {
750                        result.list = null;
751                        mCi.getCellInfoList(msg);
752                        try {
753                            result.lockObj.wait(5000);
754                        } catch (InterruptedException e) {
755                            e.printStackTrace();
756                        }
757                    }
758                } else {
759                    if (DBG) log("SST.getAllCellInfo(): return last, back to back calls");
760                    result.list = mLastCellInfoList;
761                }
762            } else {
763                if (DBG) log("SST.getAllCellInfo(): return last, same thread can't block");
764                result.list = mLastCellInfoList;
765            }
766        } else {
767            if (DBG) log("SST.getAllCellInfo(): not implemented");
768            result.list = null;
769        }
770        synchronized(result.lockObj) {
771            if (result.list != null) {
772                if (DBG) log("SST.getAllCellInfo(): X size=" + result.list.size()
773                        + " list=" + result.list);
774                return result.list;
775            } else {
776                if (DBG) log("SST.getAllCellInfo(): X size=0 list=null");
777                return null;
778            }
779        }
780    }
781
782    /**
783     * @return signal strength
784     */
785    public SignalStrength getSignalStrength() {
786        synchronized(mCellInfo) {
787            return mSignalStrength;
788        }
789    }
790
791    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
792        pw.println("ServiceStateTracker:");
793        pw.println(" mSS=" + mSS);
794        pw.println(" mNewSS=" + mNewSS);
795        pw.println(" mCellInfo=" + mCellInfo);
796        pw.println(" mRestrictedState=" + mRestrictedState);
797        pw.println(" mPollingContext=" + mPollingContext);
798        pw.println(" mDesiredPowerState=" + mDesiredPowerState);
799        pw.println(" mDontPollSignalStrength=" + mDontPollSignalStrength);
800        pw.println(" mPendingRadioPowerOffAfterDataOff=" + mPendingRadioPowerOffAfterDataOff);
801        pw.println(" mPendingRadioPowerOffAfterDataOffTag=" + mPendingRadioPowerOffAfterDataOffTag);
802    }
803
804    /**
805     * Verifies the current thread is the same as the thread originally
806     * used in the initialization of this instance. Throws RuntimeException
807     * if not.
808     *
809     * @exception RuntimeException if the current thread is not
810     * the thread that originally obtained this PhoneBase instance.
811     */
812    protected void checkCorrectThread() {
813        if (Thread.currentThread() != getLooper().getThread()) {
814            throw new RuntimeException(
815                    "ServiceStateTracker must be used from within one thread");
816        }
817    }
818
819    protected boolean isCallerOnDifferentThread() {
820        boolean value = Thread.currentThread() != getLooper().getThread();
821        if (VDBG) log("isCallerOnDifferentThread: " + value);
822        return value;
823    }
824
825    protected void updateCarrierMccMncConfiguration(String newOp, String oldOp, Context context) {
826        // if we have a change in operator, notify wifi (even to/from none)
827        if (((newOp == null) && (TextUtils.isEmpty(oldOp) == false)) ||
828                ((newOp != null) && (newOp.equals(oldOp) == false))) {
829            log("update mccmnc=" + newOp + " fromServiceState=true");
830            MccTable.updateMccMncConfiguration(context, newOp, true);
831        }
832    }
833}
834