GsmServiceStateTracker.java revision 5b81adc82a53b3064f4baa3acfeabef31586588a
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.gsm;
18
19import com.android.internal.telephony.CommandException;
20import com.android.internal.telephony.CommandsInterface;
21import com.android.internal.telephony.DataConnectionTracker;
22import com.android.internal.telephony.EventLogTags;
23import com.android.internal.telephony.IccCard;
24import com.android.internal.telephony.IccCardConstants;
25import com.android.internal.telephony.IccCardStatus;
26import com.android.internal.telephony.MccTable;
27import com.android.internal.telephony.Phone;
28import com.android.internal.telephony.RestrictedState;
29import com.android.internal.telephony.RILConstants;
30import com.android.internal.telephony.ServiceStateTracker;
31import com.android.internal.telephony.TelephonyIntents;
32import com.android.internal.telephony.TelephonyProperties;
33
34import android.app.AlarmManager;
35import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
38import android.content.BroadcastReceiver;
39import android.content.ContentResolver;
40import android.content.Context;
41import android.content.Intent;
42import android.content.IntentFilter;
43import android.content.res.Resources;
44import android.database.ContentObserver;
45import android.os.AsyncResult;
46import android.os.Handler;
47import android.os.Message;
48import android.os.PowerManager;
49import android.os.Registrant;
50import android.os.RegistrantList;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.provider.Settings;
54import android.provider.Settings.SettingNotFoundException;
55import android.telephony.ServiceState;
56import android.telephony.SignalStrength;
57import android.telephony.gsm.GsmCellLocation;
58import android.text.TextUtils;
59import android.util.EventLog;
60import android.util.Log;
61import android.util.TimeUtils;
62
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65import java.util.ArrayList;
66import java.util.Arrays;
67import java.util.Calendar;
68import java.util.Collection;
69import java.util.Date;
70import java.util.HashSet;
71import java.util.TimeZone;
72
73/**
74 * {@hide}
75 */
76final class GsmServiceStateTracker extends ServiceStateTracker {
77    static final String LOG_TAG = "GSM";
78    static final boolean DBG = true;
79
80    GSMPhone phone;
81    GsmCellLocation cellLoc;
82    GsmCellLocation newCellLoc;
83    int mPreferredNetworkType;
84
85    private int gprsState = ServiceState.STATE_OUT_OF_SERVICE;
86    private int newGPRSState = ServiceState.STATE_OUT_OF_SERVICE;
87    private int mMaxDataCalls = 1;
88    private int mNewMaxDataCalls = 1;
89    private int mReasonDataDenied = -1;
90    private int mNewReasonDataDenied = -1;
91
92    /**
93     * GSM roaming status solely based on TS 27.007 7.2 CREG. Only used by
94     * handlePollStateResult to store CREG roaming result.
95     */
96    private boolean mGsmRoaming = false;
97
98    /**
99     * Data roaming status solely based on TS 27.007 10.1.19 CGREG. Only used by
100     * handlePollStateResult to store CGREG roaming result.
101     */
102    private boolean mDataRoaming = false;
103
104    /**
105     * Mark when service state is in emergency call only mode
106     */
107    private boolean mEmergencyOnly = false;
108
109    /**
110     * Sometimes we get the NITZ time before we know what country we
111     * are in. Keep the time zone information from the NITZ string so
112     * we can fix the time zone once know the country.
113     */
114    private boolean mNeedFixZoneAfterNitz = false;
115    private int mZoneOffset;
116    private boolean mZoneDst;
117    private long mZoneTime;
118    private boolean mGotCountryCode = false;
119    private ContentResolver cr;
120
121    /** Boolean is true is setTimeFromNITZString was called */
122    private boolean mNitzUpdatedTime = false;
123
124    String mSavedTimeZone;
125    long mSavedTime;
126    long mSavedAtTime;
127
128    /**
129     * We can't register for SIM_RECORDS_LOADED immediately because the
130     * SIMRecords object may not be instantiated yet.
131     */
132    private boolean mNeedToRegForSimLoaded;
133
134    /** Started the recheck process after finding gprs should registered but not. */
135    private boolean mStartedGprsRegCheck = false;
136
137    /** Already sent the event-log for no gprs register. */
138    private boolean mReportedGprsNoReg = false;
139
140    /**
141     * The Notification object given to the NotificationManager.
142     */
143    private Notification mNotification;
144
145    /** Wake lock used while setting time of day. */
146    private PowerManager.WakeLock mWakeLock;
147    private static final String WAKELOCK_TAG = "ServiceStateTracker";
148
149    /** Keep track of SPN display rules, so we only broadcast intent if something changes. */
150    private String curSpn = null;
151    private String curPlmn = null;
152    private int curSpnRule = 0;
153
154    /** waiting period before recheck gprs and voice registration. */
155    static final int DEFAULT_GPRS_CHECK_PERIOD_MILLIS = 60 * 1000;
156
157    /** Notification type. */
158    static final int PS_ENABLED = 1001;            // Access Control blocks data service
159    static final int PS_DISABLED = 1002;           // Access Control enables data service
160    static final int CS_ENABLED = 1003;            // Access Control blocks all voice/sms service
161    static final int CS_DISABLED = 1004;           // Access Control enables all voice/sms service
162    static final int CS_NORMAL_ENABLED = 1005;     // Access Control blocks normal voice/sms service
163    static final int CS_EMERGENCY_ENABLED = 1006;  // Access Control blocks emergency call service
164
165    /** Notification id. */
166    static final int PS_NOTIFICATION = 888;  // Id to update and cancel PS restricted
167    static final int CS_NOTIFICATION = 999;  // Id to update and cancel CS restricted
168
169    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
170        @Override
171        public void onReceive(Context context, Intent intent) {
172            if (intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED)) {
173                // update emergency string whenever locale changed
174                updateSpnDisplay();
175            }
176        }
177    };
178
179    private ContentObserver mAutoTimeObserver = new ContentObserver(new Handler()) {
180        @Override
181        public void onChange(boolean selfChange) {
182            Log.i("GsmServiceStateTracker", "Auto time state changed");
183            revertToNitzTime();
184        }
185    };
186
187    private ContentObserver mAutoTimeZoneObserver = new ContentObserver(new Handler()) {
188        @Override
189        public void onChange(boolean selfChange) {
190            Log.i("GsmServiceStateTracker", "Auto time zone state changed");
191            revertToNitzTimeZone();
192        }
193    };
194
195    public GsmServiceStateTracker(GSMPhone phone) {
196        super();
197
198        this.phone = phone;
199        cm = phone.mCM;
200        ss = new ServiceState();
201        newSS = new ServiceState();
202        cellLoc = new GsmCellLocation();
203        newCellLoc = new GsmCellLocation();
204        mSignalStrength = new SignalStrength();
205
206        PowerManager powerManager =
207                (PowerManager)phone.getContext().getSystemService(Context.POWER_SERVICE);
208        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
209
210        cm.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null);
211        cm.registerForRadioStateChanged(this, EVENT_RADIO_STATE_CHANGED, null);
212
213        cm.registerForVoiceNetworkStateChanged(this, EVENT_NETWORK_STATE_CHANGED, null);
214        cm.setOnNITZTime(this, EVENT_NITZ_TIME, null);
215        cm.setOnSignalStrengthUpdate(this, EVENT_SIGNAL_STRENGTH_UPDATE, null);
216        cm.setOnRestrictedStateChanged(this, EVENT_RESTRICTED_STATE_CHANGED, null);
217        phone.getIccCard().registerForReady(this, EVENT_SIM_READY, null);
218
219        // system setting property AIRPLANE_MODE_ON is set in Settings.
220        int airplaneMode = Settings.System.getInt(
221                phone.getContext().getContentResolver(),
222                Settings.System.AIRPLANE_MODE_ON, 0);
223        mDesiredPowerState = ! (airplaneMode > 0);
224
225        cr = phone.getContext().getContentResolver();
226        cr.registerContentObserver(
227                Settings.System.getUriFor(Settings.System.AUTO_TIME), true,
228                mAutoTimeObserver);
229        cr.registerContentObserver(
230                Settings.System.getUriFor(Settings.System.AUTO_TIME_ZONE), true,
231                mAutoTimeZoneObserver);
232
233        setSignalStrengthDefaultValues();
234        mNeedToRegForSimLoaded = true;
235
236        // Monitor locale change
237        IntentFilter filter = new IntentFilter();
238        filter.addAction(Intent.ACTION_LOCALE_CHANGED);
239        phone.getContext().registerReceiver(mIntentReceiver, filter);
240
241        // Gsm doesn't support OTASP so its not needed
242        phone.notifyOtaspChanged(OTASP_NOT_NEEDED);
243    }
244
245    public void dispose() {
246        // Unregister for all events.
247        cm.unregisterForAvailable(this);
248        cm.unregisterForRadioStateChanged(this);
249        cm.unregisterForVoiceNetworkStateChanged(this);
250        phone.getIccCard().unregisterForReady(this);
251        phone.mIccRecords.unregisterForRecordsLoaded(this);
252        cm.unSetOnSignalStrengthUpdate(this);
253        cm.unSetOnRestrictedStateChanged(this);
254        cm.unSetOnNITZTime(this);
255        cr.unregisterContentObserver(this.mAutoTimeObserver);
256        cr.unregisterContentObserver(this.mAutoTimeZoneObserver);
257    }
258
259    protected void finalize() {
260        if(DBG) log("finalize");
261    }
262
263    @Override
264    protected Phone getPhone() {
265        return phone;
266    }
267
268    public void handleMessage (Message msg) {
269        AsyncResult ar;
270        int[] ints;
271        String[] strings;
272        Message message;
273
274        if (!phone.mIsTheCurrentActivePhone) {
275            Log.e(LOG_TAG, "Received message " + msg +
276                    "[" + msg.what + "] while being destroyed. Ignoring.");
277            return;
278        }
279        switch (msg.what) {
280            case EVENT_RADIO_AVAILABLE:
281                //this is unnecessary
282                //setPowerStateToDesired();
283                break;
284
285            case EVENT_SIM_READY:
286                // Set the network type, in case the radio does not restore it.
287                cm.setCurrentPreferredNetworkType();
288
289                // The SIM is now ready i.e if it was locked
290                // it has been unlocked. At this stage, the radio is already
291                // powered on.
292                if (mNeedToRegForSimLoaded) {
293                    phone.mIccRecords.registerForRecordsLoaded(this,
294                            EVENT_SIM_RECORDS_LOADED, null);
295                    mNeedToRegForSimLoaded = false;
296                }
297
298                boolean skipRestoringSelection = phone.getContext().getResources().getBoolean(
299                        com.android.internal.R.bool.skip_restoring_network_selection);
300
301                if (!skipRestoringSelection) {
302                    // restore the previous network selection.
303                    phone.restoreSavedNetworkSelection(null);
304                }
305                pollState();
306                // Signal strength polling stops when radio is off
307                queueNextSignalStrengthPoll();
308                break;
309
310            case EVENT_RADIO_STATE_CHANGED:
311                // This will do nothing in the radio not
312                // available case
313                setPowerStateToDesired();
314                pollState();
315                break;
316
317            case EVENT_NETWORK_STATE_CHANGED:
318                pollState();
319                break;
320
321            case EVENT_GET_SIGNAL_STRENGTH:
322                // This callback is called when signal strength is polled
323                // all by itself
324
325                if (!(cm.getRadioState().isOn())) {
326                    // Polling will continue when radio turns back on
327                    return;
328                }
329                ar = (AsyncResult) msg.obj;
330                onSignalStrengthResult(ar, phone, true);
331                queueNextSignalStrengthPoll();
332
333                break;
334
335            case EVENT_GET_LOC_DONE:
336                ar = (AsyncResult) msg.obj;
337
338                if (ar.exception == null) {
339                    String states[] = (String[])ar.result;
340                    int lac = -1;
341                    int cid = -1;
342                    if (states.length >= 3) {
343                        try {
344                            if (states[1] != null && states[1].length() > 0) {
345                                lac = Integer.parseInt(states[1], 16);
346                            }
347                            if (states[2] != null && states[2].length() > 0) {
348                                cid = Integer.parseInt(states[2], 16);
349                            }
350                        } catch (NumberFormatException ex) {
351                            Log.w(LOG_TAG, "error parsing location: " + ex);
352                        }
353                    }
354                    cellLoc.setLacAndCid(lac, cid);
355                    phone.notifyLocationChanged();
356                }
357
358                // Release any temporary cell lock, which could have been
359                // acquired to allow a single-shot location update.
360                disableSingleLocationUpdate();
361                break;
362
363            case EVENT_POLL_STATE_REGISTRATION:
364            case EVENT_POLL_STATE_GPRS:
365            case EVENT_POLL_STATE_OPERATOR:
366            case EVENT_POLL_STATE_NETWORK_SELECTION_MODE:
367                ar = (AsyncResult) msg.obj;
368
369                handlePollStateResult(msg.what, ar);
370                break;
371
372            case EVENT_POLL_SIGNAL_STRENGTH:
373                // Just poll signal strength...not part of pollState()
374
375                cm.getSignalStrength(obtainMessage(EVENT_GET_SIGNAL_STRENGTH));
376                break;
377
378            case EVENT_NITZ_TIME:
379                ar = (AsyncResult) msg.obj;
380
381                String nitzString = (String)((Object[])ar.result)[0];
382                long nitzReceiveTime = ((Long)((Object[])ar.result)[1]).longValue();
383
384                setTimeFromNITZString(nitzString, nitzReceiveTime);
385                break;
386
387            case EVENT_SIGNAL_STRENGTH_UPDATE:
388                // This is a notification from
389                // CommandsInterface.setOnSignalStrengthUpdate
390
391                ar = (AsyncResult) msg.obj;
392
393                // The radio is telling us about signal strength changes
394                // we don't have to ask it
395                dontPollSignalStrength = true;
396
397                onSignalStrengthResult(ar, phone, true);
398                break;
399
400            case EVENT_SIM_RECORDS_LOADED:
401                updateSpnDisplay();
402                break;
403
404            case EVENT_LOCATION_UPDATES_ENABLED:
405                ar = (AsyncResult) msg.obj;
406
407                if (ar.exception == null) {
408                    cm.getVoiceRegistrationState(obtainMessage(EVENT_GET_LOC_DONE, null));
409                }
410                break;
411
412            case EVENT_SET_PREFERRED_NETWORK_TYPE:
413                ar = (AsyncResult) msg.obj;
414                // Don't care the result, only use for dereg network (COPS=2)
415                message = obtainMessage(EVENT_RESET_PREFERRED_NETWORK_TYPE, ar.userObj);
416                cm.setPreferredNetworkType(mPreferredNetworkType, message);
417                break;
418
419            case EVENT_RESET_PREFERRED_NETWORK_TYPE:
420                ar = (AsyncResult) msg.obj;
421                if (ar.userObj != null) {
422                    AsyncResult.forMessage(((Message) ar.userObj)).exception
423                            = ar.exception;
424                    ((Message) ar.userObj).sendToTarget();
425                }
426                break;
427
428            case EVENT_GET_PREFERRED_NETWORK_TYPE:
429                ar = (AsyncResult) msg.obj;
430
431                if (ar.exception == null) {
432                    mPreferredNetworkType = ((int[])ar.result)[0];
433                } else {
434                    mPreferredNetworkType = RILConstants.NETWORK_MODE_GLOBAL;
435                }
436
437                message = obtainMessage(EVENT_SET_PREFERRED_NETWORK_TYPE, ar.userObj);
438                int toggledNetworkType = RILConstants.NETWORK_MODE_GLOBAL;
439
440                cm.setPreferredNetworkType(toggledNetworkType, message);
441                break;
442
443            case EVENT_CHECK_REPORT_GPRS:
444                if (ss != null && !isGprsConsistent(gprsState, ss.getState())) {
445
446                    // Can't register data service while voice service is ok
447                    // i.e. CREG is ok while CGREG is not
448                    // possible a network or baseband side error
449                    GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
450                    EventLog.writeEvent(EventLogTags.DATA_NETWORK_REGISTRATION_FAIL,
451                            ss.getOperatorNumeric(), loc != null ? loc.getCid() : -1);
452                    mReportedGprsNoReg = true;
453                }
454                mStartedGprsRegCheck = false;
455                break;
456
457            case EVENT_RESTRICTED_STATE_CHANGED:
458                // This is a notification from
459                // CommandsInterface.setOnRestrictedStateChanged
460
461                if (DBG) log("EVENT_RESTRICTED_STATE_CHANGED");
462
463                ar = (AsyncResult) msg.obj;
464
465                onRestrictedStateChanged(ar);
466                break;
467
468            default:
469                super.handleMessage(msg);
470            break;
471        }
472    }
473
474    protected void setPowerStateToDesired() {
475        // If we want it on and it's off, turn it on
476        if (mDesiredPowerState
477            && cm.getRadioState() == CommandsInterface.RadioState.RADIO_OFF) {
478            cm.setRadioPower(true, null);
479        } else if (!mDesiredPowerState && cm.getRadioState().isOn()) {
480            // If it's on and available and we want it off gracefully
481            DataConnectionTracker dcTracker = phone.mDataConnectionTracker;
482            powerOffRadioSafely(dcTracker);
483        } // Otherwise, we're in the desired state
484    }
485
486    @Override
487    protected void hangupAndPowerOff() {
488        // hang up all active voice calls
489        if (phone.isInCall()) {
490            phone.mCT.ringingCall.hangupIfAlive();
491            phone.mCT.backgroundCall.hangupIfAlive();
492            phone.mCT.foregroundCall.hangupIfAlive();
493        }
494
495        cm.setRadioPower(false, null);
496    }
497
498    protected void updateSpnDisplay() {
499        int rule = phone.mIccRecords.getDisplayRule(ss.getOperatorNumeric());
500        String spn = phone.mIccRecords.getServiceProviderName();
501        String plmn = ss.getOperatorAlphaLong();
502
503        // For emergency calls only, pass the EmergencyCallsOnly string via EXTRA_PLMN
504        if (mEmergencyOnly && cm.getRadioState().isOn()) {
505            plmn = Resources.getSystem().
506                getText(com.android.internal.R.string.emergency_calls_only).toString();
507            if (DBG) log("updateSpnDisplay: emergency only and radio is on plmn='" + plmn + "'");
508        }
509
510        if (rule != curSpnRule
511                || !TextUtils.equals(spn, curSpn)
512                || !TextUtils.equals(plmn, curPlmn)) {
513            boolean showSpn = !mEmergencyOnly && !TextUtils.isEmpty(spn)
514                && (rule & SIMRecords.SPN_RULE_SHOW_SPN) == SIMRecords.SPN_RULE_SHOW_SPN;
515            boolean showPlmn = !TextUtils.isEmpty(plmn) &&
516                (rule & SIMRecords.SPN_RULE_SHOW_PLMN) == SIMRecords.SPN_RULE_SHOW_PLMN;
517
518            if (DBG) {
519                log(String.format("updateSpnDisplay: changed sending intent" + " rule=" + rule +
520                            " showPlmn='%b' plmn='%s' showSpn='%b' spn='%s'",
521                            showPlmn, plmn, showSpn, spn));
522            }
523            Intent intent = new Intent(TelephonyIntents.SPN_STRINGS_UPDATED_ACTION);
524            intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
525            intent.putExtra(TelephonyIntents.EXTRA_SHOW_SPN, showSpn);
526            intent.putExtra(TelephonyIntents.EXTRA_SPN, spn);
527            intent.putExtra(TelephonyIntents.EXTRA_SHOW_PLMN, showPlmn);
528            intent.putExtra(TelephonyIntents.EXTRA_PLMN, plmn);
529            phone.getContext().sendStickyBroadcast(intent);
530        }
531
532        curSpnRule = rule;
533        curSpn = spn;
534        curPlmn = plmn;
535    }
536
537    /**
538     * Handle the result of one of the pollState()-related requests
539     */
540    protected void handlePollStateResult (int what, AsyncResult ar) {
541        int ints[];
542        String states[];
543
544        // Ignore stale requests from last poll
545        if (ar.userObj != pollingContext) return;
546
547        if (ar.exception != null) {
548            CommandException.Error err=null;
549
550            if (ar.exception instanceof CommandException) {
551                err = ((CommandException)(ar.exception)).getCommandError();
552            }
553
554            if (err == CommandException.Error.RADIO_NOT_AVAILABLE) {
555                // Radio has crashed or turned off
556                cancelPollState();
557                return;
558            }
559
560            if (!cm.getRadioState().isOn()) {
561                // Radio has crashed or turned off
562                cancelPollState();
563                return;
564            }
565
566            if (err != CommandException.Error.OP_NOT_ALLOWED_BEFORE_REG_NW) {
567                loge("RIL implementation has returned an error where it must succeed" +
568                        ar.exception);
569            }
570        } else try {
571            switch (what) {
572                case EVENT_POLL_STATE_REGISTRATION:
573                    states = (String[])ar.result;
574                    int lac = -1;
575                    int cid = -1;
576                    int regState = -1;
577                    int reasonRegStateDenied = -1;
578                    int psc = -1;
579                    if (states.length > 0) {
580                        try {
581                            regState = Integer.parseInt(states[0]);
582                            if (states.length >= 3) {
583                                if (states[1] != null && states[1].length() > 0) {
584                                    lac = Integer.parseInt(states[1], 16);
585                                }
586                                if (states[2] != null && states[2].length() > 0) {
587                                    cid = Integer.parseInt(states[2], 16);
588                                }
589                            }
590                            if (states.length > 14) {
591                                if (states[14] != null && states[14].length() > 0) {
592                                    psc = Integer.parseInt(states[14], 16);
593                                }
594                            }
595                        } catch (NumberFormatException ex) {
596                            loge("error parsing RegistrationState: " + ex);
597                        }
598                    }
599
600                    mGsmRoaming = regCodeIsRoaming(regState);
601                    newSS.setState (regCodeToServiceState(regState));
602
603                    if (regState == 10 || regState == 12 || regState == 13 || regState == 14) {
604                        mEmergencyOnly = true;
605                    } else {
606                        mEmergencyOnly = false;
607                    }
608
609                    // LAC and CID are -1 if not avail
610                    newCellLoc.setLacAndCid(lac, cid);
611                    newCellLoc.setPsc(psc);
612                break;
613
614                case EVENT_POLL_STATE_GPRS:
615                    states = (String[])ar.result;
616
617                    int type = 0;
618                    regState = -1;
619                    mNewReasonDataDenied = -1;
620                    mNewMaxDataCalls = 1;
621                    if (states.length > 0) {
622                        try {
623                            regState = Integer.parseInt(states[0]);
624
625                            // states[3] (if present) is the current radio technology
626                            if (states.length >= 4 && states[3] != null) {
627                                type = Integer.parseInt(states[3]);
628                            }
629                            if ((states.length >= 5 ) && (regState == 3)) {
630                                mNewReasonDataDenied = Integer.parseInt(states[4]);
631                            }
632                            if (states.length >= 6) {
633                                mNewMaxDataCalls = Integer.parseInt(states[5]);
634                            }
635                        } catch (NumberFormatException ex) {
636                            loge("error parsing GprsRegistrationState: " + ex);
637                        }
638                    }
639                    newGPRSState = regCodeToServiceState(regState);
640                    mDataRoaming = regCodeIsRoaming(regState);
641                    mNewRilRadioTechnology = type;
642                    newSS.setRadioTechnology(type);
643                break;
644
645                case EVENT_POLL_STATE_OPERATOR:
646                    String opNames[] = (String[])ar.result;
647
648                    if (opNames != null && opNames.length >= 3) {
649                         newSS.setOperatorName (opNames[0], opNames[1], opNames[2]);
650                    }
651                break;
652
653                case EVENT_POLL_STATE_NETWORK_SELECTION_MODE:
654                    ints = (int[])ar.result;
655                    newSS.setIsManualSelection(ints[0] == 1);
656                break;
657            }
658
659        } catch (RuntimeException ex) {
660            loge("Exception while polling service state. Probably malformed RIL response." + ex);
661        }
662
663        pollingContext[0]--;
664
665        if (pollingContext[0] == 0) {
666            /**
667             *  Since the roaming states of gsm service (from +CREG) and
668             *  data service (from +CGREG) could be different, the new SS
669             *  is set roaming while either one is roaming.
670             *
671             *  There is an exception for the above rule. The new SS is not set
672             *  as roaming while gsm service reports roaming but indeed it is
673             *  not roaming between operators.
674             */
675            boolean roaming = (mGsmRoaming || mDataRoaming);
676            if (mGsmRoaming && !isRoamingBetweenOperators(mGsmRoaming, newSS)) {
677                roaming = false;
678            }
679            newSS.setRoaming(roaming);
680            newSS.setEmergencyOnly(mEmergencyOnly);
681            pollStateDone();
682        }
683    }
684
685    private void setSignalStrengthDefaultValues() {
686        mSignalStrength = new SignalStrength(true);
687    }
688
689    /**
690     * A complete "service state" from our perspective is
691     * composed of a handful of separate requests to the radio.
692     *
693     * We make all of these requests at once, but then abandon them
694     * and start over again if the radio notifies us that some
695     * event has changed
696     */
697    private void pollState() {
698        pollingContext = new int[1];
699        pollingContext[0] = 0;
700
701        switch (cm.getRadioState()) {
702            case RADIO_UNAVAILABLE:
703                newSS.setStateOutOfService();
704                newCellLoc.setStateInvalid();
705                setSignalStrengthDefaultValues();
706                mGotCountryCode = false;
707                mNitzUpdatedTime = false;
708                pollStateDone();
709            break;
710
711            case RADIO_OFF:
712                newSS.setStateOff();
713                newCellLoc.setStateInvalid();
714                setSignalStrengthDefaultValues();
715                mGotCountryCode = false;
716                mNitzUpdatedTime = false;
717                pollStateDone();
718            break;
719
720            default:
721                // Issue all poll-related commands at once
722                // then count down the responses, which
723                // are allowed to arrive out-of-order
724
725                pollingContext[0]++;
726                cm.getOperator(
727                    obtainMessage(
728                        EVENT_POLL_STATE_OPERATOR, pollingContext));
729
730                pollingContext[0]++;
731                cm.getDataRegistrationState(
732                    obtainMessage(
733                        EVENT_POLL_STATE_GPRS, pollingContext));
734
735                pollingContext[0]++;
736                cm.getVoiceRegistrationState(
737                    obtainMessage(
738                        EVENT_POLL_STATE_REGISTRATION, pollingContext));
739
740                pollingContext[0]++;
741                cm.getNetworkSelectionMode(
742                    obtainMessage(
743                        EVENT_POLL_STATE_NETWORK_SELECTION_MODE, pollingContext));
744            break;
745        }
746    }
747
748    private void pollStateDone() {
749        if (DBG) {
750            log("Poll ServiceState done: " +
751                " oldSS=[" + ss + "] newSS=[" + newSS +
752                "] oldGprs=" + gprsState + " newData=" + newGPRSState +
753                " oldMaxDataCalls=" + mMaxDataCalls +
754                " mNewMaxDataCalls=" + mNewMaxDataCalls +
755                " oldReasonDataDenied=" + mReasonDataDenied +
756                " mNewReasonDataDenied=" + mNewReasonDataDenied +
757                " oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
758                " newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
759        }
760
761        boolean hasRegistered =
762            ss.getState() != ServiceState.STATE_IN_SERVICE
763            && newSS.getState() == ServiceState.STATE_IN_SERVICE;
764
765        boolean hasDeregistered =
766            ss.getState() == ServiceState.STATE_IN_SERVICE
767            && newSS.getState() != ServiceState.STATE_IN_SERVICE;
768
769        boolean hasGprsAttached =
770                gprsState != ServiceState.STATE_IN_SERVICE
771                && newGPRSState == ServiceState.STATE_IN_SERVICE;
772
773        boolean hasGprsDetached =
774                gprsState == ServiceState.STATE_IN_SERVICE
775                && newGPRSState != ServiceState.STATE_IN_SERVICE;
776
777        boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
778
779        boolean hasChanged = !newSS.equals(ss);
780
781        boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
782
783        boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
784
785        boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
786
787        // Add an event log when connection state changes
788        if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
789            EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
790                ss.getState(), gprsState, newSS.getState(), newGPRSState);
791        }
792
793        ServiceState tss;
794        tss = ss;
795        ss = newSS;
796        newSS = tss;
797        // clean slate for next time
798        newSS.setStateOutOfService();
799
800        GsmCellLocation tcl = cellLoc;
801        cellLoc = newCellLoc;
802        newCellLoc = tcl;
803
804        // Add an event log when network type switched
805        // TODO: we may add filtering to reduce the event logged,
806        // i.e. check preferred network setting, only switch to 2G, etc
807        if (hasRadioTechnologyChanged) {
808            int cid = -1;
809            GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
810            if (loc != null) cid = loc.getCid();
811            EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
812                    mNewRilRadioTechnology);
813            if (DBG) {
814                log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
815                        " -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
816                        " at cell " + cid);
817            }
818        }
819
820        gprsState = newGPRSState;
821        mReasonDataDenied = mNewReasonDataDenied;
822        mMaxDataCalls = mNewMaxDataCalls;
823        mRilRadioTechnology = mNewRilRadioTechnology;
824        // this new state has been applied - forget it until we get a new new state
825        mNewRilRadioTechnology = 0;
826
827
828        newSS.setStateOutOfService(); // clean slate for next time
829
830        if (hasRadioTechnologyChanged) {
831            phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
832                    ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
833        }
834
835        if (hasRegistered) {
836            mNetworkAttachedRegistrants.notifyRegistrants();
837
838            if (DBG) {
839                log("pollStateDone: registering current mNitzUpdatedTime=" +
840                        mNitzUpdatedTime + " changing to false");
841            }
842            mNitzUpdatedTime = false;
843        }
844
845        if (hasChanged) {
846            String operatorNumeric;
847
848            updateSpnDisplay();
849
850            phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
851                ss.getOperatorAlphaLong());
852
853            String prevOperatorNumeric =
854                    SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
855            operatorNumeric = ss.getOperatorNumeric();
856            phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
857
858            if (operatorNumeric == null) {
859                if (DBG) log("operatorNumeric is null");
860                phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
861                mGotCountryCode = false;
862                mNitzUpdatedTime = false;
863            } else {
864                String iso = "";
865                String mcc = "";
866                try{
867                    mcc = operatorNumeric.substring(0, 3);
868                    iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
869                } catch ( NumberFormatException ex){
870                    loge("pollStateDone: countryCodeForMcc error" + ex);
871                } catch ( StringIndexOutOfBoundsException ex) {
872                    loge("pollStateDone: countryCodeForMcc error" + ex);
873                }
874
875                phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
876                mGotCountryCode = true;
877
878                TimeZone zone = null;
879
880                if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
881                        getAutoTimeZone()) {
882
883                    // Test both paths if ignore nitz is true
884                    boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
885                                TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
886                                    ((SystemClock.uptimeMillis() & 1) == 0);
887
888                    ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
889                    if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
890                        zone = uniqueZones.get(0);
891                        if (DBG) {
892                           log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
893                                   " with zone.getID=" + zone.getID() +
894                                   " testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
895                        }
896                        setAndBroadcastNetworkSetTimeZone(zone.getID());
897                    } else {
898                        if (DBG) {
899                            log("pollStateDone: there are " + uniqueZones.size() +
900                                " unique offsets for iso-cc='" + iso +
901                                " testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
902                                "', do nothing");
903                        }
904                    }
905                }
906
907                if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
908                        mNeedFixZoneAfterNitz)) {
909                    // If the offset is (0, false) and the timezone property
910                    // is set, use the timezone property rather than
911                    // GMT.
912                    String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
913                    if (DBG) {
914                        log("pollStateDone: fix time zone zoneName='" + zoneName +
915                            "' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
916                            " iso-cc='" + iso +
917                            "' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
918                    }
919
920                    // "(mZoneOffset == 0) && (mZoneDst == false) &&
921                    //  (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
922                    // means that we received a NITZ string telling
923                    // it is in GMT+0 w/ DST time zone
924                    // BUT iso tells is NOT, e.g, a wrong NITZ reporting
925                    // local time w/ 0 offset.
926                    if ((mZoneOffset == 0) && (mZoneDst == false) &&
927                        (zoneName != null) && (zoneName.length() > 0) &&
928                        (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
929                        zone = TimeZone.getDefault();
930                        if (mNeedFixZoneAfterNitz) {
931                            // For wrong NITZ reporting local time w/ 0 offset,
932                            // need adjust time to reflect default timezone setting
933                            long ctm = System.currentTimeMillis();
934                            long tzOffset = zone.getOffset(ctm);
935                            if (DBG) {
936                                log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
937                                        TimeUtils.logTimeOfDay(ctm));
938                            }
939                            if (getAutoTime()) {
940                                long adj = ctm - tzOffset;
941                                if (DBG) log("pollStateDone: adj ltod=" +
942                                        TimeUtils.logTimeOfDay(adj));
943                                setAndBroadcastNetworkSetTime(adj);
944                            } else {
945                                // Adjust the saved NITZ time to account for tzOffset.
946                                mSavedTime = mSavedTime - tzOffset;
947                            }
948                        }
949                        if (DBG) log("pollStateDone: using default TimeZone");
950                    } else if (iso.equals("")){
951                        // Country code not found.  This is likely a test network.
952                        // Get a TimeZone based only on the NITZ parameters (best guess).
953                        zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
954                        if (DBG) log("pollStateDone: using NITZ TimeZone");
955                    } else {
956                        zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
957                        if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
958                    }
959
960                    mNeedFixZoneAfterNitz = false;
961
962                    if (zone != null) {
963                        log("pollStateDone: zone != null zone.getID=" + zone.getID());
964                        if (getAutoTimeZone()) {
965                            setAndBroadcastNetworkSetTimeZone(zone.getID());
966                        }
967                        saveNitzTimeZone(zone.getID());
968                    } else {
969                        log("pollStateDone: zone == null");
970                    }
971                }
972            }
973
974            phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
975                ss.getRoaming() ? "true" : "false");
976
977            phone.notifyServiceStateChanged(ss);
978        }
979
980        if (hasGprsAttached) {
981            mAttachedRegistrants.notifyRegistrants();
982        }
983
984        if (hasGprsDetached) {
985            mDetachedRegistrants.notifyRegistrants();
986        }
987
988        if (hasRadioTechnologyChanged) {
989            phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
990        }
991
992        if (hasRoamingOn) {
993            mRoamingOnRegistrants.notifyRegistrants();
994        }
995
996        if (hasRoamingOff) {
997            mRoamingOffRegistrants.notifyRegistrants();
998        }
999
1000        if (hasLocationChanged) {
1001            phone.notifyLocationChanged();
1002        }
1003
1004        if (! isGprsConsistent(gprsState, ss.getState())) {
1005            if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
1006                mStartedGprsRegCheck = true;
1007
1008                int check_period = Settings.Secure.getInt(
1009                        phone.getContext().getContentResolver(),
1010                        Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
1011                        DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
1012                sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
1013                        check_period);
1014            }
1015        } else {
1016            mReportedGprsNoReg = false;
1017        }
1018    }
1019
1020    /**
1021     * Check if GPRS got registered while voice is registered.
1022     *
1023     * @param gprsState for GPRS registration state, i.e. CGREG in GSM
1024     * @param serviceState for voice registration state, i.e. CREG in GSM
1025     * @return false if device only register to voice but not gprs
1026     */
1027    private boolean isGprsConsistent(int gprsState, int serviceState) {
1028        return !((serviceState == ServiceState.STATE_IN_SERVICE) &&
1029                (gprsState != ServiceState.STATE_IN_SERVICE));
1030    }
1031
1032    /**
1033     * Returns a TimeZone object based only on parameters from the NITZ string.
1034     */
1035    private TimeZone getNitzTimeZone(int offset, boolean dst, long when) {
1036        TimeZone guess = findTimeZone(offset, dst, when);
1037        if (guess == null) {
1038            // Couldn't find a proper timezone.  Perhaps the DST data is wrong.
1039            guess = findTimeZone(offset, !dst, when);
1040        }
1041        if (DBG) log("getNitzTimeZone returning " + (guess == null ? guess : guess.getID()));
1042        return guess;
1043    }
1044
1045    private TimeZone findTimeZone(int offset, boolean dst, long when) {
1046        int rawOffset = offset;
1047        if (dst) {
1048            rawOffset -= 3600000;
1049        }
1050        String[] zones = TimeZone.getAvailableIDs(rawOffset);
1051        TimeZone guess = null;
1052        Date d = new Date(when);
1053        for (String zone : zones) {
1054            TimeZone tz = TimeZone.getTimeZone(zone);
1055            if (tz.getOffset(when) == offset &&
1056                tz.inDaylightTime(d) == dst) {
1057                guess = tz;
1058                break;
1059            }
1060        }
1061
1062        return guess;
1063    }
1064
1065    private void queueNextSignalStrengthPoll() {
1066        if (dontPollSignalStrength) {
1067            // The radio is telling us about signal strength changes
1068            // we don't have to ask it
1069            return;
1070        }
1071
1072        Message msg;
1073
1074        msg = obtainMessage();
1075        msg.what = EVENT_POLL_SIGNAL_STRENGTH;
1076
1077        long nextTime;
1078
1079        // TODO Don't poll signal strength if screen is off
1080        sendMessageDelayed(msg, POLL_PERIOD_MILLIS);
1081    }
1082
1083    /**
1084     * Set restricted state based on the OnRestrictedStateChanged notification
1085     * If any voice or packet restricted state changes, trigger a UI
1086     * notification and notify registrants when sim is ready.
1087     *
1088     * @param ar an int value of RIL_RESTRICTED_STATE_*
1089     */
1090    private void onRestrictedStateChanged(AsyncResult ar) {
1091        RestrictedState newRs = new RestrictedState();
1092
1093        if (DBG) log("onRestrictedStateChanged: E rs "+ mRestrictedState);
1094
1095        if (ar.exception == null) {
1096            int[] ints = (int[])ar.result;
1097            int state = ints[0];
1098
1099            newRs.setCsEmergencyRestricted(
1100                    ((state & RILConstants.RIL_RESTRICTED_STATE_CS_EMERGENCY) != 0) ||
1101                    ((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) );
1102            //ignore the normal call and data restricted state before SIM READY
1103            if (phone.getIccCard().getState() == IccCardConstants.State.READY) {
1104                newRs.setCsNormalRestricted(
1105                        ((state & RILConstants.RIL_RESTRICTED_STATE_CS_NORMAL) != 0) ||
1106                        ((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) );
1107                newRs.setPsRestricted(
1108                        (state & RILConstants.RIL_RESTRICTED_STATE_PS_ALL)!= 0);
1109            }
1110
1111            if (DBG) log("onRestrictedStateChanged: new rs "+ newRs);
1112
1113            if (!mRestrictedState.isPsRestricted() && newRs.isPsRestricted()) {
1114                mPsRestrictEnabledRegistrants.notifyRegistrants();
1115                setNotification(PS_ENABLED);
1116            } else if (mRestrictedState.isPsRestricted() && !newRs.isPsRestricted()) {
1117                mPsRestrictDisabledRegistrants.notifyRegistrants();
1118                setNotification(PS_DISABLED);
1119            }
1120
1121            /**
1122             * There are two kind of cs restriction, normal and emergency. So
1123             * there are 4 x 4 combinations in current and new restricted states
1124             * and we only need to notify when state is changed.
1125             */
1126            if (mRestrictedState.isCsRestricted()) {
1127                if (!newRs.isCsRestricted()) {
1128                    // remove all restriction
1129                    setNotification(CS_DISABLED);
1130                } else if (!newRs.isCsNormalRestricted()) {
1131                    // remove normal restriction
1132                    setNotification(CS_EMERGENCY_ENABLED);
1133                } else if (!newRs.isCsEmergencyRestricted()) {
1134                    // remove emergency restriction
1135                    setNotification(CS_NORMAL_ENABLED);
1136                }
1137            } else if (mRestrictedState.isCsEmergencyRestricted() &&
1138                    !mRestrictedState.isCsNormalRestricted()) {
1139                if (!newRs.isCsRestricted()) {
1140                    // remove all restriction
1141                    setNotification(CS_DISABLED);
1142                } else if (newRs.isCsRestricted()) {
1143                    // enable all restriction
1144                    setNotification(CS_ENABLED);
1145                } else if (newRs.isCsNormalRestricted()) {
1146                    // remove emergency restriction and enable normal restriction
1147                    setNotification(CS_NORMAL_ENABLED);
1148                }
1149            } else if (!mRestrictedState.isCsEmergencyRestricted() &&
1150                    mRestrictedState.isCsNormalRestricted()) {
1151                if (!newRs.isCsRestricted()) {
1152                    // remove all restriction
1153                    setNotification(CS_DISABLED);
1154                } else if (newRs.isCsRestricted()) {
1155                    // enable all restriction
1156                    setNotification(CS_ENABLED);
1157                } else if (newRs.isCsEmergencyRestricted()) {
1158                    // remove normal restriction and enable emergency restriction
1159                    setNotification(CS_EMERGENCY_ENABLED);
1160                }
1161            } else {
1162                if (newRs.isCsRestricted()) {
1163                    // enable all restriction
1164                    setNotification(CS_ENABLED);
1165                } else if (newRs.isCsEmergencyRestricted()) {
1166                    // enable emergency restriction
1167                    setNotification(CS_EMERGENCY_ENABLED);
1168                } else if (newRs.isCsNormalRestricted()) {
1169                    // enable normal restriction
1170                    setNotification(CS_NORMAL_ENABLED);
1171                }
1172            }
1173
1174            mRestrictedState = newRs;
1175        }
1176        log("onRestrictedStateChanged: X rs "+ mRestrictedState);
1177    }
1178
1179    /** code is registration state 0-5 from TS 27.007 7.2 */
1180    private int regCodeToServiceState(int code) {
1181        switch (code) {
1182            case 0:
1183            case 2: // 2 is "searching"
1184            case 3: // 3 is "registration denied"
1185            case 4: // 4 is "unknown" no vaild in current baseband
1186            case 10:// same as 0, but indicates that emergency call is possible.
1187            case 12:// same as 2, but indicates that emergency call is possible.
1188            case 13:// same as 3, but indicates that emergency call is possible.
1189            case 14:// same as 4, but indicates that emergency call is possible.
1190                return ServiceState.STATE_OUT_OF_SERVICE;
1191
1192            case 1:
1193                return ServiceState.STATE_IN_SERVICE;
1194
1195            case 5:
1196                // in service, roam
1197                return ServiceState.STATE_IN_SERVICE;
1198
1199            default:
1200                loge("regCodeToServiceState: unexpected service state " + code);
1201                return ServiceState.STATE_OUT_OF_SERVICE;
1202        }
1203    }
1204
1205
1206    /**
1207     * code is registration state 0-5 from TS 27.007 7.2
1208     * returns true if registered roam, false otherwise
1209     */
1210    private boolean regCodeIsRoaming (int code) {
1211        // 5 is  "in service -- roam"
1212        return 5 == code;
1213    }
1214
1215    /**
1216     * Set roaming state when gsmRoaming is true and, if operator mcc is the
1217     * same as sim mcc, ons is different from spn
1218     * @param gsmRoaming TS 27.007 7.2 CREG registered roaming
1219     * @param s ServiceState hold current ons
1220     * @return true for roaming state set
1221     */
1222    private boolean isRoamingBetweenOperators(boolean gsmRoaming, ServiceState s) {
1223        String spn = SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA, "empty");
1224
1225        String onsl = s.getOperatorAlphaLong();
1226        String onss = s.getOperatorAlphaShort();
1227
1228        boolean equalsOnsl = onsl != null && spn.equals(onsl);
1229        boolean equalsOnss = onss != null && spn.equals(onss);
1230
1231        String simNumeric = SystemProperties.get(
1232                TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, "");
1233        String  operatorNumeric = s.getOperatorNumeric();
1234
1235        boolean equalsMcc = true;
1236        try {
1237            equalsMcc = simNumeric.substring(0, 3).
1238                    equals(operatorNumeric.substring(0, 3));
1239        } catch (Exception e){
1240        }
1241
1242        return gsmRoaming && !(equalsMcc && (equalsOnsl || equalsOnss));
1243    }
1244
1245    private static int twoDigitsAt(String s, int offset) {
1246        int a, b;
1247
1248        a = Character.digit(s.charAt(offset), 10);
1249        b = Character.digit(s.charAt(offset+1), 10);
1250
1251        if (a < 0 || b < 0) {
1252
1253            throw new RuntimeException("invalid format");
1254        }
1255
1256        return a*10 + b;
1257    }
1258
1259    /**
1260     * @return The current GPRS state. IN_SERVICE is the same as "attached"
1261     * and OUT_OF_SERVICE is the same as detached.
1262     */
1263    int getCurrentGprsState() {
1264        return gprsState;
1265    }
1266
1267    public int getCurrentDataConnectionState() {
1268        return gprsState;
1269    }
1270
1271    /**
1272     * @return true if phone is camping on a technology (eg UMTS)
1273     * that could support voice and data simultaneously.
1274     */
1275    public boolean isConcurrentVoiceAndDataAllowed() {
1276        return (mRilRadioTechnology >= ServiceState.RIL_RADIO_TECHNOLOGY_UMTS);
1277    }
1278
1279    /**
1280     * Provides the name of the algorithmic time zone for the specified
1281     * offset.  Taken from TimeZone.java.
1282     */
1283    private static String displayNameFor(int off) {
1284        off = off / 1000 / 60;
1285
1286        char[] buf = new char[9];
1287        buf[0] = 'G';
1288        buf[1] = 'M';
1289        buf[2] = 'T';
1290
1291        if (off < 0) {
1292            buf[3] = '-';
1293            off = -off;
1294        } else {
1295            buf[3] = '+';
1296        }
1297
1298        int hours = off / 60;
1299        int minutes = off % 60;
1300
1301        buf[4] = (char) ('0' + hours / 10);
1302        buf[5] = (char) ('0' + hours % 10);
1303
1304        buf[6] = ':';
1305
1306        buf[7] = (char) ('0' + minutes / 10);
1307        buf[8] = (char) ('0' + minutes % 10);
1308
1309        return new String(buf);
1310    }
1311
1312    /**
1313     * nitzReceiveTime is time_t that the NITZ time was posted
1314     */
1315    private void setTimeFromNITZString (String nitz, long nitzReceiveTime) {
1316        // "yy/mm/dd,hh:mm:ss(+/-)tz"
1317        // tz is in number of quarter-hours
1318
1319        long start = SystemClock.elapsedRealtime();
1320        if (DBG) {log("NITZ: " + nitz + "," + nitzReceiveTime +
1321                        " start=" + start + " delay=" + (start - nitzReceiveTime));
1322        }
1323
1324        try {
1325            /* NITZ time (hour:min:sec) will be in UTC but it supplies the timezone
1326             * offset as well (which we won't worry about until later) */
1327            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
1328
1329            c.clear();
1330            c.set(Calendar.DST_OFFSET, 0);
1331
1332            String[] nitzSubs = nitz.split("[/:,+-]");
1333
1334            int year = 2000 + Integer.parseInt(nitzSubs[0]);
1335            c.set(Calendar.YEAR, year);
1336
1337            // month is 0 based!
1338            int month = Integer.parseInt(nitzSubs[1]) - 1;
1339            c.set(Calendar.MONTH, month);
1340
1341            int date = Integer.parseInt(nitzSubs[2]);
1342            c.set(Calendar.DATE, date);
1343
1344            int hour = Integer.parseInt(nitzSubs[3]);
1345            c.set(Calendar.HOUR, hour);
1346
1347            int minute = Integer.parseInt(nitzSubs[4]);
1348            c.set(Calendar.MINUTE, minute);
1349
1350            int second = Integer.parseInt(nitzSubs[5]);
1351            c.set(Calendar.SECOND, second);
1352
1353            boolean sign = (nitz.indexOf('-') == -1);
1354
1355            int tzOffset = Integer.parseInt(nitzSubs[6]);
1356
1357            int dst = (nitzSubs.length >= 8 ) ? Integer.parseInt(nitzSubs[7])
1358                                              : 0;
1359
1360            // The zone offset received from NITZ is for current local time,
1361            // so DST correction is already applied.  Don't add it again.
1362            //
1363            // tzOffset += dst * 4;
1364            //
1365            // We could unapply it if we wanted the raw offset.
1366
1367            tzOffset = (sign ? 1 : -1) * tzOffset * 15 * 60 * 1000;
1368
1369            TimeZone    zone = null;
1370
1371            // As a special extension, the Android emulator appends the name of
1372            // the host computer's timezone to the nitz string. this is zoneinfo
1373            // timezone name of the form Area!Location or Area!Location!SubLocation
1374            // so we need to convert the ! into /
1375            if (nitzSubs.length >= 9) {
1376                String  tzname = nitzSubs[8].replace('!','/');
1377                zone = TimeZone.getTimeZone( tzname );
1378            }
1379
1380            String iso = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY);
1381
1382            if (zone == null) {
1383
1384                if (mGotCountryCode) {
1385                    if (iso != null && iso.length() > 0) {
1386                        zone = TimeUtils.getTimeZone(tzOffset, dst != 0,
1387                                c.getTimeInMillis(),
1388                                iso);
1389                    } else {
1390                        // We don't have a valid iso country code.  This is
1391                        // most likely because we're on a test network that's
1392                        // using a bogus MCC (eg, "001"), so get a TimeZone
1393                        // based only on the NITZ parameters.
1394                        zone = getNitzTimeZone(tzOffset, (dst != 0), c.getTimeInMillis());
1395                    }
1396                }
1397            }
1398
1399            if ((zone == null) || (mZoneOffset != tzOffset) || (mZoneDst != (dst != 0))){
1400                // We got the time before the country or the zone has changed
1401                // so we don't know how to identify the DST rules yet.  Save
1402                // the information and hope to fix it up later.
1403
1404                mNeedFixZoneAfterNitz = true;
1405                mZoneOffset  = tzOffset;
1406                mZoneDst     = dst != 0;
1407                mZoneTime    = c.getTimeInMillis();
1408            }
1409
1410            if (zone != null) {
1411                if (getAutoTimeZone()) {
1412                    setAndBroadcastNetworkSetTimeZone(zone.getID());
1413                }
1414                saveNitzTimeZone(zone.getID());
1415            }
1416
1417            String ignore = SystemProperties.get("gsm.ignore-nitz");
1418            if (ignore != null && ignore.equals("yes")) {
1419                log("NITZ: Not setting clock because gsm.ignore-nitz is set");
1420                return;
1421            }
1422
1423            try {
1424                mWakeLock.acquire();
1425
1426                if (getAutoTime()) {
1427                    long millisSinceNitzReceived
1428                            = SystemClock.elapsedRealtime() - nitzReceiveTime;
1429
1430                    if (millisSinceNitzReceived < 0) {
1431                        // Sanity check: something is wrong
1432                        if (DBG) {
1433                            log("NITZ: not setting time, clock has rolled "
1434                                            + "backwards since NITZ time was received, "
1435                                            + nitz);
1436                        }
1437                        return;
1438                    }
1439
1440                    if (millisSinceNitzReceived > Integer.MAX_VALUE) {
1441                        // If the time is this far off, something is wrong > 24 days!
1442                        if (DBG) {
1443                            log("NITZ: not setting time, processing has taken "
1444                                        + (millisSinceNitzReceived / (1000 * 60 * 60 * 24))
1445                                        + " days");
1446                        }
1447                        return;
1448                    }
1449
1450                    // Note: with range checks above, cast to int is safe
1451                    c.add(Calendar.MILLISECOND, (int)millisSinceNitzReceived);
1452
1453                    if (DBG) {
1454                        log("NITZ: Setting time of day to " + c.getTime()
1455                            + " NITZ receive delay(ms): " + millisSinceNitzReceived
1456                            + " gained(ms): "
1457                            + (c.getTimeInMillis() - System.currentTimeMillis())
1458                            + " from " + nitz);
1459                    }
1460
1461                    setAndBroadcastNetworkSetTime(c.getTimeInMillis());
1462                    Log.i(LOG_TAG, "NITZ: after Setting time of day");
1463                }
1464                SystemProperties.set("gsm.nitz.time", String.valueOf(c.getTimeInMillis()));
1465                saveNitzTime(c.getTimeInMillis());
1466                if (false) {
1467                    long end = SystemClock.elapsedRealtime();
1468                    log("NITZ: end=" + end + " dur=" + (end - start));
1469                }
1470                mNitzUpdatedTime = true;
1471            } finally {
1472                mWakeLock.release();
1473            }
1474        } catch (RuntimeException ex) {
1475            loge("NITZ: Parsing NITZ time " + nitz + " ex=" + ex);
1476        }
1477    }
1478
1479    private boolean getAutoTime() {
1480        try {
1481            return Settings.System.getInt(phone.getContext().getContentResolver(),
1482                    Settings.System.AUTO_TIME) > 0;
1483        } catch (SettingNotFoundException snfe) {
1484            return true;
1485        }
1486    }
1487
1488    private boolean getAutoTimeZone() {
1489        try {
1490            return Settings.System.getInt(phone.getContext().getContentResolver(),
1491                    Settings.System.AUTO_TIME_ZONE) > 0;
1492        } catch (SettingNotFoundException snfe) {
1493            return true;
1494        }
1495    }
1496
1497    private void saveNitzTimeZone(String zoneId) {
1498        mSavedTimeZone = zoneId;
1499    }
1500
1501    private void saveNitzTime(long time) {
1502        mSavedTime = time;
1503        mSavedAtTime = SystemClock.elapsedRealtime();
1504    }
1505
1506    /**
1507     * Set the timezone and send out a sticky broadcast so the system can
1508     * determine if the timezone was set by the carrier.
1509     *
1510     * @param zoneId timezone set by carrier
1511     */
1512    private void setAndBroadcastNetworkSetTimeZone(String zoneId) {
1513        if (DBG) log("setAndBroadcastNetworkSetTimeZone: setTimeZone=" + zoneId);
1514        AlarmManager alarm =
1515            (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE);
1516        alarm.setTimeZone(zoneId);
1517        Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
1518        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1519        intent.putExtra("time-zone", zoneId);
1520        phone.getContext().sendStickyBroadcast(intent);
1521        if (DBG) {
1522            log("setAndBroadcastNetworkSetTimeZone: call alarm.setTimeZone and broadcast zoneId=" +
1523                zoneId);
1524        }
1525    }
1526
1527    /**
1528     * Set the time and Send out a sticky broadcast so the system can determine
1529     * if the time was set by the carrier.
1530     *
1531     * @param time time set by network
1532     */
1533    private void setAndBroadcastNetworkSetTime(long time) {
1534        if (DBG) log("setAndBroadcastNetworkSetTime: time=" + time + "ms");
1535        SystemClock.setCurrentTimeMillis(time);
1536        Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME);
1537        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1538        intent.putExtra("time", time);
1539        phone.getContext().sendStickyBroadcast(intent);
1540    }
1541
1542    private void revertToNitzTime() {
1543        if (Settings.System.getInt(phone.getContext().getContentResolver(),
1544                Settings.System.AUTO_TIME, 0) == 0) {
1545            return;
1546        }
1547        if (DBG) {
1548            log("Reverting to NITZ Time: mSavedTime=" + mSavedTime
1549                + " mSavedAtTime=" + mSavedAtTime);
1550        }
1551        if (mSavedTime != 0 && mSavedAtTime != 0) {
1552            setAndBroadcastNetworkSetTime(mSavedTime
1553                    + (SystemClock.elapsedRealtime() - mSavedAtTime));
1554        }
1555    }
1556
1557    private void revertToNitzTimeZone() {
1558        if (Settings.System.getInt(phone.getContext().getContentResolver(),
1559                Settings.System.AUTO_TIME_ZONE, 0) == 0) {
1560            return;
1561        }
1562        if (DBG) log("Reverting to NITZ TimeZone: tz='" + mSavedTimeZone);
1563        if (mSavedTimeZone != null) {
1564            setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);
1565        }
1566    }
1567
1568    /**
1569     * Post a notification to NotificationManager for restricted state
1570     *
1571     * @param notifyType is one state of PS/CS_*_ENABLE/DISABLE
1572     */
1573    private void setNotification(int notifyType) {
1574
1575        if (DBG) log("setNotification: create notification " + notifyType);
1576        Context context = phone.getContext();
1577
1578        mNotification = new Notification();
1579        mNotification.when = System.currentTimeMillis();
1580        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1581        mNotification.icon = com.android.internal.R.drawable.stat_sys_warning;
1582        Intent intent = new Intent();
1583        mNotification.contentIntent = PendingIntent
1584        .getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
1585
1586        CharSequence details = "";
1587        CharSequence title = context.getText(com.android.internal.R.string.RestrictedChangedTitle);
1588        int notificationId = CS_NOTIFICATION;
1589
1590        switch (notifyType) {
1591        case PS_ENABLED:
1592            notificationId = PS_NOTIFICATION;
1593            details = context.getText(com.android.internal.R.string.RestrictedOnData);;
1594            break;
1595        case PS_DISABLED:
1596            notificationId = PS_NOTIFICATION;
1597            break;
1598        case CS_ENABLED:
1599            details = context.getText(com.android.internal.R.string.RestrictedOnAllVoice);;
1600            break;
1601        case CS_NORMAL_ENABLED:
1602            details = context.getText(com.android.internal.R.string.RestrictedOnNormal);;
1603            break;
1604        case CS_EMERGENCY_ENABLED:
1605            details = context.getText(com.android.internal.R.string.RestrictedOnEmergency);;
1606            break;
1607        case CS_DISABLED:
1608            // do nothing and cancel the notification later
1609            break;
1610        }
1611
1612        if (DBG) log("setNotification: put notification " + title + " / " +details);
1613        mNotification.tickerText = title;
1614        mNotification.setLatestEventInfo(context, title, details,
1615                mNotification.contentIntent);
1616
1617        NotificationManager notificationManager = (NotificationManager)
1618            context.getSystemService(Context.NOTIFICATION_SERVICE);
1619
1620        if (notifyType == PS_DISABLED || notifyType == CS_DISABLED) {
1621            // cancel previous post notification
1622            notificationManager.cancel(notificationId);
1623        } else {
1624            // update restricted state notification
1625            notificationManager.notify(notificationId, mNotification);
1626        }
1627    }
1628
1629    @Override
1630    protected void log(String s) {
1631        Log.d(LOG_TAG, "[GsmSST] " + s);
1632    }
1633
1634    @Override
1635    protected void loge(String s) {
1636        Log.e(LOG_TAG, "[GsmSST] " + s);
1637    }
1638
1639    private static void sloge(String s) {
1640        Log.e(LOG_TAG, "[GsmSST] " + s);
1641    }
1642
1643    @Override
1644    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1645        pw.println("GsmServiceStateTracker extends:");
1646        super.dump(fd, pw, args);
1647        pw.println(" phone=" + phone);
1648        pw.println(" cellLoc=" + cellLoc);
1649        pw.println(" newCellLoc=" + newCellLoc);
1650        pw.println(" mPreferredNetworkType=" + mPreferredNetworkType);
1651        pw.println(" gprsState=" + gprsState);
1652        pw.println(" newGPRSState=" + newGPRSState);
1653        pw.println(" mMaxDataCalls=" + mMaxDataCalls);
1654        pw.println(" mNewMaxDataCalls=" + mNewMaxDataCalls);
1655        pw.println(" mReasonDataDenied=" + mReasonDataDenied);
1656        pw.println(" mNewReasonDataDenied=" + mNewReasonDataDenied);
1657        pw.println(" mGsmRoaming=" + mGsmRoaming);
1658        pw.println(" mDataRoaming=" + mDataRoaming);
1659        pw.println(" mEmergencyOnly=" + mEmergencyOnly);
1660        pw.println(" mNeedFixZoneAfterNitz=" + mNeedFixZoneAfterNitz);
1661        pw.println(" mZoneOffset=" + mZoneOffset);
1662        pw.println(" mZoneDst=" + mZoneDst);
1663        pw.println(" mZoneTime=" + mZoneTime);
1664        pw.println(" mGotCountryCode=" + mGotCountryCode);
1665        pw.println(" mNitzUpdatedTime=" + mNitzUpdatedTime);
1666        pw.println(" mSavedTimeZone=" + mSavedTimeZone);
1667        pw.println(" mSavedTime=" + mSavedTime);
1668        pw.println(" mSavedAtTime=" + mSavedAtTime);
1669        pw.println(" mNeedToRegForSimLoaded=" + mNeedToRegForSimLoaded);
1670        pw.println(" mStartedGprsRegCheck=" + mStartedGprsRegCheck);
1671        pw.println(" mReportedGprsNoReg=" + mReportedGprsNoReg);
1672        pw.println(" mNotification=" + mNotification);
1673        pw.println(" mWakeLock=" + mWakeLock);
1674        pw.println(" curSpn=" + curSpn);
1675        pw.println(" curPlmn=" + curPlmn);
1676        pw.println(" curSpnRule=" + curSpnRule);
1677    }
1678}
1679