1/* 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 19import 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; 26import android.content.pm.PackageManager; 27import android.database.ContentObserver; 28import android.net.ConnectivityManager; 29import android.net.ConnectivityManager.NetworkCallback; 30import android.net.Network; 31import android.os.Binder; 32import android.os.Handler; 33import android.os.HandlerThread; 34import android.os.Looper; 35import android.os.Message; 36import android.os.SystemClock; 37import android.os.PowerManager; 38import android.provider.Settings; 39import android.util.Log; 40import android.util.NtpTrustedTime; 41import android.util.TimeUtils; 42import android.util.TrustedTime; 43 44import com.android.internal.telephony.TelephonyIntents; 45import com.android.internal.util.DumpUtils; 46 47import java.io.FileDescriptor; 48import java.io.PrintWriter; 49 50/** 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 */ 60public class NetworkTimeUpdateService extends Binder { 61 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; 67 private static final int EVENT_NETWORK_CHANGED = 3; 68 69 private static final String ACTION_POLL = 70 "com.android.server.NetworkTimeUpdateService.action.POLL"; 71 72 private static final int NETWORK_CHANGE_EVENT_DELAY_MS = 1000; 73 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; 79 private Network mDefaultNetwork = null; 80 81 private Context mContext; 82 private TrustedTime mTime; 83 84 // NTP lookup is done on this thread and handler 85 private Handler mHandler; 86 private AlarmManager mAlarmManager; 87 private PendingIntent mPendingPollIntent; 88 private SettingsObserver mSettingsObserver; 89 private ConnectivityManager mCM; 90 private NetworkTimeUpdateCallback mNetworkTimeUpdateCallback; 91 // The last time that we successfully fetched the NTP time. 92 private long mLastNtpFetchTime = NOT_SET; 93 private final PowerManager.WakeLock mWakeLock; 94 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; 103 // 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; 110 mTime = NtpTrustedTime.getInstance(context); 111 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 112 mCM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 113 Intent pollIntent = new Intent(ACTION_POLL, null); 114 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0); 115 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); 124 125 mWakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock( 126 PowerManager.PARTIAL_WAKE_LOCK, TAG); 127 } 128 129 /** Initialize the receivers and initiate the first NTP request */ 130 public void systemRunning() { 131 registerForTelephonyIntents(); 132 registerForAlarms(); 133 134 HandlerThread thread = new HandlerThread(TAG); 135 thread.start(); 136 mHandler = new MyHandler(thread.getLooper()); 137 mNetworkTimeUpdateCallback = new NetworkTimeUpdateCallback(); 138 mCM.registerDefaultNetworkCallback(mNetworkTimeUpdateCallback, mHandler); 139 140 mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED); 141 mSettingsObserver.observe(mContext); 142 } 143 144 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) { 162 // 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; 165 mWakeLock.acquire(); 166 try { 167 onPollNetworkTimeUnderWakeLock(event); 168 } finally { 169 mWakeLock.release(); 170 } 171 } 172 173 private void onPollNetworkTimeUnderWakeLock(int event) { 174 final long refTime = SystemClock.elapsedRealtime(); 175 // If NITZ time was received less than mPollingIntervalMs time ago, 176 // no need to sync to NTP. 177 if (mNitzTimeSetTime != NOT_SET && refTime - mNitzTimeSetTime < mPollingIntervalMs) { 178 resetAlarm(mPollingIntervalMs); 179 return; 180 } 181 final long currentTime = System.currentTimeMillis(); 182 if (DBG) Log.d(TAG, "System time = " + currentTime); 183 // Get the NTP time 184 if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + mPollingIntervalMs 185 || event == EVENT_AUTO_TIME_CHANGED) { 186 if (DBG) Log.d(TAG, "Before Ntp fetch"); 187 188 // force refresh NTP cache when outdated 189 if (mTime.getCacheAge() >= mPollingIntervalMs) { 190 mTime.forceRefresh(); 191 } 192 193 // only update when NTP time is fresh 194 if (mTime.getCacheAge() < mPollingIntervalMs) { 195 final long ntp = mTime.currentTimeMillis(); 196 mTryAgainCounter = 0; 197 // 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. 199 if (Math.abs(ntp - currentTime) > mTimeErrorThresholdMs 200 || mLastNtpFetchTime == NOT_SET) { 201 // Set the system time 202 if (DBG && mLastNtpFetchTime == NOT_SET 203 && Math.abs(ntp - currentTime) <= mTimeErrorThresholdMs) { 204 Log.d(TAG, "For initial setup, rtc = " + currentTime); 205 } 206 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 } 214 mLastNtpFetchTime = SystemClock.elapsedRealtime(); 215 } else { 216 // Try again shortly 217 mTryAgainCounter++; 218 if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) { 219 resetAlarm(mPollingIntervalShorterMs); 220 } else { 221 // Try much later 222 mTryAgainCounter = 0; 223 resetAlarm(mPollingIntervalMs); 224 } 225 return; 226 } 227 } 228 resetAlarm(mPollingIntervalMs); 229 } 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 243 /** 244 * Checks if the user prefers to automatically set the time. 245 */ 246 private boolean isAutomaticTimeRequested() { 247 return Settings.Global.getInt( 248 mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0) != 0; 249 } 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(); 257 if (DBG) Log.d(TAG, "Received " + action); 258 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: 278 case EVENT_NETWORK_CHANGED: 279 onPollNetworkTime(msg.what); 280 break; 281 } 282 } 283 } 284 285 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 300 /** 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(); 314 resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME), 315 false, this); 316 } 317 318 @Override 319 public void onChange(boolean selfChange) { 320 mHandler.obtainMessage(mMsg).sendToTarget(); 321 } 322 } 323 324 @Override 325 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 326 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return; 327 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 } 339} 340