From df59053588501178263e0e8de37f23717e649ffc Mon Sep 17 00:00:00 2001 From: Lorenzo Colitti Date: Thu, 22 Jan 2015 22:35:33 +0900 Subject: Only try to fetch time from NTP if there is a network connection. Bug: 19046107 Change-Id: Iff647ee33fe0eb9b530d7baad636d32b386e4fa7 --- core/java/android/util/NtpTrustedTime.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'core/java/android/util') diff --git a/core/java/android/util/NtpTrustedTime.java b/core/java/android/util/NtpTrustedTime.java index 602a68c..8ebcacd 100644 --- a/core/java/android/util/NtpTrustedTime.java +++ b/core/java/android/util/NtpTrustedTime.java @@ -19,6 +19,8 @@ package android.util; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; import android.net.SntpClient; import android.os.SystemClock; import android.provider.Settings; @@ -34,10 +36,13 @@ public class NtpTrustedTime implements TrustedTime { private static final boolean LOGD = false; private static NtpTrustedTime sSingleton; + private static Context sContext; private final String mServer; private final long mTimeout; + private ConnectivityManager mCM; + private boolean mHasCache; private long mCachedNtpTime; private long mCachedNtpElapsedRealtime; @@ -66,6 +71,7 @@ public class NtpTrustedTime implements TrustedTime { final String server = secureServer != null ? secureServer : defaultServer; sSingleton = new NtpTrustedTime(server, timeout); + sContext = context; } return sSingleton; @@ -78,6 +84,20 @@ public class NtpTrustedTime implements TrustedTime { return false; } + // We can't do this at initialization time: ConnectivityService might not be running yet. + synchronized (this) { + if (mCM == null) { + mCM = (ConnectivityManager) sContext.getSystemService(Context.CONNECTIVITY_SERVICE); + } + } + + final NetworkInfo ni = mCM == null ? null : mCM.getActiveNetworkInfo(); + if (ni == null || !ni.isConnected()) { + if (LOGD) Log.d(TAG, "forceRefresh: no connectivity"); + return false; + } + + if (LOGD) Log.d(TAG, "forceRefresh() from cache miss"); final SntpClient client = new SntpClient(); if (client.requestTime(mServer, (int) mTimeout)) { -- cgit v1.1