Android 9.0
frameworks/base/services/core/java/com/android/server/NetworkTimeUpdateService.java
触发
网络时间同步有以下3种触发方式:
* 切换网络,有网络可用
* 设置
* 轮巡
网络可用
315 private class NetworkTimeUpdateCallback extends NetworkCallback {
316 @Override
317 public void onAvailable(Network network) {
318 Log.d(TAG, String.format("New default network %s; checking time.", network));
319 mDefaultNetwork = network;
320 // Running on mHandler so invoke directly.
321 onPollNetworkTime(EVENT_NETWORK_CHANGED);
322 }
323
324 @Override
325 public void onLost(Network network) {
326 if (network.equals(mDefaultNetwork)) mDefaultNetwork = null;
327 }
328 }
使用网络提供时间
System(Languages, time, updates)
Date & time
Use netowork-provided time
Use network-provided time
Use GPS-provided time
Off
系统(语言、时间、更新)
时间和日期
自动确定日期和时间
使用网络提供时间
使用GPS提供时间
关闭
330 /** Observer to watch for changes to the AUTO_TIME setting */
331 private static class SettingsObserver extends ContentObserver {
332
333 private int mMsg;
334 private Handler mHandler;
335
336 SettingsObserver(Handler handler, int msg) {
337 super(handler);
338 mHandler = handler;
339 mMsg = msg;
340 }
341
342 void observe(Context context) {
343 ContentResolver resolver = context.getContentResolver();
344 resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
345 false, this);
346 }
347
348 @Override
349 public void onChange(boolean selfChange) {
350 mHandler.obtainMessage(mMsg).sendToTarget();
351 }
352 }
轮巡
同步成功、同步失败并且重试也都失败1天后再次同步。
首次同步失败,再重试3次,重试间隔1分钟。
ACTION_POLL
71 private static final String ACTION_POLL =72 "com.android.server.NetworkTimeUpdateService.action.POLL";
Intent
120 Intent pollIntent = new Intent(ACTION_POLL, null);
121 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
PollIntent
261 /**
262 * Cancel old alarm and starts a new one for the specified interval.
263 *
264 * @param interval when to trigger the alarm, starting from now.
265 */
266 private void resetAlarm(long interval) {
267 mAlarmManager.cancel(mPendingPollIntent);
268 long now = SystemClock.elapsedRealtime();
269 long next = now + interval;
270 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
271 }
resetAlarm
211 if (mTime.getCacheAge() < mPollingIntervalMs) {
212 // Obtained fresh fix; schedule next normal update
213 resetAlarm(mPollingIntervalMs);
214 if (isAutomaticTimeRequested()) {
215 updateSystemClock(event);
216 }
217
218 } else {
219 // No fresh fix; schedule retry
220 mTryAgainCounter++;
221 if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) {
222 resetAlarm(mPollingIntervalShorterMs);
223 } else {
224 // Try much later
225 mTryAgainCounter = 0;
226 resetAlarm(mPollingIntervalMs);
227 }
228 }
更新系统时间
AUTO_TIME设置为1时才会更新系统时间。
273 /**
274 * Checks if the user prefers to automatically set the time.
275 */
276 private boolean isAutomaticTimeRequested() {
277 return Settings.Global.getInt(
278 mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0) != 0;
279 }
参数
dumpsys
dumpsys命令可以查看网络时间同步参数
android 9
轮巡短间隔1分钟,同步失败重试时用。
轮巡长间隔1天,同步成功、多次重试仍同步失败时用。
同步失败最大重试次数3次。
时间差阈值5秒,超过此值进行时间同步。
同步失败重试次数。
Long.MAX_VALUE,在Java中,long的最大值为2^63-1,即9223372036854775807。
# dumpsys network_time_update_service
PollingIntervalMs: +1d0h0m0s0ms
PollingIntervalShorterMs: +1m0s0ms
TryAgainTimesMax: 3
TimeErrorThresholdMs: +5s0ms
TryAgainCounter: 0
NTP cache age: 9223372036854775807
NTP cache certainty: 9223372036854775807
android 11
PollingIntervalMs: +1d0h0m0s0ms
PollingIntervalShorterMs: +1m0s0ms
TryAgainTimesMax: 3TryAgainCounter: 0
NTP cache result: null
默认配置
frameworks/base/core/res/res/values/config.xml
1996 <!-- Remote server that can provide NTP responses. -->
1997 <string translatable="false" name="config_ntpServer">time.android.com</string>
1998 <!-- Normal polling frequency in milliseconds -->
1999 <integer name="config_ntpPollingInterval">86400000</integer>
2000 <!-- Try-again polling interval in milliseconds, in case the network request failed -->
2001 <integer name="config_ntpPollingIntervalShorter">60000</integer>
2002 <!-- Number of times to try again with the shorter interval, before backing
2003 off until the normal polling interval. A value < 0 indicates infinite. -->
2004 <integer name="config_ntpRetry">3</integer>
2005 <!-- If the time difference is greater than this threshold in milliseconds,
2006 then update the time. -->
2007 <integer name="config_ntpThreshold">5000</integer>
2008 <!-- Timeout to wait for NTP server response in milliseconds. -->
2009 <integer name="config_ntpTimeout">5000</integer>
Interval
114 public NetworkTimeUpdateService(Context context) {
115 mContext = context;
116 mTime = NtpTrustedTime.getInstance(context);
117 mAlarmManager = mContext.getSystemService(AlarmManager.class);
118 mCM = mContext.getSystemService(ConnectivityManager.class);
119
120 Intent pollIntent = new Intent(ACTION_POLL, null);
121 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
122
123 mPollingIntervalMs = mContext.getResources().getInteger(
124 com.android.internal.R.integer.config_ntpPollingInterval);
125 mPollingIntervalShorterMs = mContext.getResources().getInteger(
126 com.android.internal.R.integer.config_ntpPollingIntervalShorter);
127 mTryAgainTimesMax = mContext.getResources().getInteger(
128 com.android.internal.R.integer.config_ntpRetry);
129 mTimeErrorThresholdMs = mContext.getResources().getInteger(
130 com.android.internal.R.integer.config_ntpThreshold);
131
132 mWakeLock = context.getSystemService(PowerManager.class).newWakeLock(
133 PowerManager.PARTIAL_WAKE_LOCK, TAG);
134 //M: For multiple NTP server retry
135 mDefaultServer = ((NtpTrustedTime) mTime).getServer();
136 mNtpServers.add(mDefaultServer);
137 for (String str : SERVERLIST)
138 {
139 mNtpServers.add(str);
140 }
141 mTryAgainCounter = 0;
142 }
Server Timeout
frameworks/base/core/java/android/util/NtpTrustedTime.java
61 public static synchronized NtpTrustedTime getInstance(Context context) {62 if (sSingleton == null) {63 final Resources res = context.getResources();64 final ContentResolver resolver = context.getContentResolver();6566 final String defaultServer = res.getString(67 com.android.internal.R.string.config_ntpServer);68 final long defaultTimeout = res.getInteger(69 com.android.internal.R.integer.config_ntpTimeout);7071 final String secureServer = Settings.Global.getString(72 resolver, Settings.Global.NTP_SERVER);73 final long timeout = Settings.Global.getLong(74 resolver, Settings.Global.NTP_TIMEOUT, defaultTimeout);7576 final String server = secureServer != null ? secureServer : defaultServer;77 sSingleton = new NtpTrustedTime(server, timeout);78 sContext = context;79 }8081 return sSingleton;82 }
Settings.Global
auto_time
settings get global auto_time
settings put global auto_time 1
settings put global auto_time 0