当前位置:   article > 正文

Android 本地时间/时区自动更新 -- NITZ_本地同步腾讯时间 真

本地同步腾讯时间 真

        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

  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的注册监听方法:

  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 注册:

  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去设置时间和时区

  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)并进行时间和时区的设置

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

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

  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. private boolean getAutoTimeZone() {
  10. try {
  11. return Settings.Global.getInt(mPhone.getContext().getContentResolver(),
  12. Settings.Global.AUTO_TIME_ZONE) > 0;
  13. } catch (SettingNotFoundException snfe) {
  14. return true;
  15. }
  16. }

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

  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. }

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

  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来监听数据库内容的变化

  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函数 ,到底是不是它们更新了时间/时区呢

  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. private ContentObserver mAutoTimeZoneObserver = new ContentObserver(new Handler()) {
  9. @Override
  10. public void onChange(boolean selfChange) {
  11. Rlog.i("GsmServiceStateTracker", "Auto time zone state changed");
  12. revertToNitzTimeZone();
  13. }
  14. };

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

  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. private void revertToNitzTimeZone() {
  16. if (Settings.Global.getInt(mPhone.getContext().getContentResolver(),
  17. Settings.Global.AUTO_TIME_ZONE, 0) == 0) {
  18. return;
  19. }
  20. if (DBG) log("Reverting to NITZ TimeZone: tz='" + mSavedTimeZone);
  21. if (mSavedTimeZone != null) {
  22. setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);
  23. }
  24. }

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

  1. private void saveNitzTimeZone(String zoneId) {
  2. mSavedTimeZone = zoneId;
  3. }
  4. private void saveNitzTime(long time) {
  5. mSavedTime = time;
  6. mSavedAtTime = SystemClock.elapsedRealtime();
  7. }

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


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

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

  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. * Set the time and Send out a sticky broadcast so the system can determine
  25. * if the time was set by the carrier.
  26. *
  27. * @param time time set by network
  28. */
  29. private void setAndBroadcastNetworkSetTime(long time) {
  30. if (DBG) log("setAndBroadcastNetworkSetTime: time=" + time + "ms");
  31. // 设置系统时间
  32.  SystemClock.setCurrentTimeMillis(time);
  33. Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME);
  34. intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
  35. intent.putExtra("time", time);
  36. // 发送广播
  37.  mPhone.getContext().sendStickyBroadcastAsUser(intent, UserHandle.ALL);
  38. }

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

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

  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 回调来进行最终时间的维护,这也解释了上节中我们的疑问。

  1. mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);
  2. mSettingsObserver.observe(mContext);

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

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

四、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)

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


下面看下 关键 函数 shouldFixTimeZoneNow

  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. // If mcc is invalid then we'll return false
  8. int mcc;
  9. try {
  10. mcc = Integer.parseInt(operatorNumeric.substring(0, 3));
  11. } catch (Exception e) {
  12. if (DBG) {
  13. log("shouldFixTimeZoneNow: no mcc, operatorNumeric=" + operatorNumeric +
  14. " retVal=false");
  15. }
  16. return false;
  17. }
  18. // If prevMcc is invalid will make it different from mcc
  19. // so we'll return true if the card exists.
  20. int prevMcc;
  21. try {
  22. prevMcc = Integer.parseInt(prevOperatorNumeric.substring(0, 3));
  23. } catch (Exception e) {
  24. prevMcc = mcc + 1;
  25. }
  26. // Determine if the Icc card exists
  27. boolean iccCardExist = false;
  28. if (mUiccApplcation != null) {
  29. iccCardExist = mUiccApplcation.getState() != AppState.APPSTATE_UNKNOWN;
  30. }
  31. // Determine retVal
  32. boolean retVal = ((iccCardExist && (mcc != prevMcc)) || needToFixTimeZone);
  33. if (DBG) {
  34. long ctm = System.currentTimeMillis();
  35. log("shouldFixTimeZoneNow: retVal=" + retVal +
  36. " iccCardExist=" + iccCardExist +
  37. " operatorNumeric=" + operatorNumeric + " mcc=" + mcc +
  38. " prevOperatorNumeric=" + prevOperatorNumeric + " prevMcc=" + prevMcc +
  39. " needToFixTimeZone=" + needToFixTimeZone +
  40. " ltod=" + TimeUtils.logTimeOfDay(ctm));
  41. }
  42. return retVal;
  43. }

五、案例分析

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

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

  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. 03-09 22:35:28.578 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  8. 03-09 22:35:28.579 3569 3569 D GsmSST : [GsmSST1] Reverting to NITZ TimeZone: tz='null
  9. 03-09 22:35:28.579 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  10. 03-09 22:35:28.579 3569 3569 D GsmSST : [GsmSST0] Reverting to NITZ TimeZone: tz='America/Sao_Paulo
  11. //用户操作自动对时区的开关为关
  12. 03-09 22:35:29.790 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  13. 03-09 22:35:29.791 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  14. //用户操作自动对时区的开关为开,但是由于网络状态没有发生变化,导致时区还是默认值
  15. 03-09 22:35:35.086 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  16. 03-09 22:35:35.087 3569 3569 D GsmSST : [GsmSST1] Reverting to NITZ TimeZone: tz='null
  17. 03-09 22:35:35.087 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  18. 03-09 22:35:35.087 3569 3569 D GsmSST : [GsmSST0] Reverting to NITZ TimeZone: tz='America/Sao_Paulo
  19. //用户操作自动对时区的开关为关
  20. 03-09 22:35:38.159 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  21. 03-09 22:35:38.161 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  22. //用户操作自动对时区的开关为开,但是由于网络状态没有发生变化,导致时区还是默认值
  23. 03-09 23:35:43.070 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  24. 03-09 23:35:43.071 3569 3569 D GsmSST : [GsmSST1] Reverting to NITZ TimeZone: tz='null
  25. 03-09 23:35:43.071 3569 3569 I GsmServiceStateTracker: Auto time zone state changed
  26. 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试一下。



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/594135
推荐阅读
相关标签
  

闽ICP备14008679号