Merge "Add UI for multiple admins on Headless"
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 41d465a..de7d65c 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -256,8 +256,8 @@
     <string name="stylus_textfield_handwriting">Stylus writing in textfields</string>
     <!-- Preference title for toggling whether stylus button presses are ignored [CHAR LIMIT=none] -->
     <string name="stylus_ignore_button">Ignore all stylus button presses</string>
-    <!-- Name shown in a USI stylus header in device details page [CHAR LIMIT=60] -->
-    <string name="stylus_usi_header_title">USI stylus</string>
+    <!-- Name shown in the title of individual stylus preference in the connected devices page [CHAR LIMIT=60] -->
+    <string name="stylus_connected_devices_title">Stylus</string>
 
     <!-- Date & time settings screen title -->
     <string name="date_and_time">Date &amp; time</string>
@@ -428,6 +428,8 @@
     <string name="date_time_auto">Set time automatically</string>
     <!-- Date & time setting screen setting switch title: whether the time zone should be determined automatically [CHAR LIMIT=100]  -->
     <string name="zone_auto_title">Set automatically</string>
+    <!-- Date & time setting screen setting switch summary for non-telephony devices [CHAR LIMIT=100] -->
+    <string name="auto_zone_requires_location_summary">Location will be used for setting the time zone when this toggle is on</string>
     <!-- Date & time setting screen setting option summary text for the automatic 24 hour setting checkbox [CHAR LIMIT=100] -->
     <string name="date_time_24hour_auto">Use locale default</string>
     <!-- Date & time setting screen setting check box title -->
@@ -2992,6 +2994,16 @@
 
     <!-- [CHAR LIMIT=60] Date&Time settings screen, toggle button title -->
     <string name="location_time_zone_detection_toggle_title">Use location</string>
+    <!-- [CHAR LIMIT=50] Date&Time settings screen, title of the dialog when AutoTimeZone is degraded -->
+    <string name="location_time_zone_detection_status_title">Cannot set the time zone automatically</string>
+    <!-- Date&Time settings screen, summary of the dialog when AutoTimeZone is degraded by settings-->
+    <string name="location_time_zone_detection_status_summary_degraded_by_settings" />
+    <!-- [CHAR LIMIT=60] Date&Time settings screen, summary of the dialog when AutoTimeZone is blocked by settings -->
+    <string name="location_time_zone_detection_status_summary_blocked_by_settings">Location or Location Services are off</string>
+    <!-- Date&Time settings screen, summary of the dialog when AutoTimeZone is blocked by the environment-->
+    <string name="location_time_zone_detection_status_summary_blocked_by_environment" />
+    <!-- Date&Time settings screen, summary of the dialog when AutoTimeZone is temporarily unavailable-->
+    <string name="location_time_zone_detection_status_summary_temporarily_unavailable" />
     <!-- [CHAR LIMIT=60] Date&Time settings screen, title of the dialog shown when user tries to
          enable GeoTZ when Location toggle is off. -->
     <string name="location_time_zone_detection_location_is_off_dialog_title">Device location needed</string>
@@ -3001,6 +3013,8 @@
     <!-- [CHAR LIMIT=30] Date&Time settings screen, button on a dialog shown when user tries to
     enable GeoTZ, but Location toggle is off, which leads to Location settings page. -->
     <string name="location_time_zone_detection_location_is_off_dialog_ok_button">Location settings</string>
+    <!-- [CHAR LIMIT=30] Date&Time settings screen, button on a dialog shown when the LTZP needs to be fixed -->
+    <string name="location_time_zone_provider_fix_dialog_ok_button">Fix this</string>
     <!-- [CHAR LIMIT=30] Date&Time settings screen, button on a dialog shown when user tries to
      enable GeoTZ, but Location toggle is off, which closes the dialog. -->
     <string name="location_time_zone_detection_location_is_off_dialog_cancel_button">Cancel</string>
diff --git a/res/xml/date_time_prefs.xml b/res/xml/date_time_prefs.xml
index e3d0a7e..593c428 100644
--- a/res/xml/date_time_prefs.xml
+++ b/res/xml/date_time_prefs.xml
@@ -47,6 +47,11 @@
             android:title="@string/zone_auto_title"
             settings:userRestriction="no_config_date_time"/>
 
+        <com.android.settingslib.widget.BannerMessagePreference
+            android:key="location_time_zone_detection_status"
+            android:title="@string/location_time_zone_detection_status_title"
+            settings:controller="com.android.settings.datetime.LocationProviderStatusPreferenceController"/>
+
         <!-- This preference gets removed if location-based time zone detection is not supported -->
         <SwitchPreference
             android:key="location_time_zone_detection"
diff --git a/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java b/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java
index 61195c9..0d51ebe 100644
--- a/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java
+++ b/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java
@@ -17,6 +17,9 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.hardware.input.InputManager;
+import android.util.FeatureFlagUtils;
+import android.view.InputDevice;
 
 import androidx.annotation.VisibleForTesting;
 import androidx.preference.Preference;
@@ -26,6 +29,7 @@
 import com.android.settings.bluetooth.BluetoothDeviceUpdater;
 import com.android.settings.bluetooth.ConnectedBluetoothDeviceUpdater;
 import com.android.settings.connecteddevice.dock.DockUpdater;
+import com.android.settings.connecteddevice.stylus.StylusDeviceUpdater;
 import com.android.settings.connecteddevice.usb.ConnectedUsbDeviceUpdater;
 import com.android.settings.core.BasePreferenceController;
 import com.android.settings.core.PreferenceControllerMixin;
@@ -51,11 +55,14 @@
     private BluetoothDeviceUpdater mBluetoothDeviceUpdater;
     private ConnectedUsbDeviceUpdater mConnectedUsbDeviceUpdater;
     private DockUpdater mConnectedDockUpdater;
+    private StylusDeviceUpdater mStylusDeviceUpdater;
     private final PackageManager mPackageManager;
+    private final InputManager mInputManager;
 
     public ConnectedDeviceGroupController(Context context) {
         super(context, KEY);
         mPackageManager = context.getPackageManager();
+        mInputManager = context.getSystemService(InputManager.class);
     }
 
     @Override
@@ -69,7 +76,13 @@
             mConnectedUsbDeviceUpdater.registerCallback();
         }
 
-        mConnectedDockUpdater.registerCallback();
+        if (mConnectedDockUpdater != null) {
+            mConnectedDockUpdater.registerCallback();
+        }
+
+        if (mStylusDeviceUpdater != null) {
+            mStylusDeviceUpdater.registerCallback();
+        }
     }
 
     @Override
@@ -82,7 +95,13 @@
             mConnectedUsbDeviceUpdater.unregisterCallback();
         }
 
-        mConnectedDockUpdater.unregisterCallback();
+        if (mConnectedDockUpdater != null) {
+            mConnectedDockUpdater.unregisterCallback();
+        }
+
+        if (mStylusDeviceUpdater != null) {
+            mStylusDeviceUpdater.unregisterCallback();
+        }
     }
 
     @Override
@@ -103,8 +122,15 @@
                 mConnectedUsbDeviceUpdater.initUsbPreference(context);
             }
 
-            mConnectedDockUpdater.setPreferenceContext(context);
-            mConnectedDockUpdater.forceUpdate();
+            if (mConnectedDockUpdater != null) {
+                mConnectedDockUpdater.setPreferenceContext(context);
+                mConnectedDockUpdater.forceUpdate();
+            }
+
+            if (mStylusDeviceUpdater != null) {
+                mStylusDeviceUpdater.setPreferenceContext(context);
+                mStylusDeviceUpdater.forceUpdate();
+            }
         }
     }
 
@@ -112,6 +138,7 @@
     public int getAvailabilityStatus() {
         return (hasBluetoothFeature()
                 || hasUsbFeature()
+                || hasUsiStylusFeature()
                 || mConnectedDockUpdater != null)
                 ? AVAILABLE_UNSEARCHABLE
                 : UNSUPPORTED_ON_DEVICE;
@@ -141,11 +168,13 @@
     @VisibleForTesting
     void init(BluetoothDeviceUpdater bluetoothDeviceUpdater,
             ConnectedUsbDeviceUpdater connectedUsbDeviceUpdater,
-            DockUpdater connectedDockUpdater) {
+            DockUpdater connectedDockUpdater,
+            StylusDeviceUpdater connectedStylusDeviceUpdater) {
 
         mBluetoothDeviceUpdater = bluetoothDeviceUpdater;
         mConnectedUsbDeviceUpdater = connectedUsbDeviceUpdater;
         mConnectedDockUpdater = connectedDockUpdater;
+        mStylusDeviceUpdater = connectedStylusDeviceUpdater;
     }
 
     public void init(DashboardFragment fragment) {
@@ -160,7 +189,10 @@
                 hasUsbFeature()
                         ? new ConnectedUsbDeviceUpdater(context, fragment, this)
                         : null,
-                connectedDockUpdater);
+                connectedDockUpdater,
+                hasUsiStylusFeature()
+                        ? new StylusDeviceUpdater(context, fragment, this)
+                        : null);
     }
 
     private boolean hasBluetoothFeature() {
@@ -171,4 +203,21 @@
         return mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY)
                 || mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
     }
+
+    private boolean hasUsiStylusFeature() {
+        if (!FeatureFlagUtils.isEnabled(mContext,
+                FeatureFlagUtils.SETTINGS_SHOW_STYLUS_PREFERENCES)) {
+            return false;
+        }
+
+        for (int deviceId : mInputManager.getInputDeviceIds()) {
+            InputDevice device = mInputManager.getInputDevice(deviceId);
+            if (device != null
+                    && device.supportsSource(InputDevice.SOURCE_STYLUS)
+                    && !device.isExternal()) {
+                return true;
+            }
+        }
+        return false;
+    }
 }
diff --git a/src/com/android/settings/connecteddevice/stylus/StylusDeviceUpdater.java b/src/com/android/settings/connecteddevice/stylus/StylusDeviceUpdater.java
new file mode 100644
index 0000000..575c526
--- /dev/null
+++ b/src/com/android/settings/connecteddevice/stylus/StylusDeviceUpdater.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.connecteddevice.stylus;
+
+import android.content.Context;
+import android.hardware.BatteryState;
+import android.hardware.input.InputManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.SystemClock;
+import android.util.Log;
+import android.view.InputDevice;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+
+import com.android.settings.R;
+import com.android.settings.connecteddevice.DevicePreferenceCallback;
+import com.android.settings.core.SubSettingLauncher;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Controller to maintain available USI stylus devices. Listens to bluetooth
+ * stylus connection to determine whether to show the USI preference.
+ */
+public class StylusDeviceUpdater implements InputManager.InputDeviceListener,
+        InputManager.InputDeviceBatteryListener {
+
+    private static final String TAG = "StylusDeviceUpdater";
+    private static final String PREF_KEY = "stylus_usi_device";
+    private static final String INPUT_ID_ARG = "device_input_id";
+
+    private final DevicePreferenceCallback mDevicePreferenceCallback;
+    private final List<Integer> mRegisteredBatteryCallbackIds;
+    private final DashboardFragment mFragment;
+    private final InputManager mInputManager;
+    private final MetricsFeatureProvider mMetricsFeatureProvider;
+
+    private long mLastUsiSeenTime = 0;
+    private Context mContext;
+
+    @VisibleForTesting
+    Integer mLastDetectedUsiId;
+
+    @VisibleForTesting
+    Preference mUsiPreference;
+
+
+    public StylusDeviceUpdater(Context context, DashboardFragment fragment,
+            DevicePreferenceCallback devicePreferenceCallback) {
+        mFragment = fragment;
+        mRegisteredBatteryCallbackIds = new ArrayList<>();
+        mDevicePreferenceCallback = devicePreferenceCallback;
+        mMetricsFeatureProvider = FeatureFactory.getFactory(context).getMetricsFeatureProvider();
+        mContext = context;
+        mInputManager = context.getSystemService(InputManager.class);
+
+    }
+
+    /**
+     * Register the stylus event callback and update the list
+     */
+    public void registerCallback() {
+        for (int deviceId : mInputManager.getInputDeviceIds()) {
+            onInputDeviceAdded(deviceId);
+        }
+        mInputManager.registerInputDeviceListener(this, new Handler(Looper.myLooper()));
+        forceUpdate();
+    }
+
+    /**
+     * Unregister the stylus event callback
+     */
+    public void unregisterCallback() {
+        for (int deviceId : mRegisteredBatteryCallbackIds) {
+            mInputManager.removeInputDeviceBatteryListener(deviceId, this);
+        }
+        mInputManager.unregisterInputDeviceListener(this);
+    }
+
+    @Override
+    public void onInputDeviceAdded(int deviceId) {
+        InputDevice inputDevice = mInputManager.getInputDevice(deviceId);
+        if (inputDevice.supportsSource(InputDevice.SOURCE_STYLUS)
+                && !inputDevice.isExternal()) {
+            try {
+                mInputManager.addInputDeviceBatteryListener(deviceId,
+                        mContext.getMainExecutor(), this);
+                mRegisteredBatteryCallbackIds.add(deviceId);
+            } catch (IllegalArgumentException e) {
+                Log.e(TAG, e.getMessage());
+            }
+        }
+        forceUpdate();
+    }
+
+    @Override
+    public void onInputDeviceRemoved(int deviceId) {
+        Log.d(TAG, String.format("Input device removed %d", deviceId));
+        forceUpdate();
+    }
+
+    @Override
+    public void onInputDeviceChanged(int deviceId) {
+        if (mInputManager.getInputDevice(deviceId).supportsSource(InputDevice.SOURCE_STYLUS)) {
+            forceUpdate();
+        }
+    }
+
+
+    @Override
+    public void onBatteryStateChanged(int deviceId, long eventTimeMillis,
+            @NonNull BatteryState batteryState) {
+        if (batteryState.isPresent()) {
+            mLastUsiSeenTime = eventTimeMillis;
+            mLastDetectedUsiId = deviceId;
+        } else {
+            mLastUsiSeenTime = -1;
+            mLastDetectedUsiId = null;
+        }
+        forceUpdate();
+    }
+
+    /**
+     * Set the context to generate the {@link Preference}, so it could get the correct theme.
+     */
+    public void setPreferenceContext(Context context) {
+        mContext = context;
+    }
+
+    /**
+     * Force update to add or remove stylus preference
+     */
+    public void forceUpdate() {
+        if (shouldShowUsiPreference()) {
+            addOrUpdateUsiPreference();
+        } else {
+            removeUsiPreference();
+        }
+    }
+
+    private synchronized void addOrUpdateUsiPreference() {
+        if (mUsiPreference == null) {
+            mUsiPreference = new Preference(mContext);
+            mDevicePreferenceCallback.onDeviceAdded(mUsiPreference);
+        }
+        mUsiPreference.setKey(PREF_KEY);
+        mUsiPreference.setTitle(R.string.stylus_connected_devices_title);
+        // TODO(b/250909304): pending actual icon visD
+        mUsiPreference.setIcon(R.drawable.circle);
+        mUsiPreference.setOnPreferenceClickListener((Preference p) -> {
+            mMetricsFeatureProvider.logClickedPreference(p, mFragment.getMetricsCategory());
+            launchDeviceDetails();
+            return true;
+        });
+    }
+
+    private synchronized void removeUsiPreference() {
+        if (mUsiPreference != null) {
+            mDevicePreferenceCallback.onDeviceRemoved(mUsiPreference);
+            mUsiPreference = null;
+        }
+    }
+
+    private boolean shouldShowUsiPreference() {
+        return isUsiConnectionValid() && !hasConnectedBluetoothStylusDevice();
+    }
+
+    @VisibleForTesting
+    public Preference getPreference() {
+        return mUsiPreference;
+    }
+
+    @VisibleForTesting
+    boolean hasConnectedBluetoothStylusDevice() {
+        for (int deviceId : mInputManager.getInputDeviceIds()) {
+            InputDevice device = mInputManager.getInputDevice(deviceId);
+            if (device.supportsSource(InputDevice.SOURCE_STYLUS)
+                    && mInputManager.getInputDeviceBluetoothAddress(deviceId) != null) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    @VisibleForTesting
+    boolean isUsiConnectionValid() {
+        // battery listener uses uptimeMillis as its eventTime
+        long currentTime = SystemClock.uptimeMillis();
+        long usiValidityDuration = 60 * 60 * 1000; // 1 hour
+        return mLastUsiSeenTime > 0 && currentTime - usiValidityDuration <= mLastUsiSeenTime;
+    }
+
+    private void launchDeviceDetails() {
+        final Bundle args = new Bundle();
+        args.putInt(INPUT_ID_ARG, mLastDetectedUsiId);
+
+        new SubSettingLauncher(mFragment.getContext())
+                .setDestination(StylusUsiDetailsFragment.class.getName())
+                .setArguments(args)
+                .setSourceMetricsCategory(mFragment.getMetricsCategory()).launch();
+    }
+}
diff --git a/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderController.java b/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderController.java
index 826cc1f..13d7b57 100644
--- a/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderController.java
+++ b/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderController.java
@@ -66,7 +66,7 @@
         mHeaderPreference = screen.findPreference(getPreferenceKey());
         View view = mHeaderPreference.findViewById(R.id.entity_header);
         TextView titleView = view.findViewById(R.id.entity_header_title);
-        titleView.setText(R.string.stylus_usi_header_title);
+        titleView.setText(R.string.stylus_connected_devices_title);
 
         ImageView iconView = mHeaderPreference.findViewById(R.id.entity_header_icon);
         if (iconView != null) {
diff --git a/src/com/android/settings/core/gateway/SettingsGateway.java b/src/com/android/settings/core/gateway/SettingsGateway.java
index fa72fba..db23c43 100644
--- a/src/com/android/settings/core/gateway/SettingsGateway.java
+++ b/src/com/android/settings/core/gateway/SettingsGateway.java
@@ -83,6 +83,7 @@
 import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
 import com.android.settings.connecteddevice.NfcAndPaymentFragment;
 import com.android.settings.connecteddevice.PreviouslyConnectedDeviceDashboardFragment;
+import com.android.settings.connecteddevice.stylus.StylusUsiDetailsFragment;
 import com.android.settings.connecteddevice.usb.UsbDetailsFragment;
 import com.android.settings.datausage.DataSaverSummary;
 import com.android.settings.datausage.DataUsageList;
@@ -338,6 +339,7 @@
             BluetoothDeviceDetailsFragment.class.getName(),
             BluetoothBroadcastDialog.class.getName(),
             BluetoothFindBroadcastsFragment.class.getName(),
+            StylusUsiDetailsFragment.class.getName(),
             DataUsageList.class.getName(),
             ToggleBackupSettingFragment.class.getName(),
             PreviouslyConnectedDeviceDashboardFragment.class.getName(),
diff --git a/src/com/android/settings/datetime/AutoTimeZonePreferenceController.java b/src/com/android/settings/datetime/AutoTimeZonePreferenceController.java
index 98629b4..a4d745b 100644
--- a/src/com/android/settings/datetime/AutoTimeZonePreferenceController.java
+++ b/src/com/android/settings/datetime/AutoTimeZonePreferenceController.java
@@ -29,8 +29,10 @@
 
 import androidx.annotation.VisibleForTesting;
 import androidx.preference.Preference;
+import androidx.preference.PreferenceScreen;
 import androidx.preference.SwitchPreference;
 
+import com.android.settings.R;
 import com.android.settings.core.PreferenceControllerMixin;
 import com.android.settingslib.core.AbstractPreferenceController;
 
@@ -99,6 +101,25 @@
         return result;
     }
 
+    @Override
+    public CharSequence getSummary() {
+        // If auto time zone cannot enable telephony fallback and is capable of location, then auto
+        // time zone must use location.
+        if (LocationProviderStatusPreferenceController.hasLocationTimeZoneNoTelephonyFallback(
+                mTimeManager.getTimeZoneCapabilitiesAndConfig().getDetectorStatus())) {
+            return mContext.getResources().getString(R.string.auto_zone_requires_location_summary);
+        }
+        // If the user has a dedicated toggle to control location use, the summary can
+        // be empty because the use of location is explicit.
+        return "";
+    }
+
+    @Override
+    public void displayPreference(PreferenceScreen screen) {
+        super.displayPreference(screen);
+        refreshSummary(screen.findPreference(getPreferenceKey()));
+    }
+
     @VisibleForTesting
     boolean isEnabled() {
         TimeZoneConfiguration config = getTimeZoneCapabilitiesAndConfig().getConfiguration();
diff --git a/src/com/android/settings/datetime/LocationProviderStatusPreferenceController.java b/src/com/android/settings/datetime/LocationProviderStatusPreferenceController.java
new file mode 100644
index 0000000..9380f13
--- /dev/null
+++ b/src/com/android/settings/datetime/LocationProviderStatusPreferenceController.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.settings.datetime;
+
+import android.app.time.DetectorStatusTypes;
+import android.app.time.LocationTimeZoneAlgorithmStatus;
+import android.app.time.TelephonyTimeZoneAlgorithmStatus;
+import android.app.time.TimeManager;
+import android.app.time.TimeZoneDetectorStatus;
+import android.content.Context;
+import android.location.LocationManager;
+import android.service.timezone.TimeZoneProviderStatus;
+import android.text.TextUtils;
+
+import androidx.annotation.Nullable;
+import androidx.preference.PreferenceScreen;
+
+import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.core.SubSettingLauncher;
+import com.android.settings.location.LocationSettings;
+import com.android.settingslib.widget.BannerMessagePreference;
+
+import java.util.concurrent.Executor;
+
+/**
+ * The controller for the "location time zone detection" entry in the Location settings
+ * screen.
+ */
+public class LocationProviderStatusPreferenceController
+        extends BasePreferenceController implements TimeManager.TimeZoneDetectorListener {
+    private final TimeManager mTimeManager;
+    private final LocationManager mLocationManager;
+
+    private BannerMessagePreference mPreference = null;
+
+    public LocationProviderStatusPreferenceController(Context context, String preferenceKey) {
+        super(context, preferenceKey);
+        mTimeManager = context.getSystemService(TimeManager.class);
+        mLocationManager = context.getSystemService(LocationManager.class);
+
+        Executor mainExecutor = context.getMainExecutor();
+        mTimeManager.addTimeZoneDetectorListener(mainExecutor, this);
+    }
+
+    @Override
+    public void displayPreference(PreferenceScreen screen) {
+        super.displayPreference(screen);
+        mPreference = screen.findPreference(getPreferenceKey());
+        assert mPreference != null;
+        mPreference
+                .setPositiveButtonText(
+                        R.string.location_time_zone_provider_fix_dialog_ok_button)
+                .setPositiveButtonOnClickListener(v -> launchLocationSettings());
+    }
+
+    @Override
+    public int getAvailabilityStatus() {
+        // Checks that the summary is non-empty as most status strings are optional. If a status
+        // string is empty, we ignore the status.
+        if (!TextUtils.isEmpty(getSummary())) {
+            return AVAILABLE_UNSEARCHABLE;
+        }
+        return CONDITIONALLY_UNAVAILABLE;
+    }
+
+    private void launchLocationSettings() {
+        new SubSettingLauncher(mContext)
+                .setDestination(LocationSettings.class.getName())
+                .setSourceMetricsCategory(getMetricsCategory())
+                .launch();
+    }
+
+    // Android has up to two location time zone providers (LTZPs) which can
+    // (optionally) report their status along several dimensions. Typically there is
+    // only one LTZP on a device, the primary. The UI here only reports status for one
+    // LTZP. This UI logic prioritizes the primary if there is a "bad" status for both.
+    @Nullable
+    private TimeZoneProviderStatus getLtzpStatus() {
+        LocationTimeZoneAlgorithmStatus status =
+                mTimeManager.getTimeZoneCapabilitiesAndConfig().getDetectorStatus()
+                        .getLocationTimeZoneAlgorithmStatus();
+        TimeZoneProviderStatus primary = status.getPrimaryProviderReportedStatus();
+        TimeZoneProviderStatus secondary = status.getSecondaryProviderReportedStatus();
+        if (primary == null && secondary == null) {
+            return null;
+        }
+
+        if (primary == null) {
+            return secondary;
+        } else if (secondary == null) {
+            return primary;
+        }
+
+        if (status.getPrimaryProviderStatus()
+                != LocationTimeZoneAlgorithmStatus.PROVIDER_STATUS_IS_CERTAIN) {
+            return secondary;
+        }
+
+        return primary;
+    }
+
+    @Override
+    public void onChange() {
+        if (mPreference != null) {
+            mPreference.setVisible(getAvailabilityStatus() == AVAILABLE_UNSEARCHABLE);
+            refreshSummary(mPreference);
+        }
+    }
+
+    @Override
+    public CharSequence getSummary() {
+        boolean locationEnabled = mLocationManager.isLocationEnabled();
+        final TimeZoneDetectorStatus detectorStatus =
+                mTimeManager.getTimeZoneCapabilitiesAndConfig().getDetectorStatus();
+
+        if (!locationEnabled && hasLocationTimeZoneNoTelephonyFallback(detectorStatus)) {
+            return mContext.getResources().getString(
+                    R.string.location_time_zone_detection_status_summary_blocked_by_settings);
+        }
+
+        TimeZoneProviderStatus ltzpStatus = getLtzpStatus();
+        if (ltzpStatus == null) {
+            return "";
+        }
+
+        int status = ltzpStatus.getLocationDetectionDependencyStatus();
+
+        if (status == TimeZoneProviderStatus.DEPENDENCY_STATUS_BLOCKED_BY_ENVIRONMENT) {
+            return mContext.getResources().getString(
+                    R.string.location_time_zone_detection_status_summary_blocked_by_environment);
+        }
+        if (status == TimeZoneProviderStatus.DEPENDENCY_STATUS_DEGRADED_BY_SETTINGS) {
+            return mContext.getResources().getString(
+                    R.string.location_time_zone_detection_status_summary_degraded_by_settings);
+        }
+        if (status == TimeZoneProviderStatus.DEPENDENCY_STATUS_TEMPORARILY_UNAVAILABLE) {
+            return mContext.getResources().getString(
+                    R.string.location_time_zone_detection_status_summary_temporarily_unavailable);
+        }
+        if (status == TimeZoneProviderStatus.DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS) {
+            return mContext.getResources().getString(
+                    R.string.location_time_zone_detection_status_summary_blocked_by_settings);
+        }
+
+        return "";
+    }
+
+    /** package */
+    static boolean hasLocationTimeZoneNoTelephonyFallback(TimeZoneDetectorStatus detectorStatus) {
+        final LocationTimeZoneAlgorithmStatus locationStatus =
+                detectorStatus.getLocationTimeZoneAlgorithmStatus();
+        final TelephonyTimeZoneAlgorithmStatus telephonyStatus =
+                detectorStatus.getTelephonyTimeZoneAlgorithmStatus();
+        return telephonyStatus.getAlgorithmStatus()
+                == DetectorStatusTypes.DETECTION_ALGORITHM_STATUS_NOT_SUPPORTED
+                && locationStatus.getStatus()
+                != DetectorStatusTypes.DETECTION_ALGORITHM_STATUS_NOT_SUPPORTED;
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/connecteddevice/ConnectedDeviceGroupControllerTest.java b/tests/robotests/src/com/android/settings/connecteddevice/ConnectedDeviceGroupControllerTest.java
index 40e6494..a35ef45 100644
--- a/tests/robotests/src/com/android/settings/connecteddevice/ConnectedDeviceGroupControllerTest.java
+++ b/tests/robotests/src/com/android/settings/connecteddevice/ConnectedDeviceGroupControllerTest.java
@@ -29,6 +29,9 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.hardware.input.InputManager;
+import android.util.FeatureFlagUtils;
+import android.view.InputDevice;
 
 import androidx.preference.Preference;
 import androidx.preference.PreferenceGroup;
@@ -37,6 +40,7 @@
 
 import com.android.settings.bluetooth.ConnectedBluetoothDeviceUpdater;
 import com.android.settings.connecteddevice.dock.DockUpdater;
+import com.android.settings.connecteddevice.stylus.StylusDeviceUpdater;
 import com.android.settings.connecteddevice.usb.ConnectedUsbDeviceUpdater;
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
@@ -68,9 +72,13 @@
     @Mock
     private DockUpdater mConnectedDockUpdater;
     @Mock
+    private StylusDeviceUpdater mStylusDeviceUpdater;
+    @Mock
     private PreferenceScreen mPreferenceScreen;
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private PreferenceManager mPreferenceManager;
+    @Mock
+    private InputManager mInputManager;
 
     private ShadowApplicationPackageManager mPackageManager;
     private PreferenceGroup mPreferenceGroup;
@@ -82,7 +90,7 @@
     public void setUp() {
         MockitoAnnotations.initMocks(this);
 
-        mContext = RuntimeEnvironment.application;
+        mContext = spy(RuntimeEnvironment.application);
         mPreference = new Preference(mContext);
         mPreference.setKey(PREFERENCE_KEY_1);
         mPackageManager = (ShadowApplicationPackageManager) Shadows.shadowOf(
@@ -91,11 +99,16 @@
         when(mPreferenceGroup.getPreferenceManager()).thenReturn(mPreferenceManager);
         doReturn(mContext).when(mDashboardFragment).getContext();
         mPackageManager.setSystemFeature(PackageManager.FEATURE_BLUETOOTH, true);
+        when(mContext.getSystemService(InputManager.class)).thenReturn(mInputManager);
+        when(mInputManager.getInputDeviceIds()).thenReturn(new int[]{});
 
         mConnectedDeviceGroupController = new ConnectedDeviceGroupController(mContext);
         mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
-                mConnectedUsbDeviceUpdater, mConnectedDockUpdater);
+                mConnectedUsbDeviceUpdater, mConnectedDockUpdater, mStylusDeviceUpdater);
         mConnectedDeviceGroupController.mPreferenceGroup = mPreferenceGroup;
+
+        FeatureFlagUtils.setEnabled(mContext, FeatureFlagUtils.SETTINGS_SHOW_STYLUS_PREFERENCES,
+                true);
     }
 
     @Test
@@ -146,6 +159,7 @@
         verify(mConnectedUsbDeviceUpdater).registerCallback();
         verify(mConnectedDockUpdater).registerCallback();
         verify(mConnectedBluetoothDeviceUpdater).refreshPreference();
+        verify(mStylusDeviceUpdater).registerCallback();
     }
 
     @Test
@@ -155,6 +169,7 @@
         verify(mConnectedBluetoothDeviceUpdater).unregisterCallback();
         verify(mConnectedUsbDeviceUpdater).unregisterCallback();
         verify(mConnectedDockUpdater).unregisterCallback();
+        verify(mStylusDeviceUpdater).unregisterCallback();
     }
 
     @Test
@@ -163,7 +178,7 @@
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_ACCESSORY, false);
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_HOST, false);
         mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
-                mConnectedUsbDeviceUpdater, null);
+                mConnectedUsbDeviceUpdater, null, null);
 
         assertThat(mConnectedDeviceGroupController.getAvailabilityStatus()).isEqualTo(
                 UNSUPPORTED_ON_DEVICE);
@@ -175,7 +190,7 @@
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_ACCESSORY, false);
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_HOST, false);
         mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
-                mConnectedUsbDeviceUpdater, null);
+                mConnectedUsbDeviceUpdater, null, null);
 
         assertThat(mConnectedDeviceGroupController.getAvailabilityStatus()).isEqualTo(
                 AVAILABLE_UNSEARCHABLE);
@@ -187,7 +202,7 @@
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_ACCESSORY, false);
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_HOST, true);
         mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
-                mConnectedUsbDeviceUpdater, null);
+                mConnectedUsbDeviceUpdater, null, null);
 
         assertThat(mConnectedDeviceGroupController.getAvailabilityStatus()).isEqualTo(
                 AVAILABLE_UNSEARCHABLE);
@@ -199,7 +214,40 @@
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_ACCESSORY, false);
         mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_HOST, false);
         mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
-                mConnectedUsbDeviceUpdater, mConnectedDockUpdater);
+                mConnectedUsbDeviceUpdater, mConnectedDockUpdater, null);
+
+        assertThat(mConnectedDeviceGroupController.getAvailabilityStatus()).isEqualTo(
+                AVAILABLE_UNSEARCHABLE);
+    }
+
+
+    @Test
+    public void getAvailabilityStatus_noUsiStylusFeature_returnUnSupported() {
+        mPackageManager.setSystemFeature(PackageManager.FEATURE_BLUETOOTH, false);
+        mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_ACCESSORY, false);
+        mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_HOST, false);
+        when(mInputManager.getInputDeviceIds()).thenReturn(new int[]{0});
+        when(mInputManager.getInputDevice(0)).thenReturn(new InputDevice.Builder().setSources(
+                InputDevice.SOURCE_DPAD).setExternal(false).build());
+
+        mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
+                mConnectedUsbDeviceUpdater, null, mStylusDeviceUpdater);
+
+        assertThat(mConnectedDeviceGroupController.getAvailabilityStatus()).isEqualTo(
+                UNSUPPORTED_ON_DEVICE);
+    }
+
+    @Test
+    public void getAvailabilityStatus_haveUsiStylusFeature_returnSupported() {
+        mPackageManager.setSystemFeature(PackageManager.FEATURE_BLUETOOTH, false);
+        mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_ACCESSORY, false);
+        mPackageManager.setSystemFeature(PackageManager.FEATURE_USB_HOST, false);
+        when(mInputManager.getInputDeviceIds()).thenReturn(new int[]{0});
+        when(mInputManager.getInputDevice(0)).thenReturn(new InputDevice.Builder().setSources(
+                InputDevice.SOURCE_STYLUS).setExternal(false).build());
+
+        mConnectedDeviceGroupController.init(mConnectedBluetoothDeviceUpdater,
+                mConnectedUsbDeviceUpdater, mConnectedDockUpdater, mStylusDeviceUpdater);
 
         assertThat(mConnectedDeviceGroupController.getAvailabilityStatus()).isEqualTo(
                 AVAILABLE_UNSEARCHABLE);
diff --git a/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusDeviceUpdaterTest.java b/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusDeviceUpdaterTest.java
new file mode 100644
index 0000000..10f3727
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusDeviceUpdaterTest.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.connecteddevice.stylus;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.BatteryState;
+import android.hardware.input.InputManager;
+import android.os.SystemClock;
+import android.view.InputDevice;
+
+import com.android.settings.R;
+import com.android.settings.SettingsActivity;
+import com.android.settings.connecteddevice.DevicePreferenceCallback;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(RobolectricTestRunner.class)
+@Config(shadows = {ShadowBluetoothAdapter.class})
+public class StylusDeviceUpdaterTest {
+
+    private Context mContext;
+    private StylusDeviceUpdater mStylusDeviceUpdater;
+    private InputDevice mStylusDevice;
+    private InputDevice mOtherDevice;
+
+    @Mock
+    private SettingsActivity mSettingsActivity;
+    @Mock
+    private DashboardFragment mDashboardFragment;
+    @Mock
+    private DevicePreferenceCallback mDevicePreferenceCallback;
+    @Mock
+    private InputManager mInputManager;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        mContext = spy(RuntimeEnvironment.application);
+
+        doReturn(mContext).when(mDashboardFragment).getContext();
+        doReturn(mInputManager).when(mContext).getSystemService(InputManager.class);
+        doReturn(new int[]{}).when(mInputManager).getInputDeviceIds();
+
+        mStylusDeviceUpdater = spy(
+                new StylusDeviceUpdater(mContext, mDashboardFragment, mDevicePreferenceCallback));
+        mStylusDeviceUpdater.setPreferenceContext(mContext);
+
+        doReturn(new int[]{0, 1}).when(mInputManager).getInputDeviceIds();
+        mOtherDevice = new InputDevice.Builder().setId(0).setName("other").setSources(
+                InputDevice.SOURCE_DPAD).build();
+        doReturn(mOtherDevice).when(mInputManager).getInputDevice(0);
+        mStylusDevice = new InputDevice.Builder().setId(1).setName("Pen").setExternal(
+                false).setSources(
+                InputDevice.SOURCE_STYLUS).build();
+        doReturn(mStylusDevice).when(mInputManager).getInputDevice(1);
+    }
+
+    @Test
+    public void registerCallback_registersBatteryListener() {
+        mStylusDeviceUpdater.registerCallback();
+
+        verify(mInputManager, times(1)).addInputDeviceBatteryListener(eq(1), any(),
+                any());
+    }
+
+    @Test
+    public void registerCallback_registersInputDeviceListener() {
+        mStylusDeviceUpdater.registerCallback();
+
+        verify(mInputManager, times(1)).registerInputDeviceListener(eq(mStylusDeviceUpdater),
+                any());
+    }
+
+    @Test
+    public void onInputDeviceAdded_internalStylus_registersBatteryListener() {
+        mStylusDeviceUpdater.onInputDeviceAdded(1);
+
+        verify(mInputManager, times(1)).addInputDeviceBatteryListener(eq(1), any(),
+                any());
+    }
+
+    @Test
+    public void onInputDeviceAdded_nonStylus_doesNotRegisterBatteryListener() {
+        mStylusDeviceUpdater.onInputDeviceAdded(0);
+
+        verify(mInputManager, never()).addInputDeviceBatteryListener(eq(1), any(),
+                any());
+    }
+
+    @Test
+    public void click_usiPreference_launchUsiDetailsPage() {
+        doReturn(mSettingsActivity).when(mDashboardFragment).getContext();
+        doReturn(true).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+        mStylusDeviceUpdater.forceUpdate();
+        mStylusDeviceUpdater.mLastDetectedUsiId = 1;
+        final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
+
+        mStylusDeviceUpdater.mUsiPreference.performClick();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference.getTitle().toString()).isEqualTo(
+                mContext.getString(R.string.stylus_connected_devices_title));
+        verify(mSettingsActivity).startActivity(intentCaptor.capture());
+        assertThat(intentCaptor.getValue().getStringExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT))
+                .isEqualTo(StylusUsiDetailsFragment.class.getName());
+    }
+
+    @Test
+    public void forceUpdate_addsUsiPreference_validUsiDevice() {
+        doReturn(true).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+
+        mStylusDeviceUpdater.forceUpdate();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference).isNotNull();
+    }
+
+    @Test
+    public void forceUpdate_doesNotAddPreference_invalidUsiDevice() {
+        doReturn(false).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+
+        mStylusDeviceUpdater.forceUpdate();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference).isNull();
+    }
+
+    @Test
+    public void forceUpdate_removesUsiPreference_existingPreference_invalidUsiDevice() {
+        doReturn(true).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+
+        mStylusDeviceUpdater.forceUpdate();
+
+        doReturn(false).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        mStylusDeviceUpdater.forceUpdate();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference).isNull();
+    }
+
+    @Test
+    public void forceUpdate_doesNotAddUsiPreference_bluetoothStylusConnected() {
+        doReturn(true).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(true).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+
+        mStylusDeviceUpdater.forceUpdate();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference).isNull();
+    }
+
+    @Test
+    public void forceUpdate_addsUsiPreference_bluetoothStylusDisconnected() {
+        doReturn(true).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(true).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+        mStylusDeviceUpdater.forceUpdate();
+
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+        mStylusDeviceUpdater.forceUpdate();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference).isNotNull();
+    }
+
+    @Test
+    public void forceUpdate_removesUsiPreference_existingPreference_bluetoothStylusConnected() {
+        doReturn(true).when(mStylusDeviceUpdater).isUsiConnectionValid();
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+        mStylusDeviceUpdater.forceUpdate();
+        doReturn(true).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+
+        mStylusDeviceUpdater.forceUpdate();
+
+        assertThat(mStylusDeviceUpdater.mUsiPreference).isNull();
+    }
+
+    @Test
+    public void onBatteryStateChanged_detectsValidUsi() {
+        BatteryState batteryState = mock(BatteryState.class);
+        doReturn(true).when(batteryState).isPresent();
+        doReturn(0.5f).when(batteryState).getCapacity();
+
+        mStylusDeviceUpdater.onBatteryStateChanged(1, SystemClock.uptimeMillis(),
+                batteryState);
+
+        assertThat(mStylusDeviceUpdater.isUsiConnectionValid()).isTrue();
+    }
+
+    @Test
+    public void onBatteryStateChanged_detectsInvalidUsi_batteryNotPresent() {
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+        BatteryState batteryState = mock(BatteryState.class);
+        doReturn(false).when(batteryState).isPresent();
+
+        mStylusDeviceUpdater.onBatteryStateChanged(1, SystemClock.uptimeMillis(),
+                batteryState);
+
+        assertThat(mStylusDeviceUpdater.isUsiConnectionValid()).isFalse();
+    }
+
+    @Test
+    public void onBatteryStateChanged_ddetectsInvalidUsi_staleBatteryEventTime() {
+        doReturn(false).when(mStylusDeviceUpdater).hasConnectedBluetoothStylusDevice();
+        BatteryState batteryState = mock(BatteryState.class);
+        doReturn(true).when(batteryState).isPresent();
+        doReturn(0.5f).when(batteryState).getCapacity();
+
+        mStylusDeviceUpdater.onBatteryStateChanged(1, 0, batteryState);
+
+        assertThat(mStylusDeviceUpdater.isUsiConnectionValid()).isFalse();
+    }
+
+    @Test
+    public void detectsConnectedBluetoothStylus() {
+        InputDevice stylusDevice = new InputDevice.Builder().setId(1).setName("Pen").setSources(
+                        InputDevice.SOURCE_STYLUS)
+                .build();
+        doReturn(stylusDevice).when(mInputManager).getInputDevice(1);
+        doReturn("04:52:C7:0B:D8:3C").when(mInputManager).getInputDeviceBluetoothAddress(1);
+
+        assertThat(mStylusDeviceUpdater.hasConnectedBluetoothStylusDevice()).isTrue();
+    }
+
+    @Test
+    public void detectsDisconnectedBluetoothStylus() {
+        InputDevice stylusDevice = new InputDevice.Builder().setId(1).setName("Pen").setSources(
+                InputDevice.SOURCE_STYLUS).build();
+        doReturn(stylusDevice).when(mInputManager).getInputDevice(1);
+        doReturn(null).when(mInputManager).getInputDeviceBluetoothAddress(1);
+
+        assertThat(mStylusDeviceUpdater.hasConnectedBluetoothStylusDevice()).isFalse();
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderControllerTest.java b/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderControllerTest.java
index 27b1de5..3aad02e 100644
--- a/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderControllerTest.java
+++ b/tests/robotests/src/com/android/settings/connecteddevice/stylus/StylusUsiHeaderControllerTest.java
@@ -109,7 +109,7 @@
 
         assertThat(((TextView) mLayoutPreference.findViewById(
                 R.id.entity_header_title)).getText().toString()).isEqualTo(
-                mContext.getString(R.string.stylus_usi_header_title));
+                mContext.getString(R.string.stylus_connected_devices_title));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/datetime/AutoTimeZonePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/datetime/AutoTimeZonePreferenceControllerTest.java
index 61fca2c..41aca50 100644
--- a/tests/robotests/src/com/android/settings/datetime/AutoTimeZonePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/datetime/AutoTimeZonePreferenceControllerTest.java
@@ -16,6 +16,7 @@
 
 package com.android.settings.datetime;
 
+import static android.app.time.DetectorStatusTypes.DETECTION_ALGORITHM_STATUS_NOT_SUPPORTED;
 import static android.app.time.DetectorStatusTypes.DETECTION_ALGORITHM_STATUS_RUNNING;
 import static android.app.time.DetectorStatusTypes.DETECTOR_STATUS_RUNNING;
 import static android.app.time.LocationTimeZoneAlgorithmStatus.PROVIDER_STATUS_NOT_PRESENT;
@@ -36,10 +37,13 @@
 import android.app.time.TimeZoneConfiguration;
 import android.app.time.TimeZoneDetectorStatus;
 import android.content.Context;
+import android.location.LocationManager;
 import android.os.UserHandle;
 
 import androidx.preference.Preference;
 
+import com.android.settings.R;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -58,6 +62,8 @@
     private Preference mPreference;
     @Mock
     private TimeManager mTimeManager;
+    @Mock
+    private LocationManager mLocationManager;
 
     @Before
     public void setUp() {
@@ -67,6 +73,9 @@
         mPreference = new Preference(mContext);
 
         when(mContext.getSystemService(TimeManager.class)).thenReturn(mTimeManager);
+        when(mContext.getSystemService(LocationManager.class)).thenReturn(mLocationManager);
+
+        when(mLocationManager.isLocationEnabled()).thenReturn(true);
     }
 
     @Test
@@ -221,10 +230,35 @@
         assertThat(controller.isEnabled()).isFalse();
     }
 
+    @Test
+    public void getSummary() {
+        AutoTimeZonePreferenceController controller = new AutoTimeZonePreferenceController(
+                mContext, mCallback, false /* fromSUW */);
+
+        TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
+                /* autoSupported= */true, /* autoEnabled= */true, /* telephonySupported= */
+                true);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+        when(mTimeManager.updateTimeZoneConfiguration(Mockito.any())).thenReturn(true);
+
+        assertThat(controller.getSummary()).isEqualTo("");
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(
+                /* autoSupported= */true, /* autoEnabled= */true, /* telephonySupported= */
+                false);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+        when(mTimeManager.updateTimeZoneConfiguration(Mockito.any())).thenReturn(true);
+
+        assertThat(controller.getSummary()).isEqualTo(
+                mContext.getString(R.string.auto_zone_requires_location_summary));
+    }
+
     private static TimeZoneCapabilitiesAndConfig createCapabilitiesAndConfig(
-            boolean autoSupported, boolean autoEnabled) {
+            boolean autoSupported, boolean autoEnabled, boolean telephonySupported) {
         TimeZoneDetectorStatus status = new TimeZoneDetectorStatus(DETECTOR_STATUS_RUNNING,
-                new TelephonyTimeZoneAlgorithmStatus(DETECTION_ALGORITHM_STATUS_RUNNING),
+                new TelephonyTimeZoneAlgorithmStatus(
+                        telephonySupported ? DETECTION_ALGORITHM_STATUS_RUNNING
+                                : DETECTION_ALGORITHM_STATUS_NOT_SUPPORTED),
                 new LocationTimeZoneAlgorithmStatus(DETECTION_ALGORITHM_STATUS_RUNNING,
                         PROVIDER_STATUS_NOT_READY, null,
                         PROVIDER_STATUS_NOT_PRESENT, null));
@@ -242,4 +276,9 @@
                 .build();
         return new TimeZoneCapabilitiesAndConfig(status, capabilities, config);
     }
+
+    private static TimeZoneCapabilitiesAndConfig createCapabilitiesAndConfig(
+            boolean autoSupported, boolean autoEnabled) {
+        return createCapabilitiesAndConfig(autoSupported, autoEnabled, false);
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/datetime/LocationProviderStatusPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/datetime/LocationProviderStatusPreferenceControllerTest.java
new file mode 100644
index 0000000..4f9f1cc
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/datetime/LocationProviderStatusPreferenceControllerTest.java
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.datetime;
+
+import static android.app.time.DetectorStatusTypes.DETECTION_ALGORITHM_STATUS_RUNNING;
+import static android.app.time.DetectorStatusTypes.DETECTOR_STATUS_RUNNING;
+import static android.app.time.LocationTimeZoneAlgorithmStatus.PROVIDER_STATUS_IS_CERTAIN;
+import static android.app.time.LocationTimeZoneAlgorithmStatus.PROVIDER_STATUS_IS_UNCERTAIN;
+import static android.service.timezone.TimeZoneProviderStatus.DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS;
+import static android.service.timezone.TimeZoneProviderStatus.DEPENDENCY_STATUS_OK;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.app.time.Capabilities;
+import android.app.time.LocationTimeZoneAlgorithmStatus;
+import android.app.time.TelephonyTimeZoneAlgorithmStatus;
+import android.app.time.TimeManager;
+import android.app.time.TimeZoneCapabilities;
+import android.app.time.TimeZoneCapabilitiesAndConfig;
+import android.app.time.TimeZoneConfiguration;
+import android.app.time.TimeZoneDetectorStatus;
+import android.content.Context;
+import android.location.LocationManager;
+import android.os.UserHandle;
+import android.service.timezone.TimeZoneProviderStatus;
+
+import androidx.annotation.Nullable;
+
+import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(RobolectricTestRunner.class)
+public class LocationProviderStatusPreferenceControllerTest {
+
+    private Context mContext;
+    @Mock
+    private TimeManager mTimeManager;
+    @Mock
+    private LocationManager mLocationManager;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mContext = spy(RuntimeEnvironment.application);
+
+        when(mContext.getSystemService(TimeManager.class)).thenReturn(mTimeManager);
+        when(mContext.getSystemService(LocationManager.class)).thenReturn(mLocationManager);
+        when(mLocationManager.isLocationEnabled()).thenReturn(true);
+        when(mContext.getString(
+                R.string.location_time_zone_detection_status_summary_blocked_by_settings))
+                .thenReturn("BBS");
+    }
+
+    @Test
+    public void testCapabilityStatus() {
+        TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_OK, DEPENDENCY_STATUS_OK);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+        LocationProviderStatusPreferenceController controller =
+                new LocationProviderStatusPreferenceController(mContext, "LPSPC");
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(true, DEPENDENCY_STATUS_OK,
+                DEPENDENCY_STATUS_OK);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS, DEPENDENCY_STATUS_OK);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(true,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS, DEPENDENCY_STATUS_OK);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+    }
+
+    @Test
+    public void testProviderStatus_primaryCertain() {
+        TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_OK, DEPENDENCY_STATUS_OK);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+        LocationProviderStatusPreferenceController controller =
+                new LocationProviderStatusPreferenceController(mContext, "LPSPC");
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS, DEPENDENCY_STATUS_OK);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false, DEPENDENCY_STATUS_OK,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false, DEPENDENCY_STATUS_OK,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+    }
+
+    @Test
+    public void testProviderStatus_primaryUncertain() {
+        TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_OK, DEPENDENCY_STATUS_OK, PROVIDER_STATUS_IS_CERTAIN);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+        LocationProviderStatusPreferenceController controller =
+                new LocationProviderStatusPreferenceController(mContext, "LPSPC");
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS, DEPENDENCY_STATUS_OK,
+                PROVIDER_STATUS_IS_CERTAIN);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false, DEPENDENCY_STATUS_OK,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS, PROVIDER_STATUS_IS_UNCERTAIN);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false, DEPENDENCY_STATUS_OK,
+                DEPENDENCY_STATUS_OK, PROVIDER_STATUS_IS_UNCERTAIN);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+    }
+
+    @Test
+    public void testProviderStatus_nullProviders() {
+        TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                null, null);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+        LocationProviderStatusPreferenceController controller =
+                new LocationProviderStatusPreferenceController(mContext, "LPSPC");
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS, null);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false, DEPENDENCY_STATUS_OK, null);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.CONDITIONALLY_UNAVAILABLE);
+
+        capabilitiesAndConfig = createCapabilitiesAndConfig(false, null,
+                DEPENDENCY_STATUS_BLOCKED_BY_SETTINGS);
+        when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
+
+        assertThat(controller.getAvailabilityStatus()).isEqualTo(
+                BasePreferenceController.AVAILABLE_UNSEARCHABLE);
+    }
+
+    private TimeZoneCapabilitiesAndConfig createCapabilitiesAndConfig(boolean capabilitySupported,
+            @Nullable Integer primary, @Nullable Integer secondary) {
+        return createCapabilitiesAndConfig(capabilitySupported, primary, secondary,
+                PROVIDER_STATUS_IS_CERTAIN);
+    }
+
+    private TimeZoneCapabilitiesAndConfig createCapabilitiesAndConfig(boolean capabilitySupported,
+            @Nullable Integer primary, @Nullable Integer secondary, int primaryProviderStatus) {
+        TimeZoneDetectorStatus status = new TimeZoneDetectorStatus(DETECTOR_STATUS_RUNNING,
+                new TelephonyTimeZoneAlgorithmStatus(DETECTION_ALGORITHM_STATUS_RUNNING),
+                new LocationTimeZoneAlgorithmStatus(DETECTION_ALGORITHM_STATUS_RUNNING,
+                        primaryProviderStatus, primary != null
+                        ? new TimeZoneProviderStatus.Builder().setLocationDetectionDependencyStatus(
+                        primary).build() : null, PROVIDER_STATUS_IS_CERTAIN, secondary != null
+                        ? new TimeZoneProviderStatus.Builder().setLocationDetectionDependencyStatus(
+                        secondary).build() : null));
+
+        TimeZoneCapabilities capabilities = new TimeZoneCapabilities.Builder(
+                UserHandle.SYSTEM).setConfigureAutoDetectionEnabledCapability(
+                Capabilities.CAPABILITY_POSSESSED).setConfigureGeoDetectionEnabledCapability(
+                capabilitySupported ? Capabilities.CAPABILITY_POSSESSED
+                        : Capabilities.CAPABILITY_NOT_SUPPORTED).setSetManualTimeZoneCapability(
+                Capabilities.CAPABILITY_POSSESSED).build();
+
+        return new TimeZoneCapabilitiesAndConfig(status, capabilities,
+                new TimeZoneConfiguration.Builder().build());
+    }
+}