Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 6f2a077f authored by Neil Fuller's avatar Neil Fuller Committed by Android (Google) Code Review
Browse files

Merge "Various tidy ups / refactoring" into sc-dev

parents 7b971154 25dd7643
Loading
Loading
Loading
Loading
+5 −6
Original line number Diff line number Diff line
@@ -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());

+3 −3
Original line number Diff line number Diff line
@@ -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 =
+34 −33
Original line number Diff line number Diff line
@@ -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
+8 −8
Original line number Diff line number Diff line
@@ -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() {
+10 −10
Original line number Diff line number Diff line
@@ -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
Loading