Various tidy ups / refactoring

Rename the TimeDetectorService / TimeZoneDetectorService "Callback"
interface "Environment", since "Callback" causes confusion.

Correct the docs for TimeZoneDetectorService, which had fallen out of
date.

Tidy up log tags - make them more consistent / shorter.

Tidy up the naming for the boolean that records whether the location
time zone detection feature is enabled on a device: now called
"supported" in code, since "enabled" could be confused with the user's
setting to enable it.

Test: treehugger
Bug: 149014708
Change-Id: Ia6f8fe971f68ef4660b41b66941320c3fc118917
This commit is contained in:
Neil Fuller
2021-01-29 19:49:35 +00:00
parent d7c3a8903c
commit 25dd7643ad
9 changed files with 154 additions and 145 deletions

View File

@@ -25,7 +25,6 @@ import android.app.AlarmManager;
import android.content.ContentResolver;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.SystemProperties;
@@ -39,11 +38,11 @@ import java.time.Instant;
import java.util.Objects;
/**
* The real implementation of {@link TimeDetectorStrategyImpl.Callback} used on device.
* The real implementation of {@link TimeDetectorStrategyImpl.Environment} used on device.
*/
public final class TimeDetectorStrategyCallbackImpl implements TimeDetectorStrategyImpl.Callback {
public final class EnvironmentImpl implements TimeDetectorStrategyImpl.Environment {
private final static String TAG = "timedetector.TimeDetectorStrategyCallbackImpl";
private static final String TAG = TimeDetectorService.TAG;
private static final int SYSTEM_CLOCK_UPDATE_THRESHOLD_MILLIS_DEFAULT = 2 * 1000;
@@ -52,7 +51,7 @@ public final class TimeDetectorStrategyCallbackImpl implements TimeDetectorStrat
* incorrect for sure.
*/
private static final Instant TIME_LOWER_BOUND = Instant.ofEpochMilli(
Long.max(Environment.getRootDirectory().lastModified(), Build.TIME));
Long.max(android.os.Environment.getRootDirectory().lastModified(), Build.TIME));
/**
* By default telephony and network only suggestions are accepted and telephony takes
@@ -74,7 +73,7 @@ public final class TimeDetectorStrategyCallbackImpl implements TimeDetectorStrat
@NonNull private final AlarmManager mAlarmManager;
@NonNull private final int[] mOriginPriorities;
public TimeDetectorStrategyCallbackImpl(@NonNull Context context) {
public EnvironmentImpl(@NonNull Context context) {
mContext = Objects.requireNonNull(context);
mContentResolver = Objects.requireNonNull(context.getContentResolver());

View File

@@ -50,7 +50,7 @@ import java.util.Objects;
* implementation to deal with the logic around time detection.
*/
public final class TimeDetectorService extends ITimeDetectorService.Stub {
private static final String TAG = "TimeDetectorService";
static final String TAG = "time_detector";
public static class Lifecycle extends SystemService {
@@ -73,8 +73,8 @@ public final class TimeDetectorService extends ITimeDetectorService.Stub {
@NonNull private final TimeDetectorStrategy mTimeDetectorStrategy;
private static TimeDetectorService create(@NonNull Context context) {
TimeDetectorStrategyImpl.Callback callback = new TimeDetectorStrategyCallbackImpl(context);
TimeDetectorStrategy timeDetectorStrategy = new TimeDetectorStrategyImpl(callback);
TimeDetectorStrategyImpl.Environment environment = new EnvironmentImpl(context);
TimeDetectorStrategy timeDetectorStrategy = new TimeDetectorStrategyImpl(environment);
Handler handler = FgThread.getHandler();
TimeDetectorService timeDetectorService =

View File

@@ -40,6 +40,7 @@ import com.android.server.timezonedetector.ReferenceWithHistory;
import java.time.Instant;
import java.util.Arrays;
import java.util.Objects;
/**
* An implementation of {@link TimeDetectorStrategy} that passes telephony and manual suggestions to
@@ -51,7 +52,7 @@ import java.util.Arrays;
public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
private static final boolean DBG = false;
private static final String LOG_TAG = "SimpleTimeDetectorStrategy";
private static final String LOG_TAG = TimeDetectorService.TAG;
/** A score value used to indicate "no score", either due to validation failure or age. */
private static final int TELEPHONY_INVALID_SCORE = -1;
@@ -88,7 +89,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
private final LocalLog mTimeChangesLog = new LocalLog(30, false /* useLocalTimestamps */);
@NonNull
private final Callback mCallback;
private final Environment mEnvironment;
// Used to store the last time the system clock state was set automatically. It is used to
// detect (and log) issues with the realtime clock or whether the clock is being set without
@@ -127,7 +128,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
* moved to {@link TimeDetectorStrategy}. There are similar issues with
* {@link #systemClockMillis()} while any process can modify the system clock.
*/
public interface Callback {
public interface Environment {
/**
* The absolute threshold below which the system clock need not be updated. i.e. if setting
@@ -170,8 +171,8 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
void releaseWakeLock();
}
TimeDetectorStrategyImpl(@NonNull Callback callback) {
mCallback = callback;
TimeDetectorStrategyImpl(@NonNull Environment environment) {
mEnvironment = Objects.requireNonNull(environment);
}
@Override
@@ -267,7 +268,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
@Override
public synchronized void handleAutoTimeConfigChanged() {
boolean enabled = mCallback.isAutoTimeDetectionEnabled();
boolean enabled = mEnvironment.isAutoTimeDetectionEnabled();
// When automatic time detection is enabled we update the system clock instantly if we can.
// Conversely, when automatic time detection is disabled we leave the clock as it is.
if (enabled) {
@@ -286,20 +287,20 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
ipw.increaseIndent(); // level 1
ipw.println("mLastAutoSystemClockTimeSet=" + mLastAutoSystemClockTimeSet);
ipw.println("mCallback.isAutoTimeDetectionEnabled()="
+ mCallback.isAutoTimeDetectionEnabled());
ipw.println("mCallback.elapsedRealtimeMillis()=" + mCallback.elapsedRealtimeMillis());
ipw.println("mCallback.systemClockMillis()=" + mCallback.systemClockMillis());
ipw.println("mCallback.systemClockUpdateThresholdMillis()="
+ mCallback.systemClockUpdateThresholdMillis());
ipw.printf("mCallback.autoTimeLowerBound()=%s(%s)\n",
mCallback.autoTimeLowerBound(),
mCallback.autoTimeLowerBound().toEpochMilli());
ipw.println("mEnvironment.isAutoTimeDetectionEnabled()="
+ mEnvironment.isAutoTimeDetectionEnabled());
ipw.println("mEnvironment.elapsedRealtimeMillis()=" + mEnvironment.elapsedRealtimeMillis());
ipw.println("mEnvironment.systemClockMillis()=" + mEnvironment.systemClockMillis());
ipw.println("mEnvironment.systemClockUpdateThresholdMillis()="
+ mEnvironment.systemClockUpdateThresholdMillis());
ipw.printf("mEnvironment.autoTimeLowerBound()=%s(%s)\n",
mEnvironment.autoTimeLowerBound(),
mEnvironment.autoTimeLowerBound().toEpochMilli());
String priorities =
Arrays.stream(mCallback.autoOriginPriorities())
Arrays.stream(mEnvironment.autoOriginPriorities())
.mapToObj(TimeDetectorStrategy::originToString)
.collect(joining(",", "[", "]"));
ipw.println("mCallback.autoOriginPriorities()=" + priorities);
ipw.println("mEnvironment.autoOriginPriorities()=" + priorities);
ipw.println("Time change log:");
ipw.increaseIndent(); // level 2
@@ -372,7 +373,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
}
// We can validate the suggestion against the reference time clock.
long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
long elapsedRealtimeMillis = mEnvironment.elapsedRealtimeMillis();
if (elapsedRealtimeMillis < newUtcTime.getReferenceTimeMillis()) {
// elapsedRealtime clock went backwards?
Slog.w(LOG_TAG, "New reference time is in the future? Ignoring."
@@ -391,7 +392,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
private boolean validateSuggestionAgainstLowerBound(
@NonNull TimestampedValue<Long> newUtcTime, @NonNull Object suggestion) {
Instant lowerBound = mCallback.autoTimeLowerBound();
Instant lowerBound = mEnvironment.autoTimeLowerBound();
// Suggestion is definitely wrong if it comes before lower time bound.
if (lowerBound.isAfter(Instant.ofEpochMilli(newUtcTime.getValue()))) {
@@ -405,13 +406,13 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
@GuardedBy("this")
private void doAutoTimeDetection(@NonNull String detectionReason) {
if (!mCallback.isAutoTimeDetectionEnabled()) {
if (!mEnvironment.isAutoTimeDetectionEnabled()) {
// Avoid doing unnecessary work with this (race-prone) check.
return;
}
// Try the different origins one at a time.
int[] originPriorities = mCallback.autoOriginPriorities();
int[] originPriorities = mEnvironment.autoOriginPriorities();
for (int origin : originPriorities) {
TimestampedValue<Long> newUtcTime = null;
String cause = null;
@@ -470,7 +471,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
@GuardedBy("this")
@Nullable
private TelephonyTimeSuggestion findBestTelephonySuggestion() {
long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
long elapsedRealtimeMillis = mEnvironment.elapsedRealtimeMillis();
// Telephony time suggestions are assumed to be derived from NITZ or NITZ-like signals.
// These have a number of limitations:
@@ -579,7 +580,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
}
TimestampedValue<Long> utcTime = networkSuggestion.getUtcTime();
long elapsedRealTimeMillis = mCallback.elapsedRealtimeMillis();
long elapsedRealTimeMillis = mEnvironment.elapsedRealtimeMillis();
if (!validateSuggestionUtcTime(elapsedRealTimeMillis, utcTime)) {
// The latest suggestion is not valid, usually due to its age.
return null;
@@ -599,7 +600,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
}
TimestampedValue<Long> utcTime = gnssTimeSuggestion.getUtcTime();
long elapsedRealTimeMillis = mCallback.elapsedRealtimeMillis();
long elapsedRealTimeMillis = mEnvironment.elapsedRealtimeMillis();
if (!validateSuggestionUtcTime(elapsedRealTimeMillis, utcTime)) {
// The latest suggestion is not valid, usually due to its age.
return null;
@@ -619,7 +620,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
}
TimestampedValue<Long> utcTime = externalTimeSuggestion.getUtcTime();
long elapsedRealTimeMillis = mCallback.elapsedRealtimeMillis();
long elapsedRealTimeMillis = mEnvironment.elapsedRealtimeMillis();
if (!validateSuggestionUtcTime(elapsedRealTimeMillis, utcTime)) {
// The latest suggestion is not valid, usually due to its age.
return null;
@@ -634,7 +635,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
boolean isOriginAutomatic = isOriginAutomatic(origin);
if (isOriginAutomatic) {
if (!mCallback.isAutoTimeDetectionEnabled()) {
if (!mEnvironment.isAutoTimeDetectionEnabled()) {
if (DBG) {
Slog.d(LOG_TAG, "Auto time detection is not enabled."
+ " origin=" + originToString(origin)
@@ -644,7 +645,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
return false;
}
} else {
if (mCallback.isAutoTimeDetectionEnabled()) {
if (mEnvironment.isAutoTimeDetectionEnabled()) {
if (DBG) {
Slog.d(LOG_TAG, "Auto time detection is enabled."
+ " origin=" + originToString(origin)
@@ -655,11 +656,11 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
}
}
mCallback.acquireWakeLock();
mEnvironment.acquireWakeLock();
try {
return setSystemClockUnderWakeLock(origin, time, cause);
} finally {
mCallback.releaseWakeLock();
mEnvironment.releaseWakeLock();
}
}
@@ -671,9 +672,9 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
private boolean setSystemClockUnderWakeLock(
@Origin int origin, @NonNull TimestampedValue<Long> newTime, @NonNull String cause) {
long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
long elapsedRealtimeMillis = mEnvironment.elapsedRealtimeMillis();
boolean isOriginAutomatic = isOriginAutomatic(origin);
long actualSystemClockMillis = mCallback.systemClockMillis();
long actualSystemClockMillis = mEnvironment.systemClockMillis();
if (isOriginAutomatic) {
// CLOCK_PARANOIA : Check to see if this class owns the clock or if something else
// may be setting the clock.
@@ -701,7 +702,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
// Check if the new signal would make sufficient difference to the system clock. If it's
// below the threshold then ignore it.
long absTimeDifference = Math.abs(newSystemClockMillis - actualSystemClockMillis);
long systemClockUpdateThreshold = mCallback.systemClockUpdateThresholdMillis();
long systemClockUpdateThreshold = mEnvironment.systemClockUpdateThresholdMillis();
if (absTimeDifference < systemClockUpdateThreshold) {
if (DBG) {
Slog.d(LOG_TAG, "Not setting system clock. New time and"
@@ -715,7 +716,7 @@ public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
return true;
}
mCallback.setSystemClock(newSystemClockMillis);
mEnvironment.setSystemClock(newSystemClockMillis);
String logMsg = "Set system clock using time=" + newTime
+ " cause=" + cause
+ " elapsedRealtimeMillis=" + elapsedRealtimeMillis

View File

@@ -44,30 +44,30 @@ import com.android.server.LocalServices;
import java.util.Objects;
/**
* The real implementation of {@link TimeZoneDetectorStrategyImpl.Callback}.
* The real implementation of {@link TimeZoneDetectorStrategyImpl.Environment}.
*/
public final class TimeZoneDetectorCallbackImpl implements TimeZoneDetectorStrategyImpl.Callback {
public final class EnvironmentImpl implements TimeZoneDetectorStrategyImpl.Environment {
private static final String LOG_TAG = "TimeZoneDetectorCallbackImpl";
private static final String LOG_TAG = TimeZoneDetectorService.TAG;
private static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
@NonNull private final Context mContext;
@NonNull private final Handler mHandler;
@NonNull private final ContentResolver mCr;
@NonNull private final UserManager mUserManager;
@NonNull private final boolean mGeoDetectionFeatureEnabled;
@NonNull private final boolean mGeoDetectionSupported;
@NonNull private final LocationManager mLocationManager;
// @NonNull after setConfigChangeListener() is called.
private ConfigurationChangeListener mConfigChangeListener;
TimeZoneDetectorCallbackImpl(@NonNull Context context, @NonNull Handler handler,
boolean geoDetectionFeatureEnabled) {
EnvironmentImpl(@NonNull Context context, @NonNull Handler handler,
boolean geoDetectionSupported) {
mContext = Objects.requireNonNull(context);
mHandler = Objects.requireNonNull(handler);
mCr = context.getContentResolver();
mUserManager = context.getSystemService(UserManager.class);
mLocationManager = context.getSystemService(LocationManager.class);
mGeoDetectionFeatureEnabled = geoDetectionFeatureEnabled;
mGeoDetectionSupported = geoDetectionSupported;
// Wire up the change listener. All invocations are performed on the mHandler thread.
@@ -191,7 +191,7 @@ public final class TimeZoneDetectorCallbackImpl implements TimeZoneDetectorStrat
}
private boolean isGeoDetectionSupported() {
return mGeoDetectionFeatureEnabled;
return mGeoDetectionSupported;
}
private boolean isAutoDetectionEnabled() {

View File

@@ -59,7 +59,7 @@ import java.util.Objects;
public final class TimeZoneDetectorService extends ITimeZoneDetectorService.Stub
implements IBinder.DeathRecipient {
private static final String TAG = "TimeZoneDetectorService";
static final String TAG = "time_zone_detector";
/**
* A "feature switch" for location-based time zone detection. If this is {@code false}. It is
@@ -67,19 +67,19 @@ public final class TimeZoneDetectorService extends ITimeZoneDetectorService.Stub
* is important.
*/
@Nullable
private static Boolean sGeoLocationTimeZoneDetectionEnabled;
private static Boolean sGeoLocationTimeZoneDetectionSupported;
/** Returns {@code true} if the location-based time zone detection feature is enabled. */
public static boolean isGeoLocationTimeZoneDetectionEnabled(Context context) {
if (sGeoLocationTimeZoneDetectionEnabled == null) {
public static boolean isGeoLocationTimeZoneDetectionSupported(Context context) {
if (sGeoLocationTimeZoneDetectionSupported == null) {
// The config value is expected to be the main switch. Platform developers can also
// enable the feature using a persistent system property.
sGeoLocationTimeZoneDetectionEnabled = context.getResources().getBoolean(
sGeoLocationTimeZoneDetectionSupported = context.getResources().getBoolean(
com.android.internal.R.bool.config_enableGeolocationTimeZoneDetection)
|| SystemProperties.getBoolean(
"persist.sys.location_time_zone_detection_feature_enabled", false);
}
return sGeoLocationTimeZoneDetectionEnabled;
return sGeoLocationTimeZoneDetectionSupported;
}
/**
@@ -98,11 +98,11 @@ public final class TimeZoneDetectorService extends ITimeZoneDetectorService.Stub
Context context = getContext();
Handler handler = FgThread.getHandler();
boolean geolocationTimeZoneDetectionEnabled =
isGeoLocationTimeZoneDetectionEnabled(context);
boolean geolocationTimeZoneDetectionSupported =
isGeoLocationTimeZoneDetectionSupported(context);
TimeZoneDetectorStrategy timeZoneDetectorStrategy =
TimeZoneDetectorStrategyImpl.create(
context, handler, geolocationTimeZoneDetectionEnabled);
context, handler, geolocationTimeZoneDetectionSupported);
// Create and publish the local service for use by internal callers.
TimeZoneDetectorInternal internal =
@@ -330,7 +330,7 @@ public final class TimeZoneDetectorService extends ITimeZoneDetectorService.Stub
boolean isGeoTimeZoneDetectionSupported() {
enforceManageTimeZoneDetectorPermission();
return isGeoLocationTimeZoneDetectionEnabled(mContext);
return isGeoLocationTimeZoneDetectionSupported(mContext);
}
@Override

View File

@@ -59,7 +59,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
* conditions.
*/
@VisibleForTesting
public interface Callback {
public interface Environment {
/**
* Sets a {@link ConfigurationChangeListener} that will be invoked when there are any
@@ -97,7 +97,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
void storeConfiguration(@UserIdInt int userId, TimeZoneConfiguration newConfiguration);
}
private static final String LOG_TAG = "TimeZoneDetectorStrategy";
private static final String LOG_TAG = TimeZoneDetectorService.TAG;
private static final boolean DBG = false;
/**
@@ -164,7 +164,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
private static final int KEEP_SUGGESTION_HISTORY_SIZE = 10;
@NonNull
private final Callback mCallback;
private final Environment mEnvironment;
@GuardedBy("this")
@NonNull
@@ -203,17 +203,17 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
*/
public static TimeZoneDetectorStrategyImpl create(
@NonNull Context context, @NonNull Handler handler,
boolean geolocationTimeZoneDetectionEnabled) {
boolean geolocationTimeZoneDetectionSupported) {
TimeZoneDetectorCallbackImpl callback = new TimeZoneDetectorCallbackImpl(
context, handler, geolocationTimeZoneDetectionEnabled);
return new TimeZoneDetectorStrategyImpl(callback);
EnvironmentImpl environment = new EnvironmentImpl(
context, handler, geolocationTimeZoneDetectionSupported);
return new TimeZoneDetectorStrategyImpl(environment);
}
@VisibleForTesting
public TimeZoneDetectorStrategyImpl(@NonNull Callback callback) {
mCallback = Objects.requireNonNull(callback);
mCallback.setConfigChangeListener(this::handleConfigChanged);
public TimeZoneDetectorStrategyImpl(@NonNull Environment environment) {
mEnvironment = Objects.requireNonNull(environment);
mEnvironment.setConfigChangeListener(this::handleConfigChanged);
}
/**
@@ -230,13 +230,13 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
@Override
@NonNull
public ConfigurationInternal getConfigurationInternal(@UserIdInt int userId) {
return mCallback.getConfigurationInternal(userId);
return mEnvironment.getConfigurationInternal(userId);
}
@Override
@NonNull
public synchronized ConfigurationInternal getCurrentUserConfigurationInternal() {
int currentUserId = mCallback.getCurrentUserId();
int currentUserId = mEnvironment.getCurrentUserId();
return getConfigurationInternal(currentUserId);
}
@@ -257,9 +257,9 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
return false;
}
// Store the configuration / notify as needed. This will cause the mCallback to invoke
// Store the configuration / notify as needed. This will cause the mEnvironment to invoke
// handleConfigChanged() asynchronously.
mCallback.storeConfiguration(userId, newConfiguration);
mEnvironment.storeConfiguration(userId, newConfiguration);
String logMsg = "Configuration changed:"
+ " oldConfiguration=" + oldConfiguration
@@ -275,8 +275,9 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
public synchronized void suggestGeolocationTimeZone(
@NonNull GeolocationTimeZoneSuggestion suggestion) {
int currentUserId = mCallback.getCurrentUserId();
ConfigurationInternal currentUserConfig = mCallback.getConfigurationInternal(currentUserId);
int currentUserId = mEnvironment.getCurrentUserId();
ConfigurationInternal currentUserConfig =
mEnvironment.getConfigurationInternal(currentUserId);
if (DBG) {
Slog.d(LOG_TAG, "Geolocation suggestion received."
+ " currentUserConfig=" + currentUserConfig
@@ -299,7 +300,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
public synchronized boolean suggestManualTimeZone(
@UserIdInt int userId, @NonNull ManualTimeZoneSuggestion suggestion) {
int currentUserId = mCallback.getCurrentUserId();
int currentUserId = mEnvironment.getCurrentUserId();
if (userId != currentUserId) {
Slog.w(LOG_TAG, "Manual suggestion received but user != current user, userId=" + userId
+ " suggestion=" + suggestion);
@@ -332,8 +333,9 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
public synchronized void suggestTelephonyTimeZone(
@NonNull TelephonyTimeZoneSuggestion suggestion) {
int currentUserId = mCallback.getCurrentUserId();
ConfigurationInternal currentUserConfig = mCallback.getConfigurationInternal(currentUserId);
int currentUserId = mEnvironment.getCurrentUserId();
ConfigurationInternal currentUserConfig =
mEnvironment.getConfigurationInternal(currentUserId);
if (DBG) {
Slog.d(LOG_TAG, "Telephony suggestion received. currentUserConfig=" + currentUserConfig
+ " newSuggestion=" + suggestion);
@@ -423,7 +425,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
String zoneId;
// Introduce bias towards the device's current zone when there are multiple zone suggested.
String deviceTimeZone = mCallback.getDeviceTimeZone();
String deviceTimeZone = mEnvironment.getDeviceTimeZone();
if (zoneIds.contains(deviceTimeZone)) {
if (DBG) {
Slog.d(LOG_TAG,
@@ -486,7 +488,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
@GuardedBy("this")
private void setDeviceTimeZoneIfRequired(@NonNull String newZoneId, @NonNull String cause) {
String currentZoneId = mCallback.getDeviceTimeZone();
String currentZoneId = mEnvironment.getDeviceTimeZone();
// Avoid unnecessary changes / intents.
if (newZoneId.equals(currentZoneId)) {
@@ -501,7 +503,7 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
return;
}
mCallback.setDeviceTimeZone(newZoneId);
mEnvironment.setDeviceTimeZone(newZoneId);
String msg = "Set device time zone."
+ ", currentZoneId=" + currentZoneId
+ ", newZoneId=" + newZoneId
@@ -572,8 +574,9 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
// This method is called whenever the user changes or the config for any user changes. We
// don't know what happened, so we capture the current user's config, check to see if we
// need to clear state associated with a previous user, and rerun detection.
int currentUserId = mCallback.getCurrentUserId();
ConfigurationInternal currentUserConfig = mCallback.getConfigurationInternal(currentUserId);
int currentUserId = mEnvironment.getCurrentUserId();
ConfigurationInternal currentUserConfig =
mEnvironment.getConfigurationInternal(currentUserId);
GeolocationTimeZoneSuggestion latestGeoLocationSuggestion =
mLatestGeoLocationSuggestion.get();
@@ -603,14 +606,14 @@ public final class TimeZoneDetectorStrategyImpl implements TimeZoneDetectorStrat
ipw.println("TimeZoneDetectorStrategy:");
ipw.increaseIndent(); // level 1
int currentUserId = mCallback.getCurrentUserId();
ipw.println("mCallback.getCurrentUserId()=" + currentUserId);
ConfigurationInternal configuration = mCallback.getConfigurationInternal(currentUserId);
ipw.println("mCallback.getConfiguration(currentUserId)=" + configuration);
int currentUserId = mEnvironment.getCurrentUserId();
ipw.println("mEnvironment.getCurrentUserId()=" + currentUserId);
ConfigurationInternal configuration = mEnvironment.getConfigurationInternal(currentUserId);
ipw.println("mEnvironment.getConfiguration(currentUserId)=" + configuration);
ipw.println("[Capabilities=" + configuration.createCapabilitiesAndConfig() + "]");
ipw.println("mCallback.isDeviceTimeZoneInitialized()="
+ mCallback.isDeviceTimeZoneInitialized());
ipw.println("mCallback.getDeviceTimeZone()=" + mCallback.getDeviceTimeZone());
ipw.println("mEnvironment.isDeviceTimeZoneInitialized()="
+ mEnvironment.isDeviceTimeZoneInitialized());
ipw.println("mEnvironment.getDeviceTimeZone()=" + mEnvironment.getDeviceTimeZone());
ipw.println("Time zone change log:");
ipw.increaseIndent(); // level 2

View File

@@ -74,11 +74,17 @@ import java.util.concurrent.atomic.AtomicReference;
* mode" where the real binder clients are replaced by {@link
* SimulatedLocationTimeZoneProviderProxy}. This means that the real client providers are never
* bound (ensuring no real location events will be received) and simulated events / behaviors
* can be injected via the command line. To enter simulation mode for a provider, use
* "{@code adb shell setprop persist.sys.location_tz_simulation_mode.<provider name> 1}" and reboot.
* e.g. "{@code adb shell setprop persist.sys.location_tz_simulation_mode.primary 1}}"
* Then use "{@code adb shell cmd location_time_zone_manager help}" for injection. Set the system
* properties to "0" and reboot to return to exit simulation mode.
* can be injected via the command line.
*
* <p>To enter simulation mode for a provider, use {@code adb shell cmd location_time_zone_manager
* set_provider_mode_override &lt;provider name&gt; simulated} and restart the service with {@code
* adb shell cmd location_time_zone_manager stop} and {@code adb shell cmd
* location_time_zone_manager start}.
*
* <p>e.g. {@code adb shell cmd location_time_zone_manager set_provider_mode_override primary
* simulated}.
*
* <p>See {@code adb shell cmd location_time_zone_manager help}" for more options.
*/
public class LocationTimeZoneManagerService extends Binder {
@@ -96,7 +102,7 @@ public class LocationTimeZoneManagerService extends Binder {
@Override
public void onStart() {
Context context = getContext();
if (TimeZoneDetectorService.isGeoLocationTimeZoneDetectionEnabled(context)) {
if (TimeZoneDetectorService.isGeoLocationTimeZoneDetectionSupported(context)) {
mService = new LocationTimeZoneManagerService(context);
// The service currently exposes no LocalService or Binder API, but it extends
@@ -110,7 +116,7 @@ public class LocationTimeZoneManagerService extends Binder {
@Override
public void onBootPhase(int phase) {
Context context = getContext();
if (TimeZoneDetectorService.isGeoLocationTimeZoneDetectionEnabled(context)) {
if (TimeZoneDetectorService.isGeoLocationTimeZoneDetectionSupported(context)) {
if (phase == PHASE_SYSTEM_SERVICES_READY) {
// The location service must be functioning after this boot phase.
mService.onSystemReady();

View File

@@ -1123,10 +1123,10 @@ public class TimeDetectorStrategyImplTest {
}
/**
* A fake implementation of TimeDetectorStrategy.Callback. Besides tracking changes and behaving
* like the real thing should, it also asserts preconditions.
* A fake implementation of {@link TimeDetectorStrategyImpl.Environment}. Besides tracking
* changes and behaving like the real thing should, it also asserts preconditions.
*/
private static class FakeCallback implements TimeDetectorStrategyImpl.Callback {
private static class FakeEnvironment implements TimeDetectorStrategyImpl.Environment {
private boolean mAutoTimeDetectionEnabled;
private boolean mWakeLockAcquired;
private long mElapsedRealtimeMillis;
@@ -1254,41 +1254,41 @@ public class TimeDetectorStrategyImplTest {
*/
private class Script {
private final FakeCallback mFakeCallback;
private final FakeEnvironment mFakeEnvironment;
private final TimeDetectorStrategyImpl mTimeDetectorStrategy;
Script() {
mFakeCallback = new FakeCallback();
mTimeDetectorStrategy = new TimeDetectorStrategyImpl(mFakeCallback);
mFakeEnvironment = new FakeEnvironment();
mTimeDetectorStrategy = new TimeDetectorStrategyImpl(mFakeEnvironment);
}
Script pokeAutoTimeDetectionEnabled(boolean enabled) {
mFakeCallback.pokeAutoTimeDetectionEnabled(enabled);
mFakeEnvironment.pokeAutoTimeDetectionEnabled(enabled);
return this;
}
Script pokeFakeClocks(TimestampedValue<Instant> timeInfo) {
mFakeCallback.pokeElapsedRealtimeMillis(timeInfo.getReferenceTimeMillis());
mFakeCallback.pokeSystemClockMillis(timeInfo.getValue().toEpochMilli());
mFakeEnvironment.pokeElapsedRealtimeMillis(timeInfo.getReferenceTimeMillis());
mFakeEnvironment.pokeSystemClockMillis(timeInfo.getValue().toEpochMilli());
return this;
}
Script pokeThresholds(int systemClockUpdateThreshold) {
mFakeCallback.pokeSystemClockUpdateThreshold(systemClockUpdateThreshold);
mFakeEnvironment.pokeSystemClockUpdateThreshold(systemClockUpdateThreshold);
return this;
}
Script pokeAutoOriginPriorities(@Origin int... autoOriginPriorities) {
mFakeCallback.pokeAutoOriginPriorities(autoOriginPriorities);
mFakeEnvironment.pokeAutoOriginPriorities(autoOriginPriorities);
return this;
}
long peekElapsedRealtimeMillis() {
return mFakeCallback.peekElapsedRealtimeMillis();
return mFakeEnvironment.peekElapsedRealtimeMillis();
}
long peekSystemClockMillis() {
return mFakeCallback.peekSystemClockMillis();
return mFakeEnvironment.peekSystemClockMillis();
}
Script simulateTelephonyTimeSuggestion(TelephonyTimeSuggestion timeSuggestion) {
@@ -1324,13 +1324,13 @@ public class TimeDetectorStrategyImplTest {
}
Script simulateAutoTimeDetectionToggle() {
mFakeCallback.simulateAutoTimeZoneDetectionToggle();
mFakeEnvironment.simulateAutoTimeZoneDetectionToggle();
mTimeDetectorStrategy.handleAutoTimeConfigChanged();
return this;
}
Script simulateTimePassing(long clockIncrementMillis) {
mFakeCallback.simulateTimePassing(clockIncrementMillis);
mFakeEnvironment.simulateTimePassing(clockIncrementMillis);
return this;
}
@@ -1342,14 +1342,14 @@ public class TimeDetectorStrategyImplTest {
}
Script verifySystemClockWasNotSetAndResetCallTracking() {
mFakeCallback.verifySystemClockNotSet();
mFakeCallback.resetCallTracking();
mFakeEnvironment.verifySystemClockNotSet();
mFakeEnvironment.resetCallTracking();
return this;
}
Script verifySystemClockWasSetAndResetCallTracking(long expectedSystemClockMillis) {
mFakeCallback.verifySystemClockWasSet(expectedSystemClockMillis);
mFakeCallback.resetCallTracking();
mFakeEnvironment.verifySystemClockWasSet(expectedSystemClockMillis);
mFakeEnvironment.resetCallTracking();
return this;
}
@@ -1427,7 +1427,7 @@ public class TimeDetectorStrategyImplTest {
ManualTimeSuggestion generateManualTimeSuggestion(Instant suggestedTime) {
TimestampedValue<Long> utcTime =
new TimestampedValue<>(
mFakeCallback.peekElapsedRealtimeMillis(),
mFakeEnvironment.peekElapsedRealtimeMillis(),
suggestedTime.toEpochMilli());
return new ManualTimeSuggestion(utcTime);
}
@@ -1461,7 +1461,7 @@ public class TimeDetectorStrategyImplTest {
NetworkTimeSuggestion generateNetworkTimeSuggestion(Instant suggestedTime) {
TimestampedValue<Long> utcTime =
new TimestampedValue<>(
mFakeCallback.peekElapsedRealtimeMillis(),
mFakeEnvironment.peekElapsedRealtimeMillis(),
suggestedTime.toEpochMilli());
return new NetworkTimeSuggestion(utcTime);
}
@@ -1473,7 +1473,7 @@ public class TimeDetectorStrategyImplTest {
GnssTimeSuggestion generateGnssTimeSuggestion(Instant suggestedTime) {
TimestampedValue<Long> utcTime =
new TimestampedValue<>(
mFakeCallback.peekElapsedRealtimeMillis(),
mFakeEnvironment.peekElapsedRealtimeMillis(),
suggestedTime.toEpochMilli());
return new GnssTimeSuggestion(utcTime);
}
@@ -1485,7 +1485,7 @@ public class TimeDetectorStrategyImplTest {
ExternalTimeSuggestion generateExternalTimeSuggestion(Instant suggestedTime) {
TimestampedValue<Long> utcTime =
new TimestampedValue<>(
mFakeCallback.peekElapsedRealtimeMillis(),
mFakeEnvironment.peekElapsedRealtimeMillis(),
suggestedTime.toEpochMilli());
return new ExternalTimeSuggestion(utcTime);
}

View File

@@ -167,15 +167,15 @@ public class TimeZoneDetectorStrategyImplTest {
createConfig(null, false /* geoDetection */);
private TimeZoneDetectorStrategyImpl mTimeZoneDetectorStrategy;
private FakeCallback mFakeCallback;
private FakeEnvironment mFakeEnvironment;
private MockConfigChangeListener mMockConfigChangeListener;
@Before
public void setUp() {
mFakeCallback = new FakeCallback();
mFakeEnvironment = new FakeEnvironment();
mMockConfigChangeListener = new MockConfigChangeListener();
mTimeZoneDetectorStrategy = new TimeZoneDetectorStrategyImpl(mFakeCallback);
mTimeZoneDetectorStrategy = new TimeZoneDetectorStrategyImpl(mFakeEnvironment);
mTimeZoneDetectorStrategy.addConfigChangeListener(mMockConfigChangeListener);
}
@@ -183,7 +183,7 @@ public class TimeZoneDetectorStrategyImplTest {
public void testGetCurrentUserConfiguration() {
new Script().initializeConfig(CONFIG_INT_AUTO_ENABLED_GEO_DISABLED);
ConfigurationInternal expectedConfiguration =
mFakeCallback.getConfigurationInternal(USER_ID);
mFakeEnvironment.getConfigurationInternal(USER_ID);
assertEquals(expectedConfiguration,
mTimeZoneDetectorStrategy.getCurrentUserConfigurationInternal());
}
@@ -490,7 +490,7 @@ public class TimeZoneDetectorStrategyImplTest {
private void makeSlotIndex1SuggestionAndCheckState(Script script, TelephonyTestCase testCase) {
// Give the next suggestion a different zone from the currently set device time zone;
String currentZoneId = mFakeCallback.getDeviceTimeZone();
String currentZoneId = mFakeEnvironment.getDeviceTimeZone();
String suggestionZoneId =
"Europe/London".equals(currentZoneId) ? "Europe/Paris" : "Europe/London";
TelephonyTimeZoneSuggestion zoneSlotIndex1Suggestion =
@@ -610,9 +610,9 @@ public class TimeZoneDetectorStrategyImplTest {
}
/**
* The {@link TimeZoneDetectorStrategyImpl.Callback} is left to detect whether changing the time
* zone is actually necessary. This test proves that the strategy doesn't assume it knows the
* current settings.
* The {@link TimeZoneDetectorStrategyImpl.Environment} is left to detect whether changing the
* time zone is actually necessary. This test proves that the strategy doesn't assume it knows
* the current settings.
*/
@Test
public void testTelephonySuggestionStrategyDoesNotAssumeCurrentSetting_autoTelephony() {
@@ -958,7 +958,7 @@ public class TimeZoneDetectorStrategyImplTest {
return builder.build();
}
static class FakeCallback implements TimeZoneDetectorStrategyImpl.Callback {
static class FakeEnvironment implements TimeZoneDetectorStrategyImpl.Environment {
private final TestState<ConfigurationInternal> mConfigurationInternal = new TestState<>();
private final TestState<String> mTimeZoneId = new TestState<>();
@@ -1051,12 +1051,12 @@ public class TimeZoneDetectorStrategyImplTest {
private class Script {
Script initializeConfig(ConfigurationInternal configuration) {
mFakeCallback.initializeConfig(configuration);
mFakeEnvironment.initializeConfig(configuration);
return this;
}
Script initializeTimeZoneSetting(String zoneId) {
mFakeCallback.initializeTimeZoneSetting(zoneId);
mFakeEnvironment.initializeTimeZoneSetting(zoneId);
return this;
}
@@ -1084,7 +1084,7 @@ public class TimeZoneDetectorStrategyImplTest {
Script simulateManualTimeZoneSuggestion(
@UserIdInt int userId, ManualTimeZoneSuggestion manualTimeZoneSuggestion,
boolean expectedResult) {
mFakeCallback.assertKnownUser(userId);
mFakeEnvironment.assertKnownUser(userId);
boolean actualResult = mTimeZoneDetectorStrategy.suggestManualTimeZone(
userId, manualTimeZoneSuggestion);
assertEquals(expectedResult, actualResult);
@@ -1104,26 +1104,26 @@ public class TimeZoneDetectorStrategyImplTest {
* state was last reset.
*/
Script verifyTimeZoneNotChanged() {
mFakeCallback.assertTimeZoneNotChanged();
mFakeEnvironment.assertTimeZoneNotChanged();
return this;
}
/** Verifies the device's time zone has been set and clears change tracking history. */
Script verifyTimeZoneChangedAndReset(String zoneId) {
mFakeCallback.assertTimeZoneChangedTo(zoneId);
mFakeCallback.commitAllChanges();
mFakeEnvironment.assertTimeZoneChangedTo(zoneId);
mFakeEnvironment.commitAllChanges();
return this;
}
Script verifyTimeZoneChangedAndReset(ManualTimeZoneSuggestion suggestion) {
mFakeCallback.assertTimeZoneChangedTo(suggestion.getZoneId());
mFakeCallback.commitAllChanges();
mFakeEnvironment.assertTimeZoneChangedTo(suggestion.getZoneId());
mFakeEnvironment.commitAllChanges();
return this;
}
Script verifyTimeZoneChangedAndReset(TelephonyTimeZoneSuggestion suggestion) {
mFakeCallback.assertTimeZoneChangedTo(suggestion.getZoneId());
mFakeCallback.commitAllChanges();
mFakeEnvironment.assertTimeZoneChangedTo(suggestion.getZoneId());
mFakeEnvironment.commitAllChanges();
return this;
}
@@ -1131,9 +1131,9 @@ public class TimeZoneDetectorStrategyImplTest {
* Verifies that the configuration has been changed to the expected value.
*/
Script verifyConfigurationChangedAndReset(ConfigurationInternal expected) {
mFakeCallback.mConfigurationInternal.assertHasBeenSet();
assertEquals(expected, mFakeCallback.mConfigurationInternal.getLatest());
mFakeCallback.commitAllChanges();
mFakeEnvironment.mConfigurationInternal.assertHasBeenSet();
assertEquals(expected, mFakeEnvironment.mConfigurationInternal.getLatest());
mFakeEnvironment.commitAllChanges();
// Also confirm the listener triggered.
mMockConfigChangeListener.verifyOnChangeCalled();
@@ -1146,7 +1146,7 @@ public class TimeZoneDetectorStrategyImplTest {
* {@link TimeZoneConfiguration} have been changed.
*/
Script verifyConfigurationNotChanged() {
mFakeCallback.mConfigurationInternal.assertHasNotBeenSet();
mFakeEnvironment.mConfigurationInternal.assertHasNotBeenSet();
// Also confirm the listener did not trigger.
mMockConfigChangeListener.verifyOnChangeNotCalled();
@@ -1154,7 +1154,7 @@ public class TimeZoneDetectorStrategyImplTest {
}
Script resetConfigurationTracking() {
mFakeCallback.commitAllChanges();
mFakeEnvironment.commitAllChanges();
return this;
}
}