ServiceStateTracker.java revision 03586878fb3d870373f2fdf65afb81cc5ae97067
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
295    /**
296     * Registration point for combined roaming on
297     * combined roaming is true when roaming is true and ONS differs SPN
298     *
299     * @param h handler to notify
300     * @param what what code of message when delivered
301     * @param obj placed in Message.obj
302     */
303    public  void registerForRoamingOn(Handler h, int what, Object obj) {
304        Registrant r = new Registrant(h, what, obj);
305        mRoamingOnRegistrants.add(r);
306
307        if (mSS.getRoaming()) {
308            r.notifyRegistrant();
309        }
310    }
311
312    public  void unregisterForRoamingOn(Handler h) {
313        mRoamingOnRegistrants.remove(h);
314    }
315
316    /**
317     * Registration point for combined roaming off
318     * combined roaming is true when roaming is true and ONS differs SPN
319     *
320     * @param h handler to notify
321     * @param what what code of message when delivered
322     * @param obj placed in Message.obj
323     */
324    public  void registerForRoamingOff(Handler h, int what, Object obj) {
325        Registrant r = new Registrant(h, what, obj);
326        mRoamingOffRegistrants.add(r);
327
328        if (!mSS.getRoaming()) {
329            r.notifyRegistrant();
330        }
331    }
332
333    public  void unregisterForRoamingOff(Handler h) {
334        mRoamingOffRegistrants.remove(h);
335    }
336
337    /**
338     * Re-register network by toggling preferred network type.
339     * This is a work-around to deregister and register network since there is
340     * no ril api to set COPS=2 (deregister) only.
341     *
342     * @param onComplete is dispatched when this is complete.  it will be
343     * an AsyncResult, and onComplete.obj.exception will be non-null
344     * on failure.
345     */
346    public void reRegisterNetwork(Message onComplete) {
347        mCi.getPreferredNetworkType(
348                obtainMessage(EVENT_GET_PREFERRED_NETWORK_TYPE, onComplete));
349    }
350
351    public void
352    setRadioPower(boolean power) {
353        mDesiredPowerState = power;
354
355        setPowerStateToDesired();
356    }
357
358    /**
359     * These two flags manage the behavior of the cell lock -- the
360     * lock should be held if either flag is true.  The intention is
361     * to allow temporary acquisition of the lock to get a single
362     * update.  Such a lock grab and release can thus be made to not
363     * interfere with more permanent lock holds -- in other words, the
364     * lock will only be released if both flags are false, and so
365     * releases by temporary users will only affect the lock state if
366     * there is no continuous user.
367     */
368    private boolean mWantContinuousLocationUpdates;
369    private boolean mWantSingleLocationUpdate;
370
371    public void enableSingleLocationUpdate() {
372        if (mWantSingleLocationUpdate || mWantContinuousLocationUpdates) return;
373        mWantSingleLocationUpdate = true;
374        mCi.setLocationUpdates(true, obtainMessage(EVENT_LOCATION_UPDATES_ENABLED));
375    }
376
377    public void enableLocationUpdates() {
378        if (mWantSingleLocationUpdate || mWantContinuousLocationUpdates) return;
379        mWantContinuousLocationUpdates = true;
380        mCi.setLocationUpdates(true, obtainMessage(EVENT_LOCATION_UPDATES_ENABLED));
381    }
382
383    protected void disableSingleLocationUpdate() {
384        mWantSingleLocationUpdate = false;
385        if (!mWantSingleLocationUpdate && !mWantContinuousLocationUpdates) {
386            mCi.setLocationUpdates(false, null);
387        }
388    }
389
390    public void disableLocationUpdates() {
391        mWantContinuousLocationUpdates = false;
392        if (!mWantSingleLocationUpdate && !mWantContinuousLocationUpdates) {
393            mCi.setLocationUpdates(false, null);
394        }
395    }
396
397    @Override
398    public void handleMessage(Message msg) {
399        switch (msg.what) {
400            case EVENT_SET_RADIO_POWER_OFF:
401                synchronized(this) {
402                    if (mPendingRadioPowerOffAfterDataOff &&
403                            (msg.arg1 == mPendingRadioPowerOffAfterDataOffTag)) {
404                        if (DBG) log("EVENT_SET_RADIO_OFF, turn radio off now.");
405                        hangupAndPowerOff();
406                        mPendingRadioPowerOffAfterDataOffTag += 1;
407                        mPendingRadioPowerOffAfterDataOff = false;
408                    } else {
409                        log("EVENT_SET_RADIO_OFF is stale arg1=" + msg.arg1 +
410                                "!= tag=" + mPendingRadioPowerOffAfterDataOffTag);
411                    }
412                }
413                break;
414
415            case EVENT_ICC_CHANGED:
416                onUpdateIccAvailability();
417                break;
418
419            case EVENT_GET_CELL_INFO_LIST: {
420                AsyncResult ar = (AsyncResult) msg.obj;
421                CellInfoResult result = (CellInfoResult) ar.userObj;
422                synchronized(result.lockObj) {
423                    if (ar.exception != null) {
424                        log("EVENT_GET_CELL_INFO_LIST: error ret null, e=" + ar.exception);
425                        result.list = null;
426                    } else {
427                        result.list = (List<CellInfo>) ar.result;
428
429                        if (VDBG) {
430                            log("EVENT_GET_CELL_INFO_LIST: size=" + result.list.size()
431                                    + " list=" + result.list);
432                        }
433                    }
434                    mLastCellInfoListTime = SystemClock.elapsedRealtime();
435                    mLastCellInfoList = result.list;
436                    result.lockObj.notify();
437                }
438                break;
439            }
440
441            case EVENT_UNSOL_CELL_INFO_LIST: {
442                AsyncResult ar = (AsyncResult) msg.obj;
443                if (ar.exception != null) {
444                    log("EVENT_UNSOL_CELL_INFO_LIST: error ignoring, e=" + ar.exception);
445                } else {
446                    List<CellInfo> list = (List<CellInfo>) ar.result;
447                    if (DBG) {
448                        log("EVENT_UNSOL_CELL_INFO_LIST: size=" + list.size()
449                                + " list=" + list);
450                    }
451                    mLastCellInfoListTime = SystemClock.elapsedRealtime();
452                    mLastCellInfoList = list;
453                    mPhoneBase.notifyCellInfo(list);
454                }
455                break;
456            }
457
458            default:
459                log("Unhandled message with number: " + msg.what);
460                break;
461        }
462    }
463
464    protected abstract Phone getPhone();
465    protected abstract void handlePollStateResult(int what, AsyncResult ar);
466    protected abstract void updateSpnDisplay();
467    protected abstract void setPowerStateToDesired();
468    protected abstract void onUpdateIccAvailability();
469    protected abstract void log(String s);
470    protected abstract void loge(String s);
471
472    public abstract int getCurrentDataConnectionState();
473    public abstract boolean isConcurrentVoiceAndDataAllowed();
474
475    public abstract void setImsRegistrationState(boolean registered);
476    public abstract void pollState();
477
478    /**
479     * Registration point for transition into DataConnection attached.
480     * @param h handler to notify
481     * @param what what code of message when delivered
482     * @param obj placed in Message.obj
483     */
484    public void registerForDataConnectionAttached(Handler h, int what, Object obj) {
485        Registrant r = new Registrant(h, what, obj);
486        mAttachedRegistrants.add(r);
487
488        if (getCurrentDataConnectionState() == ServiceState.STATE_IN_SERVICE) {
489            r.notifyRegistrant();
490        }
491    }
492    public void unregisterForDataConnectionAttached(Handler h) {
493        mAttachedRegistrants.remove(h);
494    }
495
496    /**
497     * Registration point for transition into DataConnection detached.
498     * @param h handler to notify
499     * @param what what code of message when delivered
500     * @param obj placed in Message.obj
501     */
502    public void registerForDataConnectionDetached(Handler h, int what, Object obj) {
503        Registrant r = new Registrant(h, what, obj);
504        mDetachedRegistrants.add(r);
505
506        if (getCurrentDataConnectionState() != ServiceState.STATE_IN_SERVICE) {
507            r.notifyRegistrant();
508        }
509    }
510    public void unregisterForDataConnectionDetached(Handler h) {
511        mDetachedRegistrants.remove(h);
512    }
513
514    /**
515     * Registration for DataConnection RIL Data Radio Technology changing. The
516     * new radio technology will be returned AsyncResult#result as an Integer Object.
517     * The AsyncResult will be in the notification Message#obj.
518     *
519     * @param h handler to notify
520     * @param what what code of message when delivered
521     * @param obj placed in Message.obj
522     */
523    public void registerForDataRegStateOrRatChanged(Handler h, int what, Object obj) {
524        Registrant r = new Registrant(h, what, obj);
525        mDataRegStateOrRatChangedRegistrants.add(r);
526        notifyDataRegStateRilRadioTechnologyChanged();
527    }
528    public void unregisterForDataRegStateOrRatChanged(Handler h) {
529        mDataRegStateOrRatChangedRegistrants.remove(h);
530    }
531
532    /**
533     * Registration point for transition into network attached.
534     * @param h handler to notify
535     * @param what what code of message when delivered
536     * @param obj in Message.obj
537     */
538    public void registerForNetworkAttached(Handler h, int what, Object obj) {
539        Registrant r = new Registrant(h, what, obj);
540
541        mNetworkAttachedRegistrants.add(r);
542        if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE) {
543            r.notifyRegistrant();
544        }
545    }
546    public void unregisterForNetworkAttached(Handler h) {
547        mNetworkAttachedRegistrants.remove(h);
548    }
549
550    /**
551     * Registration point for transition into packet service restricted zone.
552     * @param h handler to notify
553     * @param what what code of message when delivered
554     * @param obj placed in Message.obj
555     */
556    public void registerForPsRestrictedEnabled(Handler h, int what, Object obj) {
557        Registrant r = new Registrant(h, what, obj);
558        mPsRestrictEnabledRegistrants.add(r);
559
560        if (mRestrictedState.isPsRestricted()) {
561            r.notifyRegistrant();
562        }
563    }
564
565    public void unregisterForPsRestrictedEnabled(Handler h) {
566        mPsRestrictEnabledRegistrants.remove(h);
567    }
568
569    /**
570     * Registration point for transition out of packet service restricted zone.
571     * @param h handler to notify
572     * @param what what code of message when delivered
573     * @param obj placed in Message.obj
574     */
575    public void registerForPsRestrictedDisabled(Handler h, int what, Object obj) {
576        Registrant r = new Registrant(h, what, obj);
577        mPsRestrictDisabledRegistrants.add(r);
578
579        if (mRestrictedState.isPsRestricted()) {
580            r.notifyRegistrant();
581        }
582    }
583
584    public void unregisterForPsRestrictedDisabled(Handler h) {
585        mPsRestrictDisabledRegistrants.remove(h);
586    }
587
588    /**
589     * Clean up existing voice and data connection then turn off radio power.
590     *
591     * Hang up the existing voice calls to decrease call drop rate.
592     */
593    public void powerOffRadioSafely(DcTrackerBase dcTracker) {
594        synchronized (this) {
595            if (!mPendingRadioPowerOffAfterDataOff) {
596                // To minimize race conditions we call cleanUpAllConnections on
597                // both if else paths instead of before this isDisconnected test.
598                if (dcTracker.isDisconnected()) {
599                    // To minimize race conditions we do this after isDisconnected
600                    dcTracker.cleanUpAllConnections(Phone.REASON_RADIO_TURNED_OFF);
601                    if (DBG) log("Data disconnected, turn off radio right away.");
602                    hangupAndPowerOff();
603                } else {
604                    dcTracker.cleanUpAllConnections(Phone.REASON_RADIO_TURNED_OFF);
605                    Message msg = Message.obtain(this);
606                    msg.what = EVENT_SET_RADIO_POWER_OFF;
607                    msg.arg1 = ++mPendingRadioPowerOffAfterDataOffTag;
608                    if (sendMessageDelayed(msg, 30000)) {
609                        if (DBG) log("Wait upto 30s for data to disconnect, then turn off radio.");
610                        mPendingRadioPowerOffAfterDataOff = true;
611                    } else {
612                        log("Cannot send delayed Msg, turn off radio right away.");
613                        hangupAndPowerOff();
614                    }
615                }
616            }
617        }
618    }
619
620    /**
621     * process the pending request to turn radio off after data is disconnected
622     *
623     * return true if there is pending request to process; false otherwise.
624     */
625    public boolean processPendingRadioPowerOffAfterDataOff() {
626        synchronized(this) {
627            if (mPendingRadioPowerOffAfterDataOff) {
628                if (DBG) log("Process pending request to turn radio off.");
629                mPendingRadioPowerOffAfterDataOffTag += 1;
630                hangupAndPowerOff();
631                mPendingRadioPowerOffAfterDataOff = false;
632                return true;
633            }
634            return false;
635        }
636    }
637
638    /**
639     * send signal-strength-changed notification if changed Called both for
640     * solicited and unsolicited signal strength updates
641     *
642     * @return true if the signal strength changed and a notification was sent.
643     */
644    protected boolean onSignalStrengthResult(AsyncResult ar, boolean isGsm) {
645        SignalStrength oldSignalStrength = mSignalStrength;
646
647        // This signal is used for both voice and data radio signal so parse
648        // all fields
649
650        if ((ar.exception == null) && (ar.result != null)) {
651            mSignalStrength = (SignalStrength) ar.result;
652            mSignalStrength.validateInput();
653            mSignalStrength.setGsm(isGsm);
654        } else {
655            log("onSignalStrengthResult() Exception from RIL : " + ar.exception);
656            mSignalStrength = new SignalStrength(isGsm);
657        }
658
659        return notifySignalStrength();
660    }
661
662    /**
663     * Hang up all voice call and turn off radio. Implemented by derived class.
664     */
665    protected abstract void hangupAndPowerOff();
666
667    /** Cancel a pending (if any) pollState() operation */
668    protected void cancelPollState() {
669        // This will effectively cancel the rest of the poll requests.
670        mPollingContext = new int[1];
671    }
672
673    /**
674     * Return true if time zone needs fixing.
675     *
676     * @param phoneBase
677     * @param operatorNumeric
678     * @param prevOperatorNumeric
679     * @param needToFixTimeZone
680     * @return true if time zone needs to be fixed
681     */
682    protected boolean shouldFixTimeZoneNow(PhoneBase phoneBase, String operatorNumeric,
683            String prevOperatorNumeric, boolean needToFixTimeZone) {
684        // Return false if the mcc isn't valid as we don't know where we are.
685        // Return true if we have an IccCard and the mcc changed or we
686        // need to fix it because when the NITZ time came in we didn't
687        // know the country code.
688
689        // If mcc is invalid then we'll return false
690        int mcc;
691        try {
692            mcc = Integer.parseInt(operatorNumeric.substring(0, 3));
693        } catch (Exception e) {
694            if (DBG) {
695                log("shouldFixTimeZoneNow: no mcc, operatorNumeric=" + operatorNumeric +
696                        " retVal=false");
697            }
698            return false;
699        }
700
701        // If prevMcc is invalid will make it different from mcc
702        // so we'll return true if the card exists.
703        int prevMcc;
704        try {
705            prevMcc = Integer.parseInt(prevOperatorNumeric.substring(0, 3));
706        } catch (Exception e) {
707            prevMcc = mcc + 1;
708        }
709
710        // Determine if the Icc card exists
711        boolean iccCardExist = false;
712        if (mUiccApplcation != null) {
713            iccCardExist = mUiccApplcation.getState() != AppState.APPSTATE_UNKNOWN;
714        }
715
716        // Determine retVal
717        boolean retVal = ((iccCardExist && (mcc != prevMcc)) || needToFixTimeZone);
718        if (DBG) {
719            long ctm = System.currentTimeMillis();
720            log("shouldFixTimeZoneNow: retVal=" + retVal +
721                    " iccCardExist=" + iccCardExist +
722                    " operatorNumeric=" + operatorNumeric + " mcc=" + mcc +
723                    " prevOperatorNumeric=" + prevOperatorNumeric + " prevMcc=" + prevMcc +
724                    " needToFixTimeZone=" + needToFixTimeZone +
725                    " ltod=" + TimeUtils.logTimeOfDay(ctm));
726        }
727        return retVal;
728    }
729
730    public String getSystemProperty(String property, String defValue) {
731        return TelephonyManager.getTelephonyProperty(property, mPhoneBase.getSubId(), defValue);
732    }
733
734    /**
735     * @return all available cell information or null if none.
736     */
737    public List<CellInfo> getAllCellInfo() {
738        CellInfoResult result = new CellInfoResult();
739        if (VDBG) log("SST.getAllCellInfo(): E");
740        int ver = mCi.getRilVersion();
741        if (ver >= 8) {
742            if (isCallerOnDifferentThread()) {
743                if ((SystemClock.elapsedRealtime() - mLastCellInfoListTime)
744                        > LAST_CELL_INFO_LIST_MAX_AGE_MS) {
745                    Message msg = obtainMessage(EVENT_GET_CELL_INFO_LIST, result);
746                    synchronized(result.lockObj) {
747                        mCi.getCellInfoList(msg);
748                        try {
749                            result.lockObj.wait();
750                        } catch (InterruptedException e) {
751                            e.printStackTrace();
752                            result.list = null;
753                        }
754                    }
755                } else {
756                    if (DBG) log("SST.getAllCellInfo(): return last, back to back calls");
757                    result.list = mLastCellInfoList;
758                }
759            } else {
760                if (DBG) log("SST.getAllCellInfo(): return last, same thread can't block");
761                result.list = mLastCellInfoList;
762            }
763        } else {
764            if (DBG) log("SST.getAllCellInfo(): not implemented");
765            result.list = null;
766        }
767        if (DBG) {
768            if (result.list != null) {
769                log("SST.getAllCellInfo(): X size=" + result.list.size()
770                        + " list=" + result.list);
771            } else {
772                log("SST.getAllCellInfo(): X size=0 list=null");
773            }
774        }
775        return result.list;
776    }
777
778    /**
779     * @return signal strength
780     */
781    public SignalStrength getSignalStrength() {
782        synchronized(mCellInfo) {
783            return mSignalStrength;
784        }
785    }
786
787    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
788        pw.println("ServiceStateTracker:");
789        pw.println(" mSS=" + mSS);
790        pw.println(" mNewSS=" + mNewSS);
791        pw.println(" mCellInfo=" + mCellInfo);
792        pw.println(" mRestrictedState=" + mRestrictedState);
793        pw.println(" mPollingContext=" + mPollingContext);
794        pw.println(" mDesiredPowerState=" + mDesiredPowerState);
795        pw.println(" mDontPollSignalStrength=" + mDontPollSignalStrength);
796        pw.println(" mPendingRadioPowerOffAfterDataOff=" + mPendingRadioPowerOffAfterDataOff);
797        pw.println(" mPendingRadioPowerOffAfterDataOffTag=" + mPendingRadioPowerOffAfterDataOffTag);
798    }
799
800    /**
801     * Verifies the current thread is the same as the thread originally
802     * used in the initialization of this instance. Throws RuntimeException
803     * if not.
804     *
805     * @exception RuntimeException if the current thread is not
806     * the thread that originally obtained this PhoneBase instance.
807     */
808    protected void checkCorrectThread() {
809        if (Thread.currentThread() != getLooper().getThread()) {
810            throw new RuntimeException(
811                    "ServiceStateTracker must be used from within one thread");
812        }
813    }
814
815    protected boolean isCallerOnDifferentThread() {
816        boolean value = Thread.currentThread() != getLooper().getThread();
817        if (VDBG) log("isCallerOnDifferentThread: " + value);
818        return value;
819    }
820
821    protected void updateCarrierMccMncConfiguration(String newOp, String oldOp, Context context) {
822        // if we have a change in operator, notify wifi (even to/from none)
823        if (((newOp == null) && (TextUtils.isEmpty(oldOp) == false)) ||
824                ((newOp != null) && (newOp.equals(oldOp) == false))) {
825            log("update mccmnc=" + newOp + " fromServiceState=true");
826            MccTable.updateMccMncConfiguration(context, newOp, true);
827        }
828    }
829}
830