Add primary switch for vibration settings screen

Add primary switch that updates the VIBRATE_ON user setting.

Update all settings in this page to be disabled when this main toggle is
off.

Bug: 30028435
Test: VibrationMainSwitchPreferenceControllerTest
Change-Id: I752ca3b914c46678a1347034c5b6cf24fd40cc13
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 7520c91..727c689 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -5457,6 +5457,8 @@
     <string name="accessibility_notification_alarm_vibration_category_title">Notifications and alarms</string>
     <!-- Title for the category of preferences to configure device vibrations triggered by user interaction with the device. [CHAR LIMIT=NONE] -->
     <string name="accessibility_interactive_haptics_category_title">Interactive haptics</string>
+    <!-- Title for primary switch preference for enabling device vibrations. [CHAR LIMIT=NONE] -->
+    <string name="accessibility_vibration_primary_switch_title">Use vibration &amp; haptics</string>
     <!-- Title for preference for configuring alarm vibrations. [CHAR LIMIT=NONE] -->
     <string name="accessibility_alarm_vibration_title">Alarm vibration</string>
     <!-- Title for preference for configuring media vibrations (e.g. vibrations played together with animations, music, videos, etc). [CHAR LIMIT=NONE] -->
@@ -8235,6 +8237,8 @@
     <!-- List of synonyms for hotspot and tethering setting (where you share your wifi with other devices), used to match in settings search [CHAR LIMIT=NONE] -->
     <string name="keywords_hotspot_tethering">usb tether, bluetooth tether, wifi hotspot</string>
 
+    <!-- List of synonyms for device vibration primary setting, used to match in settings search [CHAR LIMIT=NONE] -->
+    <string name="keywords_accessibility_vibration_primary_switch">haptics, vibrate, vibration</string>
     <!-- List of synonyms for touch vibration setting (where you get a haptic response for touching things on the screen), used to match in settings search [CHAR LIMIT=NONE] -->
     <string name="keywords_touch_vibration">haptics, vibrate, screen, sensitivity</string>
     <!-- List of synonyms for ring vibration setting (changes whether your phone vibrates when it rings), used to match in settings search [CHAR LIMIT=NONE] -->
diff --git a/res/xml/accessibility_vibration_intensity_settings.xml b/res/xml/accessibility_vibration_intensity_settings.xml
index 7982268..7b08fe0 100644
--- a/res/xml/accessibility_vibration_intensity_settings.xml
+++ b/res/xml/accessibility_vibration_intensity_settings.xml
@@ -19,6 +19,12 @@
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:title="@string/accessibility_vibration_settings_title">
 
+    <com.android.settingslib.widget.MainSwitchPreference
+        android:key="vibration_main_switch"
+        android:title="@string/accessibility_vibration_primary_switch_title"
+        app:keywords="@string/keywords_accessibility_vibration_primary_switch"
+        app:controller="com.android.settings.accessibility.VibrationMainSwitchPreferenceController"/>
+
     <PreferenceCategory
         android:key="accessibility_call_vibration_category"
         android:title="@string/accessibility_call_vibration_category_title">
diff --git a/res/xml/accessibility_vibration_settings.xml b/res/xml/accessibility_vibration_settings.xml
index af78433..25be499 100644
--- a/res/xml/accessibility_vibration_settings.xml
+++ b/res/xml/accessibility_vibration_settings.xml
@@ -19,6 +19,12 @@
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:title="@string/accessibility_vibration_settings_title">
 
+    <com.android.settingslib.widget.MainSwitchPreference
+        android:key="vibration_main_switch"
+        android:title="@string/accessibility_vibration_primary_switch_title"
+        app:keywords="@string/keywords_accessibility_vibration_primary_switch"
+        app:controller="com.android.settings.accessibility.VibrationMainSwitchPreferenceController"/>
+
     <PreferenceCategory
         android:key="accessibility_call_vibration_category"
         android:title="@string/accessibility_call_vibration_category_title">
diff --git a/src/com/android/settings/accessibility/RingVibrationIntensityPreferenceController.java b/src/com/android/settings/accessibility/RingVibrationIntensityPreferenceController.java
index 894d818..e79ad8b 100644
--- a/src/com/android/settings/accessibility/RingVibrationIntensityPreferenceController.java
+++ b/src/com/android/settings/accessibility/RingVibrationIntensityPreferenceController.java
@@ -16,57 +16,12 @@
 
 package com.android.settings.accessibility;
 
-import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
-import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
-
 import android.content.Context;
-import android.media.AudioManager;
-import android.os.VibrationAttributes;
-import android.os.Vibrator;
-import android.provider.Settings;
 
 /** Preference controller for ringtone vibration intensity */
 public class RingVibrationIntensityPreferenceController
         extends VibrationIntensityPreferenceController {
 
-    /** General configuration for ringtone vibration intensity settings. */
-    public static final class RingVibrationPreferenceConfig extends VibrationPreferenceConfig {
-        private final AudioManager mAudioManager;
-
-        public RingVibrationPreferenceConfig(Context context) {
-            super(context, Settings.System.RING_VIBRATION_INTENSITY,
-                    VibrationAttributes.USAGE_RINGTONE);
-            mAudioManager = context.getSystemService(AudioManager.class);
-        }
-
-        @Override
-        public int readIntensity() {
-            final int vibrateWhenRinging = Settings.System.getInt(mContentResolver,
-                    Settings.System.VIBRATE_WHEN_RINGING, ON);
-
-            if ((vibrateWhenRinging == OFF)
-                    && !mAudioManager.isRampingRingerEnabled()) {
-                // VIBRATE_WHEN_RINGING is deprecated but should still be applied if the user has
-                // turned it off and has not enabled the ramping ringer (old three-state setting).
-                return Vibrator.VIBRATION_INTENSITY_OFF;
-            }
-
-            return super.readIntensity();
-        }
-
-        @Override
-        public boolean updateIntensity(int intensity) {
-            final boolean success = super.updateIntensity(intensity);
-
-            // VIBRATE_WHEN_RINGING is deprecated but should still reflect the intensity setting.
-            // Ramping ringer is independent of the ring intensity and should not be affected.
-            Settings.System.putInt(mContentResolver, Settings.System.VIBRATE_WHEN_RINGING,
-                    (intensity == Vibrator.VIBRATION_INTENSITY_OFF) ? OFF : ON);
-
-            return success;
-        }
-    }
-
     public RingVibrationIntensityPreferenceController(Context context, String preferenceKey) {
         super(context, preferenceKey, new RingVibrationPreferenceConfig(context));
     }
diff --git a/src/com/android/settings/accessibility/RingVibrationPreferenceConfig.java b/src/com/android/settings/accessibility/RingVibrationPreferenceConfig.java
new file mode 100644
index 0000000..da446d7
--- /dev/null
+++ b/src/com/android/settings/accessibility/RingVibrationPreferenceConfig.java
@@ -0,0 +1,64 @@
+/*
+ * 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.accessibility;
+
+import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
+import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
+
+import android.content.Context;
+import android.media.AudioManager;
+import android.os.VibrationAttributes;
+import android.os.Vibrator;
+import android.provider.Settings;
+
+/** General configuration for ringtone vibration intensity settings. */
+public class RingVibrationPreferenceConfig extends VibrationPreferenceConfig {
+    private final AudioManager mAudioManager;
+
+    public RingVibrationPreferenceConfig(Context context) {
+        super(context, Settings.System.RING_VIBRATION_INTENSITY,
+                VibrationAttributes.USAGE_RINGTONE);
+        mAudioManager = context.getSystemService(AudioManager.class);
+    }
+
+    @Override
+    public int readIntensity() {
+        final int vibrateWhenRinging = Settings.System.getInt(mContentResolver,
+                Settings.System.VIBRATE_WHEN_RINGING, ON);
+
+        if ((vibrateWhenRinging == OFF)
+                && !mAudioManager.isRampingRingerEnabled()) {
+            // VIBRATE_WHEN_RINGING is deprecated but should still be applied if the user has
+            // turned it off and has not enabled the ramping ringer (old three-state setting).
+            return Vibrator.VIBRATION_INTENSITY_OFF;
+        }
+
+        return super.readIntensity();
+    }
+
+    @Override
+    public boolean updateIntensity(int intensity) {
+        final boolean success = super.updateIntensity(intensity);
+
+        // VIBRATE_WHEN_RINGING is deprecated but should still reflect the intensity setting.
+        // Ramping ringer is independent of the ring intensity and should not be affected.
+        Settings.System.putInt(mContentResolver, Settings.System.VIBRATE_WHEN_RINGING,
+                (intensity == Vibrator.VIBRATION_INTENSITY_OFF) ? OFF : ON);
+
+        return success;
+    }
+}
diff --git a/src/com/android/settings/accessibility/RingVibrationTogglePreferenceController.java b/src/com/android/settings/accessibility/RingVibrationTogglePreferenceController.java
index e68b6ce..efad946 100644
--- a/src/com/android/settings/accessibility/RingVibrationTogglePreferenceController.java
+++ b/src/com/android/settings/accessibility/RingVibrationTogglePreferenceController.java
@@ -18,8 +18,6 @@
 
 import android.content.Context;
 
-import com.android.settings.accessibility.RingVibrationIntensityPreferenceController.RingVibrationPreferenceConfig;
-
 /** Preference controller for ringtone vibration with only a toggle for on/off states. */
 public class RingVibrationTogglePreferenceController extends VibrationTogglePreferenceController {
 
diff --git a/src/com/android/settings/accessibility/VibrationIntensityPreferenceController.java b/src/com/android/settings/accessibility/VibrationIntensityPreferenceController.java
index ef15f06..b3e8168 100644
--- a/src/com/android/settings/accessibility/VibrationIntensityPreferenceController.java
+++ b/src/com/android/settings/accessibility/VibrationIntensityPreferenceController.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.os.Vibrator;
 
+import androidx.preference.Preference;
 import androidx.preference.PreferenceScreen;
 
 import com.android.settings.R;
@@ -70,14 +71,23 @@
         super.displayPreference(screen);
         final SeekBarPreference preference = screen.findPreference(getPreferenceKey());
         mSettingsContentObserver.onDisplayPreference(this, preference);
-        // TODO: remove this and replace with a different way to play the haptic preview without
-        // relying on the setting being propagated to the service.
+        preference.setEnabled(mPreferenceConfig.isPreferenceEnabled());
+        // TODO: remove setContinuousUpdates and replace with a different way to play the haptic
+        // preview without relying on the setting being propagated to the service.
         preference.setContinuousUpdates(true);
         preference.setMin(getMin());
         preference.setMax(getMax());
     }
 
     @Override
+    public void updateState(Preference preference) {
+        super.updateState(preference);
+        if (preference != null) {
+            preference.setEnabled(mPreferenceConfig.isPreferenceEnabled());
+        }
+    }
+
+    @Override
     public int getMin() {
         return Vibrator.VIBRATION_INTENSITY_OFF;
     }
@@ -89,12 +99,19 @@
 
     @Override
     public int getSliderPosition() {
+        if (!mPreferenceConfig.isPreferenceEnabled()) {
+            return getMin();
+        }
         final int position = mPreferenceConfig.readIntensity();
         return Math.min(position, getMax());
     }
 
     @Override
     public boolean setSliderPosition(int position) {
+        if (!mPreferenceConfig.isPreferenceEnabled()) {
+            // Ignore slider updates when the preference is disabled.
+            return false;
+        }
         final int intensity = calculateVibrationIntensity(position);
         final boolean success = mPreferenceConfig.updateIntensity(intensity);
 
diff --git a/src/com/android/settings/accessibility/VibrationMainSwitchPreferenceController.java b/src/com/android/settings/accessibility/VibrationMainSwitchPreferenceController.java
new file mode 100644
index 0000000..726bbc1
--- /dev/null
+++ b/src/com/android/settings/accessibility/VibrationMainSwitchPreferenceController.java
@@ -0,0 +1,91 @@
+/*
+ * 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.accessibility;
+
+import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
+import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
+
+import android.content.Context;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Handler;
+import android.provider.Settings;
+
+import com.android.settings.R;
+import com.android.settings.widget.SettingsMainSwitchPreferenceController;
+import com.android.settingslib.core.lifecycle.LifecycleObserver;
+import com.android.settingslib.core.lifecycle.events.OnStart;
+import com.android.settingslib.core.lifecycle.events.OnStop;
+
+/**
+ * Preference controller for the main switch setting for vibration and haptics screen.
+ *
+ * <p>This preference is controlled by the setting key{@link Settings.System#VIBRATE_ON}, and it
+ * will disable the entire settings screen once the settings is turned OFF. All device haptics will
+ * be disabled by this setting, except the flagged alerts and accessibility touch feedback.
+ */
+public class VibrationMainSwitchPreferenceController extends SettingsMainSwitchPreferenceController
+        implements LifecycleObserver, OnStart, OnStop {
+
+    private final ContentObserver mSettingObserver;
+
+    public VibrationMainSwitchPreferenceController(Context context, String preferenceKey) {
+        super(context, preferenceKey);
+        mSettingObserver = new ContentObserver(new Handler(/* async= */ true)) {
+            @Override
+            public void onChange(boolean selfChange, Uri uri) {
+                updateState(mSwitchPreference);
+            }
+        };
+    }
+
+    @Override
+    public int getAvailabilityStatus() {
+        return AVAILABLE;
+    }
+
+    @Override
+    public void onStart() {
+        mContext.getContentResolver().registerContentObserver(
+                Settings.System.getUriFor(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY),
+                /* notifyForDescendants= */ false,
+                mSettingObserver);
+    }
+
+    @Override
+    public void onStop() {
+        mContext.getContentResolver().unregisterContentObserver(mSettingObserver);
+    }
+
+    @Override
+    public boolean isChecked() {
+        return VibrationPreferenceConfig.isMainVibrationSwitchEnabled(
+                mContext.getContentResolver());
+    }
+
+    @Override
+    public boolean setChecked(boolean isChecked) {
+        return Settings.System.putInt(mContext.getContentResolver(),
+                VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY,
+                isChecked ? ON : OFF);
+    }
+
+    @Override
+    public int getSliceHighlightMenuRes() {
+        return R.string.menu_key_accessibility;
+    }
+}
diff --git a/src/com/android/settings/accessibility/VibrationPreferenceConfig.java b/src/com/android/settings/accessibility/VibrationPreferenceConfig.java
index aa59554..1b0b163 100644
--- a/src/com/android/settings/accessibility/VibrationPreferenceConfig.java
+++ b/src/com/android/settings/accessibility/VibrationPreferenceConfig.java
@@ -16,6 +16,8 @@
 
 package com.android.settings.accessibility;
 
+import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
+
 import android.content.ContentResolver;
 import android.content.Context;
 import android.database.ContentObserver;
@@ -36,12 +38,23 @@
  */
 public abstract class VibrationPreferenceConfig {
 
+    /**
+     * SettingsProvider key for the main "Vibration & haptics" toggle preference, that can disable
+     * all device vibrations.
+     */
+    public static final String MAIN_SWITCH_SETTING_KEY = Settings.System.VIBRATE_ON;
+
     protected final ContentResolver mContentResolver;
     private final Vibrator mVibrator;
     private final String mSettingKey;
     private final int mDefaultIntensity;
     private final VibrationAttributes mVibrationAttributes;
 
+    /** Returns true if the user setting for enabling device vibrations is enabled. */
+    public static boolean isMainVibrationSwitchEnabled(ContentResolver contentResolver) {
+        return Settings.System.getInt(contentResolver, MAIN_SWITCH_SETTING_KEY, ON) == ON;
+    }
+
     public VibrationPreferenceConfig(Context context, String settingKey, int vibrationUsage) {
         mContentResolver = context.getContentResolver();
         mVibrator = context.getSystemService(Vibrator.class);
@@ -52,11 +65,16 @@
                 .build();
     }
 
-    /** Return the setting key for this setting preference. */
+    /** Returns the setting key for this setting preference. */
     public String getSettingKey() {
         return mSettingKey;
     }
 
+    /** Returns true if this setting preference is enabled for user update. */
+    public boolean isPreferenceEnabled() {
+        return isMainVibrationSwitchEnabled(mContentResolver);
+    }
+
     /** Returns the default intensity to be displayed when the setting value is not set. */
     public int getDefaultIntensity() {
         return mDefaultIntensity;
@@ -80,6 +98,9 @@
 
     /** {@link ContentObserver} for a setting described by a {@link VibrationPreferenceConfig}. */
     public static final class SettingObserver extends ContentObserver {
+        private static final Uri MAIN_SWITCH_SETTING_URI =
+                Settings.System.getUriFor(MAIN_SWITCH_SETTING_KEY);
+
         private final Uri mUri;
         private AbstractPreferenceController mPreferenceController;
         private Preference mPreference;
@@ -92,7 +113,11 @@
 
         @Override
         public void onChange(boolean selfChange, Uri uri) {
-            if (mUri.equals(uri) && mPreferenceController != null && mPreference != null) {
+            if (mPreferenceController == null || mPreference == null) {
+                // onDisplayPreference not triggered yet, nothing to update.
+                return;
+            }
+            if (mUri.equals(uri) || MAIN_SWITCH_SETTING_URI.equals(uri)) {
                 mPreferenceController.updateState(mPreference);
             }
         }
@@ -103,6 +128,8 @@
          */
         public void register(ContentResolver contentResolver) {
             contentResolver.registerContentObserver(mUri, /* notifyForDescendants= */ false, this);
+            contentResolver.registerContentObserver(MAIN_SWITCH_SETTING_URI,
+                    /* notifyForDescendants= */ false, this);
         }
 
         /**
diff --git a/src/com/android/settings/accessibility/VibrationRampingRingerTogglePreferenceController.java b/src/com/android/settings/accessibility/VibrationRampingRingerTogglePreferenceController.java
index 21a5e36..37a0257 100644
--- a/src/com/android/settings/accessibility/VibrationRampingRingerTogglePreferenceController.java
+++ b/src/com/android/settings/accessibility/VibrationRampingRingerTogglePreferenceController.java
@@ -21,7 +21,6 @@
 import android.media.AudioManager;
 import android.net.Uri;
 import android.os.Handler;
-import android.os.VibrationAttributes;
 import android.os.Vibrator;
 import android.provider.DeviceConfig;
 import android.provider.Settings;
@@ -57,8 +56,9 @@
 
     private final DeviceConfigProvider mDeviceConfigProvider;
     private final ContentObserver mSettingObserver;
-    private final Vibrator mVibrator;
     private final AudioManager mAudioManager;
+    private final VibrationPreferenceConfig mRingVibrationPreferenceConfig;
+    private final VibrationPreferenceConfig.SettingObserver mRingSettingObserver;
 
     private Preference mPreference;
 
@@ -70,8 +70,10 @@
             String preferenceKey, DeviceConfigProvider deviceConfigProvider) {
         super(context, preferenceKey);
         mDeviceConfigProvider = deviceConfigProvider;
-        mVibrator = context.getSystemService(Vibrator.class);
         mAudioManager = context.getSystemService(AudioManager.class);
+        mRingVibrationPreferenceConfig = new RingVibrationPreferenceConfig(context);
+        mRingSettingObserver = new VibrationPreferenceConfig.SettingObserver(
+                mRingVibrationPreferenceConfig);
         mSettingObserver = new ContentObserver(new Handler(/* async= */ true)) {
             @Override
             public void onChange(boolean selfChange, Uri uri) {
@@ -91,18 +93,16 @@
 
     @Override
     public void onStart() {
+        mRingSettingObserver.register(mContext.getContentResolver());
         mContext.getContentResolver().registerContentObserver(
                 Settings.System.getUriFor(Settings.System.APPLY_RAMPING_RINGER),
                 /* notifyForDescendants= */ false,
                 mSettingObserver);
-        mContext.getContentResolver().registerContentObserver(
-                Settings.System.getUriFor(Settings.System.RING_VIBRATION_INTENSITY),
-                /* notifyForDescendants= */ false,
-                mSettingObserver);
     }
 
     @Override
     public void onStop() {
+        mRingSettingObserver.unregister(mContext.getContentResolver());
         mContext.getContentResolver().unregisterContentObserver(mSettingObserver);
     }
 
@@ -110,6 +110,7 @@
     public void displayPreference(PreferenceScreen screen) {
         super.displayPreference(screen);
         mPreference = screen.findPreference(getPreferenceKey());
+        mRingSettingObserver.onDisplayPreference(this, mPreference);
         mPreference.setEnabled(isRingVibrationEnabled());
     }
 
@@ -141,9 +142,8 @@
     }
 
     private boolean isRingVibrationEnabled() {
-        final int ringIntensity = Settings.System.getInt(mContext.getContentResolver(),
-                Settings.System.RING_VIBRATION_INTENSITY,
-                mVibrator.getDefaultVibrationIntensity(VibrationAttributes.USAGE_RINGTONE));
-        return ringIntensity != Vibrator.VIBRATION_INTENSITY_OFF;
+        return mRingVibrationPreferenceConfig.isPreferenceEnabled()
+                && (mRingVibrationPreferenceConfig.readIntensity()
+                != Vibrator.VIBRATION_INTENSITY_OFF);
     }
 }
diff --git a/src/com/android/settings/accessibility/VibrationTogglePreferenceController.java b/src/com/android/settings/accessibility/VibrationTogglePreferenceController.java
index 5278b66..8f158cc 100644
--- a/src/com/android/settings/accessibility/VibrationTogglePreferenceController.java
+++ b/src/com/android/settings/accessibility/VibrationTogglePreferenceController.java
@@ -58,16 +58,29 @@
         super.displayPreference(screen);
         final Preference preference = screen.findPreference(getPreferenceKey());
         mSettingsContentObserver.onDisplayPreference(this, preference);
+        preference.setEnabled(mPreferenceConfig.isPreferenceEnabled());
+    }
+
+    @Override
+    public void updateState(Preference preference) {
+        super.updateState(preference);
+        if (preference != null) {
+            preference.setEnabled(mPreferenceConfig.isPreferenceEnabled());
+        }
     }
 
     @Override
     public boolean isChecked() {
-        final int position = mPreferenceConfig.readIntensity();
-        return position != Vibrator.VIBRATION_INTENSITY_OFF;
+        return mPreferenceConfig.isPreferenceEnabled()
+                && (mPreferenceConfig.readIntensity() != Vibrator.VIBRATION_INTENSITY_OFF);
     }
 
     @Override
     public boolean setChecked(boolean isChecked) {
+        if (!mPreferenceConfig.isPreferenceEnabled()) {
+            // Ignore toggle updates when the preference is disabled.
+            return false;
+        }
         final int newIntensity = isChecked
                 ? mPreferenceConfig.getDefaultIntensity()
                 : Vibrator.VIBRATION_INTENSITY_OFF;
diff --git a/tests/robotests/src/com/android/settings/accessibility/VibrationIntensityPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/accessibility/VibrationIntensityPreferenceControllerTest.java
index ba48f66..c68262c 100644
--- a/tests/robotests/src/com/android/settings/accessibility/VibrationIntensityPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/accessibility/VibrationIntensityPreferenceControllerTest.java
@@ -38,11 +38,14 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.RobolectricTestRunner;
 
+/** Tests for {@link VibrationIntensityPreferenceController}. */
 @RunWith(RobolectricTestRunner.class)
 public class VibrationIntensityPreferenceControllerTest {
 
     private static final String SETTING_KEY = Settings.System.NOTIFICATION_VIBRATION_INTENSITY;
     private static final int VIBRATION_USAGE = VibrationAttributes.USAGE_NOTIFICATION;
+    private static final int OFF = 0;
+    private static final int ON = 1;
 
     /** Basic implementation of preference controller to test generic behavior. */
     private static class TestPreferenceController extends VibrationIntensityPreferenceController {
@@ -77,13 +80,34 @@
     @Test
     public void missingSetting_shouldReturnDefault() {
         VibrationIntensityPreferenceController controller = createPreferenceController(3);
-        Settings.System.putString(mContext.getContentResolver(), SETTING_KEY, null);
+        Settings.System.putString(mContext.getContentResolver(), SETTING_KEY, /* value= */ null);
         controller.updateState(mPreference);
         assertThat(mPreference.getProgress())
                 .isEqualTo(mVibrator.getDefaultVibrationIntensity(VIBRATION_USAGE));
     }
 
     @Test
+    public void updateState_mainSwitchUpdates_shouldPreserveSettingBetweenUpdates() {
+        VibrationIntensityPreferenceController controller = createPreferenceController(3);
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_LOW);
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, ON);
+        controller.updateState(mPreference);
+        assertThat(mPreference.getProgress()).isEqualTo(Vibrator.VIBRATION_INTENSITY_LOW);
+        assertThat(mPreference.isEnabled()).isTrue();
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, OFF);
+        controller.updateState(mPreference);
+        assertThat(mPreference.getProgress()).isEqualTo(Vibrator.VIBRATION_INTENSITY_OFF);
+        assertThat(mPreference.isEnabled()).isFalse();
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, ON);
+        controller.updateState(mPreference);
+        assertThat(mPreference.getProgress()).isEqualTo(Vibrator.VIBRATION_INTENSITY_LOW);
+        assertThat(mPreference.isEnabled()).isTrue();
+    }
+
+    @Test
     public void updateState_allLevelsSupported_shouldDisplayIntensityInSliderPosition() {
         VibrationIntensityPreferenceController controller = createPreferenceController(3);
 
@@ -147,6 +171,21 @@
     }
 
     @Test
+    public void setProgress_mainSwitchDisabled_ignoresUpdates() throws Exception {
+        VibrationIntensityPreferenceController controller = createPreferenceController(3);
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_LOW);
+        assertThat(mPreference.getProgress()).isEqualTo(Vibrator.VIBRATION_INTENSITY_LOW);
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, OFF);
+        controller.updateState(mPreference);
+        controller.setSliderPosition(Vibrator.VIBRATION_INTENSITY_HIGH);
+
+        assertThat(readSetting(SETTING_KEY)).isEqualTo(Vibrator.VIBRATION_INTENSITY_LOW);
+        assertThat(mPreference.getProgress()).isEqualTo(Vibrator.VIBRATION_INTENSITY_OFF);
+        assertThat(mPreference.isEnabled()).isFalse();
+
+    }
+    @Test
     public void setProgress_allSupportedPositions_updatesIntensitySetting() throws Exception {
         VibrationIntensityPreferenceController controller = createPreferenceController(3);
 
diff --git a/tests/robotests/src/com/android/settings/accessibility/VibrationMainSwitchPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/accessibility/VibrationMainSwitchPreferenceControllerTest.java
new file mode 100644
index 0000000..6f57003
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/accessibility/VibrationMainSwitchPreferenceControllerTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.accessibility;
+
+import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
+import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.provider.Settings;
+
+import androidx.preference.PreferenceScreen;
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.settingslib.core.lifecycle.Lifecycle;
+import com.android.settingslib.widget.MainSwitchPreference;
+
+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;
+
+/** Tests for {@link VibrationMainSwitchPreferenceController}. */
+@RunWith(RobolectricTestRunner.class)
+public class VibrationMainSwitchPreferenceControllerTest {
+
+    private static final String PREFERENCE_KEY = "preference_key";
+
+    @Mock private PreferenceScreen mScreen;
+
+    private Lifecycle mLifecycle;
+    private Context mContext;
+    private VibrationMainSwitchPreferenceController mController;
+    private MainSwitchPreference mPreference;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mLifecycle = new Lifecycle(() -> mLifecycle);
+        mContext = ApplicationProvider.getApplicationContext();
+        mController = new VibrationMainSwitchPreferenceController(mContext, PREFERENCE_KEY);
+        mLifecycle.addObserver(mController);
+        mPreference = new MainSwitchPreference(mContext);
+        mPreference.setTitle("Test title");
+        when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
+        mController.displayPreference(mScreen);
+    }
+
+    @Test
+    public void verifyConstants() {
+        assertThat(mController.getPreferenceKey()).isEqualTo(PREFERENCE_KEY);
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+    }
+
+    @Test
+    public void updateState_shouldReturnTheSettingState() {
+        updateSetting(Settings.System.VIBRATE_ON, ON);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+
+        updateSetting(Settings.System.VIBRATE_ON, OFF);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isFalse();
+    }
+
+    @Test
+    public void setChecked_updatesSetting() throws Settings.SettingNotFoundException {
+        updateSetting(Settings.System.VIBRATE_ON, OFF);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isFalse();
+
+        mController.setChecked(true);
+        assertThat(readSetting(Settings.System.VIBRATE_ON)).isEqualTo(ON);
+
+        mController.setChecked(false);
+        assertThat(readSetting(Settings.System.VIBRATE_ON)).isEqualTo(OFF);
+    }
+
+    private void updateSetting(String key, int value) {
+        Settings.System.putInt(mContext.getContentResolver(), key, value);
+    }
+
+    private int readSetting(String settingKey) throws Settings.SettingNotFoundException {
+        return Settings.System.getInt(mContext.getContentResolver(), settingKey);
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/accessibility/VibrationTogglePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/accessibility/VibrationTogglePreferenceControllerTest.java
new file mode 100644
index 0000000..cb4a07e
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/accessibility/VibrationTogglePreferenceControllerTest.java
@@ -0,0 +1,172 @@
+/*
+ * 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.accessibility;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.VibrationAttributes;
+import android.os.Vibrator;
+import android.provider.Settings;
+
+import androidx.preference.PreferenceScreen;
+import androidx.preference.SwitchPreference;
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.settingslib.core.lifecycle.Lifecycle;
+
+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;
+
+/** Tests for {@link VibrationTogglePreferenceController}. */
+@RunWith(RobolectricTestRunner.class)
+public class VibrationTogglePreferenceControllerTest {
+
+    private static final String SETTING_KEY = Settings.System.NOTIFICATION_VIBRATION_INTENSITY;
+    private static final int VIBRATION_USAGE = VibrationAttributes.USAGE_NOTIFICATION;
+    private static final int OFF = 0;
+    private static final int ON = 1;
+
+    /** Basic implementation of preference controller to test generic behavior. */
+    private static class TestPreferenceController extends VibrationTogglePreferenceController {
+
+        TestPreferenceController(Context context) {
+            super(context, "preference_key",
+                    new VibrationPreferenceConfig(context, SETTING_KEY, VIBRATION_USAGE) {});
+        }
+
+        @Override
+        public int getAvailabilityStatus() {
+            return AVAILABLE;
+        }
+    }
+
+    @Mock private PreferenceScreen mScreen;
+
+    private Lifecycle mLifecycle;
+    private Context mContext;
+    private Vibrator mVibrator;
+    private SwitchPreference mPreference;
+    private VibrationTogglePreferenceController mController;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mLifecycle = new Lifecycle(() -> mLifecycle);
+        mContext = ApplicationProvider.getApplicationContext();
+        mVibrator = mContext.getSystemService(Vibrator.class);
+        mController = new TestPreferenceController(mContext);
+        mLifecycle.addObserver(mController);
+        mPreference = new SwitchPreference(mContext);
+        mPreference.setTitle("Test title");
+        when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
+        mController.displayPreference(mScreen);
+    }
+
+    @Test
+    public void missingSetting_shouldBeCheckedByDefault() {
+        Settings.System.putString(mContext.getContentResolver(), SETTING_KEY, /* value= */ null);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+    }
+
+    @Test
+    public void updateState_mainSwitchUpdates_shouldPreserveSettingBetweenUpdates() {
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_LOW);
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, ON);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+        assertThat(mPreference.isEnabled()).isTrue();
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, OFF);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isFalse();
+        assertThat(mPreference.isEnabled()).isFalse();
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, ON);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+        assertThat(mPreference.isEnabled()).isTrue();
+    }
+
+    @Test
+    public void updateState_shouldUpdateToggleState() {
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_HIGH);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_OFF);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isFalse();
+
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_MEDIUM);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_OFF);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isFalse();
+
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_LOW);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+    }
+
+    @Test
+    public void setProgress_mainSwitchDisabled_ignoresUpdates() throws Exception {
+        updateSetting(SETTING_KEY, Vibrator.VIBRATION_INTENSITY_LOW);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isTrue();
+
+        updateSetting(VibrationPreferenceConfig.MAIN_SWITCH_SETTING_KEY, OFF);
+        mController.updateState(mPreference);
+        assertThat(mPreference.isChecked()).isFalse();
+
+        mController.setChecked(true);
+        assertThat(readSetting(SETTING_KEY)).isEqualTo(Vibrator.VIBRATION_INTENSITY_LOW);
+        assertThat(mPreference.isChecked()).isFalse();
+        assertThat(mPreference.isEnabled()).isFalse();
+
+    }
+    @Test
+    public void setProgress_updatesCheckedState() throws Exception {
+        mController.setChecked(false);
+        assertThat(readSetting(SETTING_KEY)).isEqualTo(Vibrator.VIBRATION_INTENSITY_OFF);
+
+        mController.setChecked(true);
+        assertThat(readSetting(SETTING_KEY))
+                .isEqualTo(mVibrator.getDefaultVibrationIntensity(VIBRATION_USAGE));
+
+        mController.setChecked(false);
+        assertThat(readSetting(SETTING_KEY)).isEqualTo(Vibrator.VIBRATION_INTENSITY_OFF);
+    }
+
+    private void updateSetting(String key, int value) {
+        Settings.System.putInt(mContext.getContentResolver(), key, value);
+    }
+
+    private int readSetting(String settingKey) throws Settings.SettingNotFoundException {
+        return Settings.System.getInt(mContext.getContentResolver(), settingKey);
+    }
+}