blob: 1ad14047adf9d7da63b26991f1049d731c27f781 [file] [log] [blame]
Amith Yamasani6734b9f2010-09-13 16:24:08 -07001/*
2 * Copyright (C) 2010 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.server;
18
Amith Yamasani6734b9f2010-09-13 16:24:08 -070019import android.app.AlarmManager;
20import android.app.PendingIntent;
21import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080026import android.content.pm.PackageManager;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070027import android.database.ContentObserver;
Amith Yamasani8d394fa2011-03-01 12:41:04 -080028import android.net.ConnectivityManager;
zhoulei45d1b262017-05-10 18:09:50 +080029import android.net.ConnectivityManager.NetworkCallback;
30import android.net.Network;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080031import android.os.Binder;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070032import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -070033import android.os.HandlerThread;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070034import android.os.Looper;
35import android.os.Message;
36import android.os.SystemClock;
Thierry Strudel8c842172015-10-29 14:40:29 -070037import android.os.PowerManager;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070038import android.provider.Settings;
39import android.util.Log;
Jeff Sharkey104344e2011-07-10 14:20:41 -070040import android.util.NtpTrustedTime;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080041import android.util.TimeUtils;
Jeff Sharkey104344e2011-07-10 14:20:41 -070042import android.util.TrustedTime;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070043
Jeff Sharkey104344e2011-07-10 14:20:41 -070044import com.android.internal.telephony.TelephonyIntents;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060045import com.android.internal.util.DumpUtils;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070046
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080047import java.io.FileDescriptor;
48import java.io.PrintWriter;
49
Amith Yamasani6734b9f2010-09-13 16:24:08 -070050/**
51 * Monitors the network time and updates the system time if it is out of sync
52 * and there hasn't been any NITZ update from the carrier recently.
53 * If looking up the network time fails for some reason, it tries a few times with a short
54 * interval and then resets to checking on longer intervals.
55 * <p>
56 * If the user enables AUTO_TIME, it will check immediately for the network time, if NITZ wasn't
57 * available.
58 * </p>
59 */
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080060public class NetworkTimeUpdateService extends Binder {
Amith Yamasani6734b9f2010-09-13 16:24:08 -070061
62 private static final String TAG = "NetworkTimeUpdateService";
63 private static final boolean DBG = false;
64
65 private static final int EVENT_AUTO_TIME_CHANGED = 1;
66 private static final int EVENT_POLL_NETWORK_TIME = 2;
Lorenzo Colittidf590532015-01-22 22:35:33 +090067 private static final int EVENT_NETWORK_CHANGED = 3;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070068
Amith Yamasani6734b9f2010-09-13 16:24:08 -070069 private static final String ACTION_POLL =
70 "com.android.server.NetworkTimeUpdateService.action.POLL";
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080071
72 private static final int NETWORK_CHANGE_EVENT_DELAY_MS = 1000;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070073 private static int POLL_REQUEST = 0;
74
75 private static final long NOT_SET = -1;
76 private long mNitzTimeSetTime = NOT_SET;
77 // TODO: Have a way to look up the timezone we are in
78 private long mNitzZoneSetTime = NOT_SET;
zhoulei45d1b262017-05-10 18:09:50 +080079 private Network mDefaultNetwork = null;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070080
81 private Context mContext;
Jeff Sharkey104344e2011-07-10 14:20:41 -070082 private TrustedTime mTime;
83
Amith Yamasani6734b9f2010-09-13 16:24:08 -070084 // NTP lookup is done on this thread and handler
85 private Handler mHandler;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070086 private AlarmManager mAlarmManager;
87 private PendingIntent mPendingPollIntent;
88 private SettingsObserver mSettingsObserver;
zhoulei45d1b262017-05-10 18:09:50 +080089 private ConnectivityManager mCM;
90 private NetworkTimeUpdateCallback mNetworkTimeUpdateCallback;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070091 // The last time that we successfully fetched the NTP time.
92 private long mLastNtpFetchTime = NOT_SET;
Thierry Strudel8c842172015-10-29 14:40:29 -070093 private final PowerManager.WakeLock mWakeLock;
Jaewan Kimc3560b82012-11-20 23:58:07 +090094
95 // Normal polling frequency
96 private final long mPollingIntervalMs;
97 // Try-again polling interval, in case the network request failed
98 private final long mPollingIntervalShorterMs;
99 // Number of times to try again
100 private final int mTryAgainTimesMax;
101 // If the time difference is greater than this threshold, then update the time.
102 private final int mTimeErrorThresholdMs;
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700103 // Keeps track of how many quick attempts were made to fetch NTP time.
104 // During bootup, the network may not have been up yet, or it's taking time for the
105 // connection to happen.
106 private int mTryAgainCounter;
107
108 public NetworkTimeUpdateService(Context context) {
109 mContext = context;
Jeff Sharkey104344e2011-07-10 14:20:41 -0700110 mTime = NtpTrustedTime.getInstance(context);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700111 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
zhoulei45d1b262017-05-10 18:09:50 +0800112 mCM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700113 Intent pollIntent = new Intent(ACTION_POLL, null);
114 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
Jaewan Kimc3560b82012-11-20 23:58:07 +0900115
116 mPollingIntervalMs = mContext.getResources().getInteger(
117 com.android.internal.R.integer.config_ntpPollingInterval);
118 mPollingIntervalShorterMs = mContext.getResources().getInteger(
119 com.android.internal.R.integer.config_ntpPollingIntervalShorter);
120 mTryAgainTimesMax = mContext.getResources().getInteger(
121 com.android.internal.R.integer.config_ntpRetry);
122 mTimeErrorThresholdMs = mContext.getResources().getInteger(
123 com.android.internal.R.integer.config_ntpThreshold);
Thierry Strudel8c842172015-10-29 14:40:29 -0700124
125 mWakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
126 PowerManager.PARTIAL_WAKE_LOCK, TAG);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700127 }
128
129 /** Initialize the receivers and initiate the first NTP request */
Svetoslav Ganova0027152013-06-25 14:59:53 -0700130 public void systemRunning() {
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700131 registerForTelephonyIntents();
132 registerForAlarms();
133
Amith Yamasani450a16b2013-09-18 16:28:50 -0700134 HandlerThread thread = new HandlerThread(TAG);
135 thread.start();
136 mHandler = new MyHandler(thread.getLooper());
zhoulei45d1b262017-05-10 18:09:50 +0800137 mNetworkTimeUpdateCallback = new NetworkTimeUpdateCallback();
138 mCM.registerDefaultNetworkCallback(mNetworkTimeUpdateCallback, mHandler);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700139
140 mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);
141 mSettingsObserver.observe(mContext);
142 }
143
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700144 private void registerForTelephonyIntents() {
145 IntentFilter intentFilter = new IntentFilter();
146 intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);
147 intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
148 mContext.registerReceiver(mNitzReceiver, intentFilter);
149 }
150
151 private void registerForAlarms() {
152 mContext.registerReceiver(
153 new BroadcastReceiver() {
154 @Override
155 public void onReceive(Context context, Intent intent) {
156 mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();
157 }
158 }, new IntentFilter(ACTION_POLL));
159 }
160
161 private void onPollNetworkTime(int event) {
zhoulei45d1b262017-05-10 18:09:50 +0800162 // If Automatic time is not set, don't bother. Similarly, if we don't
163 // have any default network, don't bother.
164 if (!isAutomaticTimeRequested() || mDefaultNetwork == null) return;
Thierry Strudel8c842172015-10-29 14:40:29 -0700165 mWakeLock.acquire();
166 try {
167 onPollNetworkTimeUnderWakeLock(event);
168 } finally {
169 mWakeLock.release();
170 }
171 }
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700172
Thierry Strudel8c842172015-10-29 14:40:29 -0700173 private void onPollNetworkTimeUnderWakeLock(int event) {
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700174 final long refTime = SystemClock.elapsedRealtime();
Jaewan Kimc3560b82012-11-20 23:58:07 +0900175 // If NITZ time was received less than mPollingIntervalMs time ago,
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700176 // no need to sync to NTP.
Jaewan Kimc3560b82012-11-20 23:58:07 +0900177 if (mNitzTimeSetTime != NOT_SET && refTime - mNitzTimeSetTime < mPollingIntervalMs) {
178 resetAlarm(mPollingIntervalMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700179 return;
180 }
181 final long currentTime = System.currentTimeMillis();
182 if (DBG) Log.d(TAG, "System time = " + currentTime);
183 // Get the NTP time
Jaewan Kimc3560b82012-11-20 23:58:07 +0900184 if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + mPollingIntervalMs
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700185 || event == EVENT_AUTO_TIME_CHANGED) {
186 if (DBG) Log.d(TAG, "Before Ntp fetch");
Jeff Sharkey104344e2011-07-10 14:20:41 -0700187
188 // force refresh NTP cache when outdated
Jaewan Kimc3560b82012-11-20 23:58:07 +0900189 if (mTime.getCacheAge() >= mPollingIntervalMs) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700190 mTime.forceRefresh();
191 }
192
193 // only update when NTP time is fresh
Jaewan Kimc3560b82012-11-20 23:58:07 +0900194 if (mTime.getCacheAge() < mPollingIntervalMs) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700195 final long ntp = mTime.currentTimeMillis();
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700196 mTryAgainCounter = 0;
Amith Yamasani708d5d42012-05-02 11:50:31 -0700197 // If the clock is more than N seconds off or this is the first time it's been
198 // fetched since boot, set the current time.
Jaewan Kimc3560b82012-11-20 23:58:07 +0900199 if (Math.abs(ntp - currentTime) > mTimeErrorThresholdMs
Amith Yamasani708d5d42012-05-02 11:50:31 -0700200 || mLastNtpFetchTime == NOT_SET) {
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700201 // Set the system time
Amith Yamasani708d5d42012-05-02 11:50:31 -0700202 if (DBG && mLastNtpFetchTime == NOT_SET
Jaewan Kimc3560b82012-11-20 23:58:07 +0900203 && Math.abs(ntp - currentTime) <= mTimeErrorThresholdMs) {
Amith Yamasani708d5d42012-05-02 11:50:31 -0700204 Log.d(TAG, "For initial setup, rtc = " + currentTime);
205 }
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700206 if (DBG) Log.d(TAG, "Ntp time to be set = " + ntp);
207 // Make sure we don't overflow, since it's going to be converted to an int
208 if (ntp / 1000 < Integer.MAX_VALUE) {
209 SystemClock.setCurrentTimeMillis(ntp);
210 }
211 } else {
212 if (DBG) Log.d(TAG, "Ntp time is close enough = " + ntp);
213 }
Amith Yamasani708d5d42012-05-02 11:50:31 -0700214 mLastNtpFetchTime = SystemClock.elapsedRealtime();
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700215 } else {
216 // Try again shortly
217 mTryAgainCounter++;
Jaewan Kimc3560b82012-11-20 23:58:07 +0900218 if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) {
219 resetAlarm(mPollingIntervalShorterMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700220 } else {
221 // Try much later
222 mTryAgainCounter = 0;
Jaewan Kimc3560b82012-11-20 23:58:07 +0900223 resetAlarm(mPollingIntervalMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700224 }
225 return;
226 }
227 }
Jaewan Kimc3560b82012-11-20 23:58:07 +0900228 resetAlarm(mPollingIntervalMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700229 }
230
231 /**
232 * Cancel old alarm and starts a new one for the specified interval.
233 *
234 * @param interval when to trigger the alarm, starting from now.
235 */
236 private void resetAlarm(long interval) {
237 mAlarmManager.cancel(mPendingPollIntent);
238 long now = SystemClock.elapsedRealtime();
239 long next = now + interval;
240 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
241 }
242
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700243 /**
244 * Checks if the user prefers to automatically set the time.
245 */
246 private boolean isAutomaticTimeRequested() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700247 return Settings.Global.getInt(
248 mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0) != 0;
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700249 }
250
251 /** Receiver for Nitz time events */
252 private BroadcastReceiver mNitzReceiver = new BroadcastReceiver() {
253
254 @Override
255 public void onReceive(Context context, Intent intent) {
256 String action = intent.getAction();
Fyodor Kupolov32af07a2016-02-26 16:54:25 -0800257 if (DBG) Log.d(TAG, "Received " + action);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700258 if (TelephonyIntents.ACTION_NETWORK_SET_TIME.equals(action)) {
259 mNitzTimeSetTime = SystemClock.elapsedRealtime();
260 } else if (TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE.equals(action)) {
261 mNitzZoneSetTime = SystemClock.elapsedRealtime();
262 }
263 }
264 };
265
266 /** Handler to do the network accesses on */
267 private class MyHandler extends Handler {
268
269 public MyHandler(Looper l) {
270 super(l);
271 }
272
273 @Override
274 public void handleMessage(Message msg) {
275 switch (msg.what) {
276 case EVENT_AUTO_TIME_CHANGED:
277 case EVENT_POLL_NETWORK_TIME:
Lorenzo Colittidf590532015-01-22 22:35:33 +0900278 case EVENT_NETWORK_CHANGED:
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700279 onPollNetworkTime(msg.what);
280 break;
281 }
282 }
283 }
284
zhoulei45d1b262017-05-10 18:09:50 +0800285 private class NetworkTimeUpdateCallback extends NetworkCallback {
286 @Override
287 public void onAvailable(Network network) {
288 Log.d(TAG, String.format("New default network %s; checking time.", network));
289 mDefaultNetwork = network;
290 // Running on mHandler so invoke directly.
291 onPollNetworkTime(EVENT_NETWORK_CHANGED);
292 }
293
294 @Override
295 public void onLost(Network network) {
296 if (network.equals(mDefaultNetwork)) mDefaultNetwork = null;
297 }
298 }
299
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700300 /** Observer to watch for changes to the AUTO_TIME setting */
301 private static class SettingsObserver extends ContentObserver {
302
303 private int mMsg;
304 private Handler mHandler;
305
306 SettingsObserver(Handler handler, int msg) {
307 super(handler);
308 mHandler = handler;
309 mMsg = msg;
310 }
311
312 void observe(Context context) {
313 ContentResolver resolver = context.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700314 resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700315 false, this);
316 }
317
318 @Override
319 public void onChange(boolean selfChange) {
320 mHandler.obtainMessage(mMsg).sendToTarget();
321 }
322 }
Fyodor Kupolov32af07a2016-02-26 16:54:25 -0800323
324 @Override
325 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600326 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -0800327 pw.print("PollingIntervalMs: ");
328 TimeUtils.formatDuration(mPollingIntervalMs, pw);
329 pw.print("\nPollingIntervalShorterMs: ");
330 TimeUtils.formatDuration(mPollingIntervalShorterMs, pw);
331 pw.println("\nTryAgainTimesMax: " + mTryAgainTimesMax);
332 pw.print("TimeErrorThresholdMs: ");
333 TimeUtils.formatDuration(mTimeErrorThresholdMs, pw);
334 pw.println("\nTryAgainCounter: " + mTryAgainCounter);
335 pw.print("LastNtpFetchTime: ");
336 TimeUtils.formatDuration(mLastNtpFetchTime, pw);
337 pw.println();
338 }
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700339}