Android 本地时间/时区自动更新 -- NITZ

来源:互联网 发布:java中的方法 编辑:程序博客网 时间:2024/05/19 12:39

NITZ - Network Identity and Time Zone,网络标识和时区,是一种用于自动配置本地时间和日期的机制,同时也通过无线网向移动设备提供运营商信息。NITZ经常被用来自动更新移动电话的系统时钟,Android原有的更新机制就是采用NITZ方式,这是一种运营商的可选服务。其基本原理简单的来说,就是UI根据 Modem主动上报的时间信息,更新终端系统的时间及时区。


一、Framework 对Modem主动上报消息的处理及时间更新

1、RIL_UNSOL_NITZ_TIME_RECEIVED 主动上报及通知

RIL在收到Modem主动上报的RIL_UNSOL_NITZ_TIME_RECEIVED消息后,调用mNITZTimeRegistrant.notifyRegistrant 通知注册者进行时间更新处理。

frameworks/opt/telephony/src/java/com/android/internal/telephony/RIL.java

[java] view plain copy
  1. case RIL_UNSOL_NITZ_TIME_RECEIVED:  
  2.                 if (RILJ_LOGD) unsljLogRet(response, ret);  
  3.                 // has bonus long containing milliseconds since boot that the NITZ  
  4.                 // time was received  
  5.                 long nitzReceiveTime = p.readLong();  
  6.                 Object[] result = new Object[2];  
  7.                 result[0] = ret;  
  8.                 result[1] = Long.valueOf(nitzReceiveTime);  
  9.                 boolean ignoreNitz = SystemProperties.getBoolean(  
  10.                         TelephonyProperties.PROPERTY_IGNORE_NITZ, false);  
  11.                 if (ignoreNitz) {  
  12.                     if (RILJ_LOGD) riljLog("ignoring UNSOL_NITZ_TIME_RECEIVED");  
  13.                 } else {  
  14.                     if (mNITZTimeRegistrant != null) {  
  15.                         mNITZTimeRegistrant  
  16.                             .notifyRegistrant(new AsyncResult (null, result, null));  // 通知注册接收方  
  17.                     }  
  18.                     // in case NITZ time registrant isn't registered yet, or a new registrant  
  19.                     // registers later  
  20.                     mLastNITZTimeInfo = result;  
  21.                 }  
  22.             break;  

mNITZTimeRegistrant的注册监听方法:

[java] view plain copy
  1. @Override   
  2. public void  setOnNITZTime(Handler h, int what, Object obj) {  
  3.         super.setOnNITZTime(h, what, obj);  
  4.         // Send the last NITZ time if we have it  
  5.         if (mLastNITZTimeInfo != null) {  
  6.             mNITZTimeRegistrant  
  7.                 .notifyRegistrant(  
  8.                     new AsyncResult (null, mLastNITZTimeInfo, null));  
  9.         }  
  10. }  

2、mNITZTimeRegistrant 注册及 EVENT_NITZ_TIME 接收处理

ServiceStateTracker在系统启动时,会调用setOnNITZTime将Tracher中的Handler与RIL中的上报消息绑定在一起,即收到上报消息,就回调Handler中的某些方法,以GsmServiceStateTracker 为例,代码分析如下:

frameworks/opt/telephony/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java

调用setOnNITZTime 进行mNITZTimeRegistrant 注册:

[java] view plain copy
  1. public GsmServiceStateTracker(GSMPhone phone) {  
  2.         super(phone, phone.mCi, new CellInfoGsm());  
  3.         mPhone = phone;  
  4.       ……  
  5.         mCi.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null);  
  6.         mCi.registerForRadioStateChanged(this, EVENT_RADIO_STATE_CHANGED, null);  
  7.         mCi.registerForVoiceNetworkStateChanged(this, EVENT_NETWORK_STATE_CHANGED, null);  
  8.         // 注册 NITZ 消息监听  
  9.         mCi.setOnNITZTime(this, EVENT_NITZ_TIME, null);      
  10.      …….  
  11. }  

接收到EVENT_NITZ_TIME后,调用 setTimeFromNITZString去设置时间和时区

[java] view plain copy
  1. case EVENT_NITZ_TIME:  
  2.         ar = (AsyncResult) msg.obj;  
  3.         String nitzString = (String)((Object[])ar.result)[0];  
  4.         long nitzReceiveTime = ((Long)((Object[])ar.result)[1]).longValue();  
  5.         setTimeFromNITZString(nitzString, nitzReceiveTime);  
  6.         break;  

setTimeFromNITZString 负责解析传过来字符串(nitzString)并进行时间和时区的设置

[java] view plain copy
  1.     /** 
  2.      * nitzReceiveTime is time_t that the NITZ time was posted 
  3.      */  
  4.     private void setTimeFromNITZString (String nitz, long nitzReceiveTime) {  
  5.         // "yy/mm/dd,hh:mm:ss(+/-)tz"  
  6.         // tz is in number of quarter-hours  
  7.   
  8.         long start = SystemClock.elapsedRealtime();  
  9.         if (DBG) {log("NITZ: " + nitz + "," + nitzReceiveTime +  
  10.                         " start=" + start + " delay=" + (start - nitzReceiveTime));  
  11.         }  
  12.   
  13.         // 解析从 modem 获取的时间字符串 nitzString  
  14.         try {  
  15.             /* NITZ time (hour:min:sec) will be in UTC but it supplies the timezone 
  16.              * offset as well (which we won't worry about until later) */  
  17.             Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));  
  18.   
  19.             c.clear();  
  20.             c.set(Calendar.DST_OFFSET, 0);  
  21.   
  22.             String[] nitzSubs = nitz.split("[/:,+-]");  
  23.   
  24.             int year = 2000 + Integer.parseInt(nitzSubs[0]);  
  25.             if (year > MAX_NITZ_YEAR) {  
  26.               if (DBG) loge("NITZ year: " + year + " exceeds limit, skip NITZ time update");  
  27.               return;  
  28.             }  
  29.             c.set(Calendar.YEAR, year);  
  30.   
  31.             // month is 0 based!  
  32.             int month = Integer.parseInt(nitzSubs[1]) - 1;  
  33.             c.set(Calendar.MONTH, month);  
  34.   
  35.             int date = Integer.parseInt(nitzSubs[2]);  
  36.             c.set(Calendar.DATE, date);  
  37.   
  38.             int hour = Integer.parseInt(nitzSubs[3]);  
  39.             c.set(Calendar.HOUR, hour);  
  40.   
  41.             int minute = Integer.parseInt(nitzSubs[4]);  
  42.             c.set(Calendar.MINUTE, minute);  
  43.   
  44.             int second = Integer.parseInt(nitzSubs[5]);  
  45.             c.set(Calendar.SECOND, second);  
  46.   
  47.             boolean sign = (nitz.indexOf('-') == -1);  
  48.   
  49.             int tzOffset = Integer.parseInt(nitzSubs[6]);  
  50.   
  51.             int dst = (nitzSubs.length >= 8 ) ? Integer.parseInt(nitzSubs[7])  
  52.                                               : 0;  
  53.   
  54.             // The zone offset received from NITZ is for current local time,  
  55.             // so DST correction is already applied.  Don't add it again.  
  56.             //  
  57.             // tzOffset += dst * 4;  
  58.             //  
  59.             // We could unapply it if we wanted the raw offset.  
  60.   
  61.             tzOffset = (sign ? 1 : -1) * tzOffset * 15 * 60 * 1000;  
  62.   
  63.             TimeZone    zone = null;  
  64.   
  65.             // As a special extension, the Android emulator appends the name of  
  66.             // the host computer's timezone to the nitz string. this is zoneinfo  
  67.             // timezone name of the form Area!Location or Area!Location!SubLocation  
  68.             // so we need to convert the ! into /  
  69.             if (nitzSubs.length >= 9) {  
  70.                 String  tzname = nitzSubs[8].replace('!','/');  
  71.                 zone = TimeZone.getTimeZone( tzname );  
  72.             }  
  73.   
  74.             String iso = ((TelephonyManager) mPhone.getContext().  
  75.                     getSystemService(Context.TELEPHONY_SERVICE)).  
  76.                     getNetworkCountryIsoForPhone(mPhone.getPhoneId());  
  77.   
  78.             if (zone == null) {  
  79.   
  80.                 if (mGotCountryCode) {  
  81.                     if (iso != null && iso.length() > 0) {  
  82.                         zone = TimeUtils.getTimeZone(tzOffset, dst != 0,  
  83.                                 c.getTimeInMillis(),  
  84.                                 iso);  
  85.                     } else {  
  86.                         // We don't have a valid iso country code.  This is  
  87.                         // most likely because we're on a test network that's  
  88.                         // using a bogus MCC (eg, "001"), so get a TimeZone  
  89.                         // based only on the NITZ parameters.  
  90.                         zone = getNitzTimeZone(tzOffset, (dst != 0), c.getTimeInMillis());  
  91.                     }  
  92.                 }  
  93.             }  
  94.   
  95.             if ((zone == null) || (mZoneOffset != tzOffset) || (mZoneDst != (dst != 0))){  
  96.                 // We got the time before the country or the zone has changed  
  97.                 // so we don't know how to identify the DST rules yet.  Save  
  98.                 // the information and hope to fix it up later.  
  99.   
  100.                 mNeedFixZoneAfterNitz = true;   // 重要标记,用于SS变化时是否进行时区更新判断  
  101.                 mZoneOffset  = tzOffset;  
  102.                 mZoneDst     = dst != 0;  
  103.                 mZoneTime    = c.getTimeInMillis();  
  104.             }  
  105.   
  106.             if (zone != null) {  
  107.                 if (getAutoTimeZone()) {  
  108.                     // 设置时区并发送广播  
  109.                      setAndBroadcastNetworkSetTimeZone(zone.getID());  
  110.                 }  
  111.                 // 保存当前设置时区值  
  112.                 saveNitzTimeZone(zone.getID());  
  113.             }  
  114.   
  115.             String ignore = SystemProperties.get("gsm.ignore-nitz");  
  116.             if (ignore != null && ignore.equals("yes")) {  
  117.                 log("NITZ: Not setting clock because gsm.ignore-nitz is set");  
  118.                 return;  
  119.             }  
  120.   
  121.             try {  
  122.                 mWakeLock.acquire();  
  123.   
  124.                 if (getAutoTime()) {  
  125.                     long millisSinceNitzReceived  
  126.                             = SystemClock.elapsedRealtime() - nitzReceiveTime;  
  127.   
  128.                     if (millisSinceNitzReceived < 0) {  
  129.                         // Sanity check: something is wrong  
  130.                         if (DBG) {  
  131.                             log("NITZ: not setting time, clock has rolled "  
  132.                                             + "backwards since NITZ time was received, "  
  133.                                             + nitz);  
  134.                         }  
  135.                         return;  
  136.                     }  
  137.   
  138.                     if (millisSinceNitzReceived > Integer.MAX_VALUE) {  
  139.                         // If the time is this far off, something is wrong > 24 days!  
  140.                         if (DBG) {  
  141.                             log("NITZ: not setting time, processing has taken "  
  142.                                         + (millisSinceNitzReceived / (1000 * 60 * 60 * 24))  
  143.                                         + " days");  
  144.                         }  
  145.                         return;  
  146.                     }  
  147.   
  148.                     // Note: with range checks above, cast to int is safe  
  149.                     c.add(Calendar.MILLISECOND, (int)millisSinceNitzReceived);  
  150.   
  151.                     if (DBG) {  
  152.                         log("NITZ: Setting time of day to " + c.getTime()  
  153.                             + " NITZ receive delay(ms): " + millisSinceNitzReceived  
  154.                             + " gained(ms): "  
  155.                             + (c.getTimeInMillis() - System.currentTimeMillis())  
  156.                             + " from " + nitz);  
  157.                     }  
  158.                     // 设置系统时间并发送广播  
  159.                     setAndBroadcastNetworkSetTime(c.getTimeInMillis());  
  160.                     Rlog.i(LOG_TAG, "NITZ: after Setting time of day");  
  161.                 }  
  162.                 // 保存当前设置 NITZ 时间值并存储到系统属性  
  163.                 SystemProperties.set("gsm.nitz.time", String.valueOf(c.getTimeInMillis()));  
  164.                 saveNitzTime(c.getTimeInMillis());  
  165.                 if (VDBG) {  
  166.                     long end = SystemClock.elapsedRealtime();  
  167.                     log("NITZ: end=" + end + " dur=" + (end - start));  
  168.                 }  
  169.                 mNitzUpdatedTime = true;  
  170.             } finally {  
  171.                 mWakeLock.release();  
  172.             }  
  173.         } catch (RuntimeException ex) {  
  174.             loge("NITZ: Parsing NITZ time " + nitz + " ex=" + ex);  
  175.         }  
  176.     }  

从代码中可以看出只有在数据库对自动同步网络时间/时区为勾选状态时,才会调用setAndBroadcastNetworkSetTime和 setAndBroadcastNetworkSetTimeZone设置当前NITZ解析的时间及时区,并发送广播进行最终的系统时间/时区维护。这里相关数据库的勾选状态获取方法如下,主要判断 Settings.Global.AUTO_TIME 及 Settings.Global.AUTO_TIME_ZONE 存储值

[java] view plain copy
  1. private boolean getAutoTime() {  
  2.     try {  
  3.         return Settings.Global.getInt(mPhone.getContext().getContentResolver(),  
  4.                 Settings.Global.AUTO_TIME) > 0;  
  5.     } catch (SettingNotFoundException snfe) {  
  6.         return true;  
  7.     }  
  8. }  
  9.   
  10. private boolean getAutoTimeZone() {  
  11.     try {  
  12.         return Settings.Global.getInt(mPhone.getContext().getContentResolver(),  
  13.                 Settings.Global.AUTO_TIME_ZONE) > 0;  
  14.     } catch (SettingNotFoundException snfe) {  
  15.         return true;  
  16.     }  
  17. }  

3、Modem主动上报消息跟新流程

    如上分析, framework 对 Modem 主动上报消息RIL_UNSOL_NITZ_TIME_RECEIVED 的处理流程及时间/时区更新逻辑,可简单总结流程如下。我们可以看到发送广播后,时间及时区的最终维护走到了 NetworkTimeUpdateService  中,具体该服务做了哪些处理,后面我们再对此作进一步解读。


二、UI层面时间更新的处理逻辑    

接着,我们再从用户主动选择自动更新的角度,继续分析代码。

1、点击自动更新数据库
Android手机的自动更新时间选项都设置在时间和日期选项卡下,正常用户主动点击勾选自动更新后,会通过修改数据库value 触发时间/时区的自动更新。在2.3中只有一个选项-同步,会同时同步时区和时间日期,4.0中把他们分成了两项,时区和日期时间能分别进行自动更新,其实原理都是一样,都是在数据库中设置对应值,详细如下。

packages/apps/Settings/src/com/android/settings/DateTimeSettings.java

[java] view plain copy
  1. @Override  
  2. public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {  
  3.     if (key.equals(KEY_AUTO_TIME)) {  
  4.         boolean autoEnabled = preferences.getBoolean(key, true);  
  5.         Settings.Global.putInt(getContentResolver(), Settings.Global.AUTO_TIME,  
  6.                 autoEnabled ? 1 : 0);  
  7.         mTimePref.setEnabled(!autoEnabled);  
  8.         mDatePref.setEnabled(!autoEnabled);  
  9.     } else if (key.equals(KEY_AUTO_TIME_ZONE)) {  
  10.         boolean autoZoneEnabled = preferences.getBoolean(key, true);  
  11.         Settings.Global.putInt(  
  12.                 getContentResolver(), Settings.Global.AUTO_TIME_ZONE, autoZoneEnabled ? 1 : 0);  
  13.         mTimeZone.setEnabled(!autoZoneEnabled);  
  14.     }  
  15. }  

对于一些时间和时区共用一个控件的处理,通常会同时修改两个数据库,如

[java] view plain copy
  1. @Override  
  2. public boolean onPreferenceChange(Preference preference, Object newValue) {  
  3.     String key = preference.getKey();  
  4.     Log.d(TAG,"DateTimeSettings DateTimeSettings  key is :"+key+",value is:"+newValue);  
  5.     if (key.equals(KEY_AUTO_TIME_AND_ZONE)){   
  6.         boolean autoTimeZoneEnabled = (Boolean) newValue;  
  7.         Settings.Global.putInt(  
  8.                 getContentResolver(), Settings.Global.AUTO_TIME_ZONE, autoTimeZoneEnabled ? 1 : 0);  
  9.         mTimeZone.setEnabled(!autoTimeZoneEnabled);  
  10.         Settings.Global.putInt(getContentResolver(), Settings.Global.AUTO_TIME,  
  11.                 autoTimeZoneEnabled ? 1 : 0);  
  12.         mTimePref.setEnabled(!autoTimeZoneEnabled);  
  13.         mDatePref.setEnabled(!autoTimeZoneEnabled);          
  14.         mDateTimePreference.setEnabled(!autoTimeZoneEnabled);  
  15.     }   
  16.    .......  
  17. }  

2、数据库变化的监听处理

frameworks/opt/telephony/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java

追踪代码,发现GsmServiceStateTracker构造函数中注册了两个ContentObserver来监听数据库内容的变化

[java] view plain copy
  1.     public GsmServiceStateTracker(GSMPhone phone) {  
  2.         ……  
  3.         mCr = phone.getContext().getContentResolver();  
  4.         mCr.registerContentObserver(  
  5.                 Settings.Global.getUriFor(Settings.Global.AUTO_TIME), true,  
  6.                 mAutoTimeObserver);  
  7.         mCr.registerContentObserver(  
  8.                 Settings.Global.getUriFor(Settings.Global.AUTO_TIME_ZONE), true,  
  9.                 mAutoTimeZoneObserver);  
  10.         .…..  
  11. }  

接着再看看这两个 ContentObserver,我们发现两个关于NITZ的revert函数 ,到底是不是它们更新了时间/时区呢

[java] view plain copy
  1. private ContentObserver mAutoTimeObserver = new ContentObserver(new Handler()) {  
  2.     @Override  
  3.     public void onChange(boolean selfChange) {  
  4.         Rlog.i("GsmServiceStateTracker""Auto time state changed");  
  5.         revertToNitzTime();  
  6.     }  
  7. };  
  8.   
  9. private ContentObserver mAutoTimeZoneObserver = new ContentObserver(new Handler()) {  
  10.     @Override  
  11.     public void onChange(boolean selfChange) {  
  12.         Rlog.i("GsmServiceStateTracker""Auto time zone state changed");  
  13.         revertToNitzTimeZone();  
  14.     }  

接着看代码,终于发现了我们熟悉的调用 setAndBroadcastNetworkSetTime 和 setAndBroadcastNetworkSetTimeZone,至此,我们也就和上节的讨论关联到了一起

[java] view plain copy
  1. private void revertToNitzTime() {  
  2.     if (Settings.Global.getInt(mPhone.getContext().getContentResolver(),  
  3.             Settings.Global.AUTO_TIME, 0) == 0) {  
  4.         return;  
  5.     }  
  6.     if (DBG) {  
  7.         log("Reverting to NITZ Time: mSavedTime=" + mSavedTime  
  8.             + " mSavedAtTime=" + mSavedAtTime);  
  9.     }  
  10.     if (mSavedTime != 0 && mSavedAtTime != 0) {  
  11.         setAndBroadcastNetworkSetTime(mSavedTime  
  12.                 + (SystemClock.elapsedRealtime() - mSavedAtTime));  
  13.     }  
  14. }  
  15.   
  16. private void revertToNitzTimeZone() {  
  17.     if (Settings.Global.getInt(mPhone.getContext().getContentResolver(),  
  18.             Settings.Global.AUTO_TIME_ZONE, 0) == 0) {  
  19.         return;  
  20.     }  
  21.     if (DBG) log("Reverting to NITZ TimeZone: tz='" + mSavedTimeZone);  
  22.     if (mSavedTimeZone != null) {  
  23.         setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);  
  24.     }  
  25. }  

仔细看下代码,我们发现这里有几个关键值 mSavedTime、 mSavedAtTime 和 mSavedTimeZone 影响着上述两个调用的执行,那么他们究竟从哪里来的呢?追踪一下,如下两个函数进行了设置,具体调用在上节(Framework 对Modem主动上报消息的处理及时间更新)中与 setAndBroadcastNetworkSetTime 、setAndBroadcastNetworkSetTimeZone 有同步处理

[java] view plain copy
  1. private void saveNitzTimeZone(String zoneId) {  
  2.     mSavedTimeZone = zoneId;  
  3. }  
  4.   
  5. private void saveNitzTime(long time) {  
  6.     mSavedTime = time;  
  7.     mSavedAtTime = SystemClock.elapsedRealtime();  
  8. }  

既然找到了这些值的赋值处,是不是又有一个疑问呢?显然这里只有进行过 NITZ 时间设置才会调用 setAndBroadcastNetworkSetTime 、setAndBroadcastNetworkSetTimeZone 设置时间和时区,并发出广播进行最终维护。那么,如果从未进行过 NITZ 时间设置呢?显然这和我们实际遇到的情况是不一样的,那么必然还有其他的监听处理,带着这个问题我们继续看下最终维护时间的 NetworkTimeUpdateService


三、最终的时间维护服务 NetworkTimeUpdateService

从上面两节,发现他们时间设置最终都调到了setAndBroadcastNetworkSetTime 、setAndBroadcastNetworkSetTimeZone 进行时间与时区的更新维护,那么这两个函数到底做了什么呢,下面我们具体看下代码

[java] view plain copy
  1. /** 
  2.  * Set the timezone and send out a sticky broadcast so the system can 
  3.  * determine if the timezone was set by the carrier. 
  4.  * 
  5.  * @param zoneId timezone set by carrier 
  6.  */  
  7. private void setAndBroadcastNetworkSetTimeZone(String zoneId) {  
  8.     if (DBG) log("setAndBroadcastNetworkSetTimeZone: setTimeZone=" + zoneId);  
  9.     AlarmManager alarm =  
  10.         (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);  
  11.    // 设置时区  
  12.     alarm.setTimeZone(zoneId);  
  13.     Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);  
  14.     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);  
  15.     intent.putExtra("time-zone", zoneId);  
  16.    // 发送广播  
  17.     mPhone.getContext().sendStickyBroadcastAsUser(intent, UserHandle.ALL);  
  18.     if (DBG) {  
  19.         log("setAndBroadcastNetworkSetTimeZone: call alarm.setTimeZone and broadcast zoneId=" +  
  20.             zoneId);  
  21.     }  
  22. }  
  23.   
  24. /** 
  25.  * Set the time and Send out a sticky broadcast so the system can determine 
  26.  * if the time was set by the carrier. 
  27.  * 
  28.  * @param time time set by network 
  29.  */  
  30. private void setAndBroadcastNetworkSetTime(long time) {  
  31.     if (DBG) log("setAndBroadcastNetworkSetTime: time=" + time + "ms");  
  32.    // 设置系统时间  
  33.     SystemClock.setCurrentTimeMillis(time);  
  34.     Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME);  
  35.     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);  
  36.     intent.putExtra("time", time);  
  37.    // 发送广播  
  38.     mPhone.getContext().sendStickyBroadcastAsUser(intent, UserHandle.ALL);  
  39. }  

找到相应的 Receiver ,这里只对mNitzTimeSetTime、mNitzZoneSetTime两个变量进行了赋值,那么这样做的目的是什么呢?

frameworks/base/services/core/java/com/android/server/NetworkTimeUpdateService.java

[java] view plain copy
  1.     private BroadcastReceiver mNitzReceiver = new BroadcastReceiver() {  
  2.         @Override  
  3.         public void onReceive(Context context, Intent intent) {  
  4.             String action = intent.getAction();  
  5.             if (TelephonyIntents.ACTION_NETWORK_SET_TIME.equals(action)) {  
  6.                 mNitzTimeSetTime = SystemClock.elapsedRealtime();  
  7.             } else if (TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE.equals(action)) {  
  8.                 mNitzZoneSetTime = SystemClock.elapsedRealtime();  
  9.             }  
  10.         }  
  11. };  

继续查找这两个赋值的使用,我们发现其使用场景为 onPollNetworkTimeUnderWakeLock <- onPollNetworkTime <- handleMessage (EVENT_AUTO_TIME_CHANGED)。看到这里是不是有种似曾相识的感觉呢?对的,正如你所想的,NetworkTimeUpdateService 同样注册了对数据库 Settings.Global.AUTO_TIME 的监听SettingsObserver,在数据库变化时通过EVENT_AUTO_TIME_CHANGED 回调来进行最终时间的维护,这也解释了上节中我们的疑问。

[java] view plain copy
  1. mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);  
  2. mSettingsObserver.observe(mContext);  

同样的,onPollNetworkTime只有在设置自动更新时间打开的情况下才会调用onPollNetworkTimeUnderWakeLock 进行时间的最终维护,简单看下代码,该函数主要是用在NITZ 没更新时间的情况下,通过 NTP 服务器来完成时间的同步

[java] view plain copy
  1. private void onPollNetworkTimeUnderWakeLock(int event) {  
  2.     final long refTime = SystemClock.elapsedRealtime();  
  3.   
  4.     // If NITZ time was received less than mPollingIntervalMs time ago,  
  5.     // no need to sync to NTP.  
  6.     if (mNitzTimeSetTime != NOT_SET && refTime - mNitzTimeSetTime < mPollingIntervalMs) {  
  7.         if (DBG) Log.i(TAG, "onPollNetworkTime nitz used mNitzTimeSetTime = " + mNitzTimeSetTime + "; mNitzTimeSetTime = " +mNitzTimeSetTime + "; refTime = " +refTime + " resetAlarm 1 ...");  
  8.         resetAlarm(mPollingIntervalMs);  
  9.         return;  
  10.     }  
  11.     final long currentTime = System.currentTimeMillis();  
  12.     if (DBG) Log.i(TAG, "onPollNetworkTime after nitz logic System time = " + currentTime + ", mLastNtpFetchTime = " +mLastNtpFetchTime +", refTime = " +refTime  
  13.              +", mLastNtpFetchTime = " +mLastNtpFetchTime + ", mPollingIntervalMs = " +mPollingIntervalMs);  
  14.     // Get the NTP time  
  15.     if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + mPollingIntervalMs  
  16.             || event == EVENT_AUTO_TIME_CHANGED) {  
  17.         if (DBG) Log.i(TAG, "Before Ntp fetch");  
  18.   
  19.         // force refresh NTP cache when outdated  
  20.         if (mTime.getCacheAge() >= mPollingIntervalMs && isNetworkOk()) {  
  21.             if (DBG) Log.i(TAG, "onPollNetworkTime force refresh NTP cache when outdated ...");  
  22.             //mTime.forceRefresh();  
  23.             int index = mTryAgainCounter % mNtpServers.size();  
  24.             if (DBG) Log.i(TAG, "mTryAgainCounter = " + mTryAgainCounter + ";mNtpServers.size() = " + mNtpServers.size() + ";index = " + index + ";mNtpServers = " + mNtpServers.get(index));  
  25.             if (mTime instanceof NtpTrustedTime)  
  26.             {  
  27.                 if (DBG) Log.i(TAG, "onPollNetworkTime start foceRefresh ...");  
  28.                 ((NtpTrustedTime) mTime).setServer(mNtpServers.get(index));  
  29.                 mTime.forceRefresh();  
  30.                 ((NtpTrustedTime) mTime).setServer(mDefaultServer);  
  31.                 if (DBG) Log.i(TAG, "onPollNetworkTime after foceRefresh ...");  
  32.             }  
  33.             else  
  34.             {  
  35.                 if (DBG) Log.i(TAG, "onPollNetworkTime other TrustedTime instance ...");  
  36.                 mTime.forceRefresh();  
  37.             }  
  38.         }  
  39.   
  40.         // only update when NTP time is fresh  
  41.         if (mTime.getCacheAge() < mPollingIntervalMs) {  
  42.             if (DBG) Log.i(TAG, "onPollNetworkTime only update when NTP time is fresh ...");  
  43.             final long ntp = mTime.currentTimeMillis();  
  44.             mTryAgainCounter = 0;  
  45.             if (DBG) Log.i(TAG, "onPollNetworkTime ntp = " + ntp + ", currentTime = " +currentTime + ", mLastNtpFetchTime = "+mLastNtpFetchTime);  
  46.   
  47.             // If the clock is more than N seconds off or this is the first time it's been  
  48.             // fetched since boot, set the current time.  
  49.             if (Math.abs(ntp - currentTime) > mTimeErrorThresholdMs  
  50.                     || mLastNtpFetchTime == NOT_SET) {  
  51.                 // Set the system time  
  52.                 if (DBG && mLastNtpFetchTime == NOT_SET  
  53.                         && Math.abs(ntp - currentTime) <= mTimeErrorThresholdMs) {  
  54.                     Log.i(TAG, "For initial setup, rtc = " + currentTime);  
  55.                 }  
  56.                 if (DBG) Log.i(TAG, "Ntp time to be set = " + ntp);  
  57.                 // Make sure we don't overflow, since it's going to be converted to an int  
  58.                 if (ntp / 1000 < Integer.MAX_VALUE) {  
  59.                     if (DBG) Log.i(TAG, "onPollNetworkTime ******** SystemClock.setCurrentTimeMillis(ntp) ********");  
  60.                     SystemClock.setCurrentTimeMillis(ntp);  
  61.                 }  
  62.             } else {  
  63.                 if (DBG) Log.i(TAG, "Ntp time is close enough = " + ntp);  
  64.             }  
  65.             mLastNtpFetchTime = SystemClock.elapsedRealtime();  
  66.         } else {  
  67.             // Try again shortly  
  68.             if (DBG) Log.i(TAG, "onPollNetworkTime NTP time is not fresh... mTryAgainCounter = " + mTryAgainCounter + " mTryAgainTimesMax=" + mTryAgainTimesMax);  
  69.             mTryAgainCounter++;  
  70.             if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) {  
  71.                 if (DBG) Log.i(TAG, "onPollNetworkTime resetAlarm short ...");  
  72.                 resetAlarm(mPollingIntervalShorterMs);  
  73.             } else {  
  74.                 if (DBG) Log.i(TAG, "onPollNetworkTime clear counter resetAlarm max ...");  
  75.                 // Try much later  
  76.                 mTryAgainCounter = 0;  
  77.                 resetAlarm(mPollingIntervalMs);  
  78.             }  
  79.             return;  
  80.         }  
  81.     }  
  82.      if (DBG) Log.i(TAG, "onPollNetworkTime final resetAlarm ...");  
  83.     resetAlarm(mPollingIntervalMs);  
  84. }  

四、ServiceState 注册状态变化时触发的时间/时区更新

frameworks/opt/telephony/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java

对于SS 从非注册状态变成注册状态过程,pollStateDone 会发起时间/时区的新一轮更新处理。大概总结下,在保证当前获取的 operatorNumeric != null情况下,进行时间/时区更新的场景主要分如下几类:
1、    根据解析出的 mcc 获取有效国家码(ios)
2、    插卡且mcc 变化
3、    mNeedFixZoneAfterNitz = true,即解析出时间信息时国家码和时区还没变化(具体参考setTimeFromNITZString)

[java] view plain copy
  1. protected void pollStateDone() {  
  2.      .......  
  3.     boolean hasRegistered =  
  4.         mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE  
  5.         && mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;  
  6.   
  7.     boolean hasChanged = !mNewSS.equals(mSS);  
  8.   
  9.     if (hasRegistered) {  
  10.         mNetworkAttachedRegistrants.notifyRegistrants();  
  11.   
  12.         if (DBG) {  
  13.             log("pollStateDone: registering current mNitzUpdatedTime=" +  
  14.                     mNitzUpdatedTime + " changing to false");  
  15.         }  
  16.         mNitzUpdatedTime = false;  
  17.     }  
  18.   
  19.     if (hasChanged) {  
  20.         String operatorNumeric;  
  21.   
  22.         updateSpnDisplay();  
  23.   
  24.         tm.setNetworkOperatorNameForPhone(mPhone.getPhoneId(), mSS.getOperatorAlphaLong());  
  25.   
  26.         String prevOperatorNumeric = tm.getNetworkOperatorForPhone(mPhone.getPhoneId());  
  27.         operatorNumeric = mSS.getOperatorNumeric();  
  28.         tm.setNetworkOperatorNumericForPhone(mPhone.getPhoneId(), operatorNumeric);  
  29.         updateCarrierMccMncConfiguration(operatorNumeric,  
  30.                 prevOperatorNumeric, mPhone.getContext());  
  31.         if (operatorNumeric == null) {  
  32.             if (DBG) log("operatorNumeric is null");  
  33.             tm.setNetworkCountryIsoForPhone(mPhone.getPhoneId(), "");  
  34.             mGotCountryCode = false;  
  35.             mNitzUpdatedTime = false;  
  36.         } else {  
  37.             String iso = "";  
  38.             String mcc = "";  
  39.             try{  
  40.                 mcc = operatorNumeric.substring(03);  
  41.                 iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));  
  42.             } catch ( NumberFormatException ex){  
  43.                 loge("pollStateDone: countryCodeForMcc error" + ex);  
  44.             } catch ( StringIndexOutOfBoundsException ex) {  
  45.                 loge("pollStateDone: countryCodeForMcc error" + ex);  
  46.             }  
  47.   
  48.             tm.setNetworkCountryIsoForPhone(mPhone.getPhoneId(), iso);  
  49.             mGotCountryCode = true;  
  50.   
  51.             TimeZone zone = null;  
  52.   
  53.             if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso)) {  
  54.   
  55.                 // Test both paths if ignore nitz is true  
  56.                 boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(  
  57.                             TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&  
  58.                                 ((SystemClock.uptimeMillis() & 1) == 0);  
  59.   
  60.                 ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);  
  61.                 if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {  
  62.                     zone = uniqueZones.get(0);  
  63.                     if (DBG) {  
  64.                        log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +  
  65.                                " with zone.getID=" + zone.getID() +  
  66.                                " testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);  
  67.                     }  
  68.   
  69.                     if (getAutoTimeZone()) {  
  70.                         setAndBroadcastNetworkSetTimeZone(zone.getID());  
  71.                     }  
  72.                     saveNitzTimeZone(zone.getID());  
  73.                 } else {  
  74.                     if (DBG) {  
  75.                         log("pollStateDone: there are " + uniqueZones.size() +  
  76.                             " unique offsets for iso-cc='" + iso +  
  77.                             " testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +  
  78.                             "', do nothing");  
  79.                     }  
  80.                 }  
  81.             }  
  82.   
  83.             if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric,  
  84.                     mNeedFixZoneAfterNitz)) {  
  85.                 // If the offset is (0, false) and the timezone property  
  86.                 // is set, use the timezone property rather than  
  87.                 // GMT.  
  88.                 String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);  
  89.                 if (DBG) {  
  90.                     log("pollStateDone: fix time zone zoneName='" + zoneName +  
  91.                         "' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +  
  92.                         " iso-cc='" + iso +  
  93.                         "' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));  
  94.                 }  
  95.   
  96.                 if (zone != null) {  
  97.                     log("pollStateDone: zone="+zone);  
  98.                 } else  
  99.                 if ("".equals(iso) && mNeedFixZoneAfterNitz) {  
  100.                     // Country code not found.  This is likely a test network.  
  101.                     // Get a TimeZone based only on the NITZ parameters (best guess).  
  102.                     zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);  
  103.                     if (DBG) log("pollStateDone: using NITZ TimeZone");  
  104.                 } else  
  105.                 // "(mZoneOffset == 0) && (mZoneDst == false) &&  
  106.                 //  (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"  
  107.                 // means that we received a NITZ string telling  
  108.                 // it is  GMTin+0 w/ DST time zone  
  109.                 // BUT iso tells is NOT, e.g, a wrong NITZ reporting  
  110.                 // local time w/ 0 offset.  
  111.                 if ((mZoneOffset == 0) && (mZoneDst == false) &&  
  112.                     (zoneName != null) && (zoneName.length() > 0) &&  
  113.                     (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {  
  114.                     zone = TimeZone.getDefault();  
  115.                     if (mNeedFixZoneAfterNitz) {  
  116.                         // For wrong NITZ reporting local time w/ 0 offset,  
  117.                         // need adjust time to reflect default timezone setting  
  118.                         long ctm = System.currentTimeMillis();  
  119.                         long tzOffset = zone.getOffset(ctm);  
  120.                         if (DBG) {  
  121.                             log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +  
  122.                                     TimeUtils.logTimeOfDay(ctm));  
  123.                         }  
  124.                         if (getAutoTime()) {  
  125.                             long adj = ctm - tzOffset;  
  126.                             if (DBG) log("pollStateDone: adj ltod=" +  
  127.                                     TimeUtils.logTimeOfDay(adj));  
  128.                             setAndBroadcastNetworkSetTime(adj);  
  129.                         } else {  
  130.                             // Adjust the saved NITZ time to account for tzOffset.  
  131.                             mSavedTime = mSavedTime - tzOffset;  
  132.                         }  
  133.                     }  
  134.                     if (DBG) log("pollStateDone: using default TimeZone");  
  135.                 } else {  
  136.                     zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);  
  137.                     if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");  
  138.                 }  
  139.   
  140.                 mNeedFixZoneAfterNitz = false;  
  141.   
  142.                 if (zone != null) {  
  143.                     log("pollStateDone: zone != null zone.getID=" + zone.getID());  
  144.                     if (getAutoTimeZone()) {  
  145.                         setAndBroadcastNetworkSetTimeZone(zone.getID());  
  146.                     }  
  147.                     saveNitzTimeZone(zone.getID());  
  148.                 } else {  
  149.                     log("pollStateDone: zone == null");  
  150.                 }  
  151.             }  
  152.         }  
  153.         .......  
  154. }  


下面看下 关键 函数 shouldFixTimeZoneNow

[java] view plain copy
  1. protected boolean shouldFixTimeZoneNow(PhoneBase phoneBase, String operatorNumeric,  
  2.             String prevOperatorNumeric, boolean needToFixTimeZone) {  
  3.         // Return false if the mcc isn't valid as we don't know where we are.  
  4.         // Return true if we have an IccCard and the mcc changed or we  
  5.         // need to fix it because when the NITZ time came in we didn't  
  6.         // know the country code.  
  7.   
  8.         // If mcc is invalid then we'll return false  
  9.         int mcc;  
  10.         try {  
  11.             mcc = Integer.parseInt(operatorNumeric.substring(03));  
  12.         } catch (Exception e) {  
  13.             if (DBG) {  
  14.                 log("shouldFixTimeZoneNow: no mcc, operatorNumeric=" + operatorNumeric +  
  15.                         " retVal=false");  
  16.             }  
  17.             return false;  
  18.         }  
  19.   
  20.         // If prevMcc is invalid will make it different from mcc  
  21.         // so we'll return true if the card exists.  
  22.         int prevMcc;  
  23.         try {  
  24.             prevMcc = Integer.parseInt(prevOperatorNumeric.substring(03));  
  25.         } catch (Exception e) {  
  26.             prevMcc = mcc + 1;  
  27.         }  
  28.   
  29.         // Determine if the Icc card exists  
  30.         boolean iccCardExist = false;  
  31.         if (mUiccApplcation != null) {  
  32.             iccCardExist = mUiccApplcation.getState() != AppState.APPSTATE_UNKNOWN;  
  33.         }  
  34.   
  35.         // Determine retVal  
  36.         boolean retVal = ((iccCardExist && (mcc != prevMcc)) || needToFixTimeZone);  
  37.         if (DBG) {  
  38.             long ctm = System.currentTimeMillis();  
  39.             log("shouldFixTimeZoneNow: retVal=" + retVal +  
  40.                     " iccCardExist=" + iccCardExist +  
  41.                     " operatorNumeric=" + operatorNumeric + " mcc=" + mcc +  
  42.                     " prevOperatorNumeric=" + prevOperatorNumeric + " prevMcc=" + prevMcc +  
  43.                     " needToFixTimeZone=" + needToFixTimeZone +  
  44.                     " ltod=" + TimeUtils.logTimeOfDay(ctm));  
  45.         }  
  46.         return retVal;  
  47.     }  

五、案例分析

[系统设置][必现]关闭自动确定时区,更改时区后,重启手机,开启自动确定时区,时区同步错误

【原因分析】:原生的设计逻辑是只有在网络发生变化时才可以自动调整正确的时区,但是本问题的出现时用户在网络稳定后操作时区开关,由于此时网络不发生变化,因此导致时区无法调整正确,具体日志如下

[java] view plain copy
  1. //开始的时候,注册到网络上,但是因为自动对时区是关闭的, 导致系统默认没有更新时区,使用了默认时区  
  2. 03-09 22:35:10.392 3569 3569 D GsmSST : [GsmSST0] pollStateDone: registering current mNitzUpdatedTime=false changing to false  
  3. 03-09 22:35:10.418 3569 3569 D GsmSST : [GsmSST0] pollStateDone: fix time zone zoneName='America/Sao_Paulo' mZoneOffset=0 mZoneDst=false iso-cc='cn' iso-cc-idx=-3  
  4. 03-09 22:35:10.418 3569 3569 D GsmSST : [GsmSST0] pollStateDone: using default TimeZone  
  5. 03-09 22:35:10.418 3569 3569 D GsmSST : [GsmSST0] pollStateDone: zone != null zone.getID=America/Sao_Paulo  
  6.   
  7. //用户操作自动对时区的开关为开,但是由于网络状态没有发生变化,导致时区还是默认值  
  8. 03-09 22:35:28.578 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  9. 03-09 22:35:28.579 3569 3569 D GsmSST : [GsmSST1] Reverting to NITZ TimeZone: tz='null  
  10. 03-09 22:35:28.579 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  11. 03-09 22:35:28.579 3569 3569 D GsmSST : [GsmSST0] Reverting to NITZ TimeZone: tz='America/Sao_Paulo  
  12.   
  13. //用户操作自动对时区的开关为关  
  14. 03-09 22:35:29.790 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  15. 03-09 22:35:29.791 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  16.   
  17. //用户操作自动对时区的开关为开,但是由于网络状态没有发生变化,导致时区还是默认值  
  18. 03-09 22:35:35.086 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  19. 03-09 22:35:35.087 3569 3569 D GsmSST : [GsmSST1] Reverting to NITZ TimeZone: tz='null  
  20. 03-09 22:35:35.087 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  21. 03-09 22:35:35.087 3569 3569 D GsmSST : [GsmSST0] Reverting to NITZ TimeZone: tz='America/Sao_Paulo  
  22.   
  23. //用户操作自动对时区的开关为关  
  24. 03-09 22:35:38.159 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  25. 03-09 22:35:38.161 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  26.   
  27. //用户操作自动对时区的开关为开,但是由于网络状态没有发生变化,导致时区还是默认值  
  28. 03-09 23:35:43.070 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  29. 03-09 23:35:43.071 3569 3569 D GsmSST : [GsmSST1] Reverting to NITZ TimeZone: tz='null  
  30. 03-09 23:35:43.071 3569 3569 I GsmServiceStateTracker: Auto time zone state changed  
  31. 03-09 22:35:43.080 3569 3569 D GsmSST : [GsmSST0] Reverting to NITZ TimeZone: tz='America/Sao_Paulo  

【解决方案】:在网络注册成功后,将通过网络MCC查询出来的时区记忆下来,等待后续时区开关动作时使用


PS:NITZ 与 NTP 小结

现在Android通过网络同步时间有两种方式:NITZ和NTP,它们使用的条件不同,可以获取的信息也不一样;勾选自动同步功能后,手机首先会尝试NITZ方式,若获取时间失败,则使用NTP方式
1.NITZ(network identity and time zone)同步时间

NITZ是一种GSM/WCDMA基地台方式,必须插入SIM卡,且需要operator支持;可以提供时间和时区信息

中国大陆运营商基本是不支持的

2.NTP(network time protocol)同步时间

NTP在无SIM卡或operator不支持NITZ时使用,单纯通过网络(GPRS/WIFI)获取时间,只提供时间信息,没有时区信息(因此在不支持NITZ的地区,自动获取时区功能实际上是无效的)

NTP还有一种缓存机制:当前成功获取的时间会保存下来,当用户下次开启自动更新时间功能时会结合手机clock来进行时间更新。这也是没有任何网络时手机却能自动更新时间的原因。

此外,因为NTP是通过对时的server获取时间,当同步时间失败时,可以检查一下对时的server是否有效,并替换为其他server试一下。


原创粉丝点击