名词解释:
NITZ:NITZ(Network Identity and Time Zone)或网络标识和时区,是一种用于主动装备本地的时刻和日期的机制,一起也经过无线网向移动设备供给运营商信息。NITZ是自从PHASE 2+ RELEASE 96 的GSM中的可选功用,经常被用来主动更新移动电话的体系时钟。
NTP:NTP(Network Time Protocol)供给精确时刻,首要要有精确的时刻来历,这一时刻应该是世界标准时刻UTC。 NTP取得UTC的时刻来历可所以原子钟、天文台、卫星,也能够从Internet上获取。这样就有了精确而牢靠的时刻源。时刻按NTP服务器的等级传达。
1.在setting中勾选“主动确认时刻和日期”,“主动确认时区”后仅仅对key值为AUTO_TIME和AUTO_TIME_ZONE的Preference进行了赋值.
源码途径:packages/apps/Settings/src/com/android/settings/DateTimeSettings.java
2.在/frameworks/base/services/java/com/android/server/NetworkTimeUpdateService中对上述的key值进行了监听,在检测到key值改动的时分,就会发送音讯mHandler.obtainMessage(mMsg).sendToTarget();
10void observe(Context context) {
ContentResolver resolver = context.getContentResolver();
resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
false, this);
}
@Override
public void onChange(boolean selfChange) {
mHandler.obtainMessage(mMsg).sendToTarget();
}
handler接到音讯后进行音讯处理调用onPollNetworkTime(msg.what),发现无论是数据或者是wifi下都是调用该办法进行更新
9public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_AUTO_TIME_CHANGED:
case EVENT_POLL_NETWORK_TIME:
case EVENT_NETWORK_CONNECTED:
onPollNetworkTime(msg.what);
break;
}
}
3.在onPollNetworkTime办法中先判别是否勾选“主动更新时刻”,假如没勾选直接退出,假如勾选了再看,假如更新的NITZ时刻不为NOT_SET(-1),且更新距离小于mPollingIntervalMs,mPollingIntervalMs=24小时,那么就直接更新NITZ的时刻,不然用NTP同步时刻。
6// If NITZ time was received less than mPollingIntervalMs time ago,
// no need to sync to NTP.
if (mNitzTimeSetTime != NOT_SET refTime – mNitzTimeSetTime mPollingIntervalMs) {
resetAlarm(mPollingIntervalMs);
return;
}
11final long ntp = mTime.currentTimeMillis();
mTryAgainCounter = 0;
// If the clock is more than N seconds off or this is the first time it’s been
// fetched since boot, set the current time.
if (Math.abs(ntp – currentTime) > mTimeErrorThresholdMs
|| mLastNtpFetchTime == NOT_SET) {
// Set the system time
……
if (ntp / 1000 Integer.MAX_VALUE) {
SystemClock.setCurrentTimeMillis(ntp);
}
当从时刻服务器上获取的NTP时刻和当时时刻之差的绝对值大于一个阀值,体系以为当时时刻过错,需求更新时刻。
总结:
假如时刻主动同步选项未勾选,直接回来;
假如NITZ已同步且前次NITZ同步未超越24小时,则设置定时器24小时后再触发同步,即播送NetworkTimeUpdateService.ACTION_POLL;
假如NTP前次成功同步超越24小时或用户勾选主动同步选项,则进行下面的NTP同步,不然同上设置定时器24小时后再触发同步;
假如前次NTP成功同步超越24小时,则建议同步mTime.forceRefresh();
假如同步成功,获取此时NTP时刻ntp=mTime.currentTimeMillis();
假如同步时刻与当时本机时刻误差超越指定值阀值,则把ntp设置为本机时刻SystemClock.setCurrentTimeMillis(ntp)