Merge "Fix DirectAudioProfilesForAttributesTest for non direct profiles" into tm-dev
diff --git a/apps/CameraITS/tests/scene2_a/test_auto_flash.py b/apps/CameraITS/tests/scene2_a/test_auto_flash.py
index f16145d..f1b879b 100644
--- a/apps/CameraITS/tests/scene2_a/test_auto_flash.py
+++ b/apps/CameraITS/tests/scene2_a/test_auto_flash.py
@@ -29,8 +29,8 @@
             4: 'ON_AUTO_FLASH_REDEYE', 5: 'ON_EXTERNAL_FLASH'}
 AE_STATES = {0: 'INACTIVE', 1: 'SEARCHING', 2: 'CONVERGED', 3: 'LOCKED',
              4: 'FLASH_REQUIRED', 5: 'PRECAPTURE'}
-_GRAD_DELTA_ATOL = 100  # gradiant for tablets as screen aborbs energy
-_MEAN_DELTA_ATOL = 100  # mean used for reflective charts
+_GRAD_DELTA_ATOL = 50  # gradiant for tablets as screen aborbs energy
+_MEAN_DELTA_ATOL = 50  # mean used for reflective charts
 _NUM_FRAMES = 8
 _PATCH_H = 0.25  # center 25%
 _PATCH_W = 0.25
diff --git a/apps/CameraITS/utils/opencv_processing_utils.py b/apps/CameraITS/utils/opencv_processing_utils.py
index 2953314..d108cac 100644
--- a/apps/CameraITS/utils/opencv_processing_utils.py
+++ b/apps/CameraITS/utils/opencv_processing_utils.py
@@ -18,11 +18,9 @@
 import math
 import os
 import unittest
-
+import cv2
 import numpy
 
-
-import cv2
 import capture_request_utils
 import image_processing_utils
 
@@ -232,6 +230,8 @@
     scale_stop = self._scale_stop * s_factor
     scale_step = self._scale_step * s_factor
     self.scale = s_factor
+    logging.debug('scale start: %.3f, stop: %.3f, step: %.3f',
+                  scale_start, scale_stop, scale_step)
     max_match = []
     # check for normalized image
     if numpy.amax(scene) <= 1.0:
@@ -250,7 +250,7 @@
 
     # determine if optimization results are valid
     opt_values = [x[0] for x in max_match]
-    if 2.0 * min(opt_values) > max(opt_values):
+    if not opt_values or (2.0 * min(opt_values) > max(opt_values)):
       estring = ('Warning: unable to find chart in scene!\n'
                  'Check camera distance and self-reported '
                  'pixel pitch, focal length and hyperfocal distance.')
@@ -538,6 +538,7 @@
   """Unit tests for this module."""
 
   def test_get_angle_identify_rotated_chessboard_angle(self):
+    """Unit test to check extracted angles from images."""
     # Array of the image files and angles containing rotated chessboards.
     test_cases = [
         ('', 0),
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index baaa61d..04a8576 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -3755,6 +3755,11 @@
             Device Owner. Then press the button below, and check that CTSVerifier is NOT Device
             Owner anymore.
     </string>
+    <string name="device_owner_remove_device_owner_test_info_on_tv">
+            Please check in Settings &gt; Privacy &gt; Security &amp; Restrictions &gt; Device Administrators if CTSVerifier is
+            Device Owner. Then press the button below, and check that CTSVerifier is NOT Device
+            Owner anymore.
+    </string>
     <string name="remove_device_owner_button">Remove device owner</string>
     <string name="device_owner_check_device_owner_test">Check device owner</string>
     <string name="device_owner_check_profile_owner_test">Check profile owner</string>
@@ -4059,12 +4064,13 @@
     <string name="device_owner_disallow_config_bt">Disallow configuring Bluetooth</string>
     <string name="device_owner_disallow_config_bt_info">
         Please press the Set restriction button to set the user restriction.
-        Then press Go to open the Bluetooth page in Settings.
-        Confirm that:\n
-        \n
+        Then press Go, you should either see (a) the Bluetooth settings page or (b) trigger a support message directly.\n
+        In the case of (a), confirm that:\n
         - You cannot view Bluetooth devices in range.\n
         - Trying to edit, add or remove any already paired devices triggers a support message.\n
         \n
+        In the case of (b) this step is successful.\n
+        \n
         Use the Back button to return to this page.
     </string>
     <string name="device_owner_disallow_config_wifi">Disallow configuring WiFi</string>
@@ -6385,6 +6391,12 @@
         bubble does NOT appear on screen. Verify that there is a notification in the notification
         shade.</string>
     <string name="bubbles_test_lowram_button">Add bubble</string>
+    <!-- Disable bubbles by config_supportsBubble -->
+    <string name="bubbles_test_disable_config_title">No bubbles on bubbles disabled device</string>
+    <string name="bubbles_test_disable_config_verify">Click the button below and verify that a
+        bubble does NOT appear on screen. Verify that there is a notification in the notification
+        shade.</string>
+    <string name="bubbles_test_disable_config_button">Add bubble</string>
     <!-- Bubbles end of test summary -->
     <string name="bubbles_test_summary_title">Test Complete</string>
     <string name="bubbles_test_summary">%1$d out of %2$d tests passed</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
index cdca014..1110b0f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -96,6 +96,8 @@
     private static final String DISALLOW_ADD_WIFI_CONFIG_ID = "DISALLOW_ADD_WIFI_CONFIG";
     private static final String WIFI_SECURITY_LEVEL_RESTRICTION_ID =
             "WIFI_SECURITY_LEVEL_RESTRICTION";
+    private static final String ACTION_CONNECT_INPUT =
+            "com.google.android.intent.action.CONNECT_INPUT";
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -401,7 +403,8 @@
                                             UserManager.DISALLOW_CONFIG_BLUETOOTH, true)),
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
-                                    new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)),
+                                    new Intent(Utils.isTV(this) ? ACTION_CONNECT_INPUT
+                                            : Settings.ACTION_BLUETOOTH_SETTINGS)),
                             new ButtonInfo(
                                     R.string.device_owner_user_restriction_unset,
                                     CommandReceiverActivity.createSetCurrentUserRestrictionIntent(
@@ -410,7 +413,7 @@
         }
 
         // DISALLOW_USB_FILE_TRANSFER
-        if (FeatureUtil.isUsbFileTransferSupported(this)) {
+        if (FeatureUtil.isUsbFileTransferSupported(this) && !Utils.isTV(this)) {
             adapter.add(createInteractiveTestItem(this, DISALLOW_USB_FILE_TRANSFER_ID,
                     R.string.device_owner_disallow_usb_file_transfer_test,
                     R.string.device_owner_disallow_usb_file_transfer_test_info,
@@ -467,7 +470,7 @@
 
         // setLockTaskFeatures
         // TODO(b/189282625): replace FEATURE_WATCH with a more specific feature
-        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH) && !Utils.isTV(this)) {
             final Intent lockTaskUiTestIntent = new Intent(this, LockTaskUiTestActivity.class);
             lockTaskUiTestIntent.putExtra(LockTaskUiTestActivity.EXTRA_TEST_ID,
                     LOCK_TASK_UI_TEST_ID);
@@ -676,7 +679,8 @@
         // removeDeviceOwner
         adapter.add(createInteractiveTestItem(this, REMOVE_DEVICE_OWNER_TEST_ID,
                 R.string.device_owner_remove_device_owner_test,
-                R.string.device_owner_remove_device_owner_test_info,
+                Utils.isTV(this) ? R.string.device_owner_remove_device_owner_test_info_on_tv
+                        : R.string.device_owner_remove_device_owner_test_info,
                 new ButtonInfo(
                         R.string.remove_device_owner_button,
                         createTearDownIntent())));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerRequestingBugreportTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerRequestingBugreportTestActivity.java
index 4a4eae4..40eefea 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerRequestingBugreportTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerRequestingBugreportTestActivity.java
@@ -240,7 +240,8 @@
         // removeDeviceOwner
         adapter.add(createInteractiveTestItem(this, REMOVE_DEVICE_OWNER_TEST_ID,
                 R.string.device_owner_remove_device_owner_test,
-                R.string.device_owner_remove_device_owner_test_info,
+                Utils.isTV(this) ? R.string.device_owner_remove_device_owner_test_info_on_tv
+                        : R.string.device_owner_remove_device_owner_test_info,
                 new ButtonInfo(
                         R.string.remove_device_owner_button,
                         createTearDownIntent())));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/Utils.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/Utils.java
index 5fad20c..d8b659e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/Utils.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/Utils.java
@@ -158,4 +158,9 @@
         return context.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_SECURE_LOCK_SCREEN);
     }
+
+    static boolean isTV(Context context) {
+        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+                || context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEVISION);
+    }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java
index 8acfcd5..55a4cce 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/BubblesVerifierActivity.java
@@ -42,6 +42,7 @@
 import android.content.Intent;
 import android.content.pm.ShortcutInfo;
 import android.content.pm.ShortcutManager;
+import android.content.res.Resources;
 import android.graphics.Color;
 import android.graphics.Insets;
 import android.graphics.drawable.Icon;
@@ -150,6 +151,10 @@
         if (am.isLowRamDevice()) {
             // Bubbles don't occur on low ram, instead they just show as notifs so test that
             mTests.add(new LowRamBubbleTest());
+        } else if (!Resources.getSystem()
+                    .getBoolean(com.android.internal.R.bool.config_supportsBubble)) {
+            // Bubbles don't occur on bubble disabled devices, only test notifications.
+            mTests.add(new BubbleDisabledTest());
         } else {
             //
             // Behavior around settings at the device level and on the app settings page.
@@ -963,6 +968,31 @@
         }
     }
 
+    private class BubbleDisabledTest extends BubblesTestStep {
+        @Override
+        public int getTestTitle() {
+            return R.string.bubbles_test_disable_config_title;
+        }
+
+        @Override
+        public int getTestDescription() {
+            return R.string.bubbles_test_disable_config_verify;
+        }
+
+        @Override
+        public int getButtonText() {
+            return R.string.bubbles_test_disable_config_button;
+        }
+
+        @Override
+        public void performTestAction() {
+            Notification.Builder builder = getConversationNotif(getTestTitle());
+            builder.setBubbleMetadata(getBubbleBuilder().build());
+
+            mNotificationManager.notify(NOTIFICATION_ID, builder.build());
+        }
+    }
+
     /** Creates a shortcut to use for the notifications to be considered conversations */
     private void createShortcuts() {
         mShortcuts.clear();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthenticationMultiDocument.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthenticationMultiDocument.java
index d68c5b6..316e15a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthenticationMultiDocument.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/IdentityCredentialAuthenticationMultiDocument.java
@@ -18,6 +18,8 @@
 
 import android.Manifest;
 import android.app.KeyguardManager;
+import android.content.Context;
+import android.content.pm.FeatureInfo;
 import android.content.pm.PackageManager;
 import android.hardware.biometrics.BiometricManager;
 import android.hardware.biometrics.BiometricManager.Authenticators;
@@ -48,6 +50,7 @@
 import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
+import java.util.Locale;
 import java.util.Map;
 
 /**
@@ -59,6 +62,8 @@
 
     private static final int BIOMETRIC_REQUEST_PERMISSION_CODE = 0;
 
+    private static final int PRESENTATION_SESSION_FEATURE_VERSION_NEEDED = 202201;
+
     private BiometricManager mBiometricManager;
     private KeyguardManager mKeyguardManager;
 
@@ -70,6 +75,31 @@
         return R.string.sec_identity_credential_authentication_multi_document_test_info;
     }
 
+    // Returns 0 if Identity Credential is not implemented. Otherwise returns the feature version.
+    //
+    private static int getFeatureVersion(Context appContext) {
+        PackageManager pm = appContext.getPackageManager();
+
+        if (pm.hasSystemFeature(PackageManager.FEATURE_IDENTITY_CREDENTIAL_HARDWARE)) {
+            FeatureInfo[] infos = pm.getSystemAvailableFeatures();
+            for (int n = 0; n < infos.length; n++) {
+                FeatureInfo info = infos[n];
+                if (info.name.equals(PackageManager.FEATURE_IDENTITY_CREDENTIAL_HARDWARE)) {
+                    return info.version;
+                }
+            }
+        }
+
+        // Use of the system feature is not required since Android 12. So for Android 11
+        // return 202009 which is the feature version shipped with Android 11.
+        IdentityCredentialStore store = IdentityCredentialStore.getInstance(appContext);
+        if (store != null) {
+            return 202009;
+        }
+
+        return 0;
+    }
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
@@ -154,6 +184,18 @@
             getPassButton().setEnabled(true);
             return;
         }
+        int featureVersion = getFeatureVersion(this);
+        Log.i(TAG, "Identity Credential featureVersion: " + featureVersion);
+        if (featureVersion < PRESENTATION_SESSION_FEATURE_VERSION_NEEDED) {
+            showToast(String.format(
+                          Locale.US,
+                          "Identity Credential version %d or later is required but "
+                          + "version %d was found. Test passed.",
+                          PRESENTATION_SESSION_FEATURE_VERSION_NEEDED,
+                          featureVersion));
+            getPassButton().setEnabled(true);
+            return;
+        }
 
         final int result = mBiometricManager.canAuthenticate(Authenticators.BIOMETRIC_STRONG);
         switch (result) {
diff --git a/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureDemoMode.java b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureDemoMode.java
new file mode 100644
index 0000000..22928dc
--- /dev/null
+++ b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureDemoMode.java
@@ -0,0 +1,45 @@
+/*
+ * 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.bedstead.harrier.annotations;
+
+import static com.android.bedstead.harrier.annotations.AnnotationRunPrecedence.MIDDLE;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+/**
+ * Ensure that the device is in retail demo mode before running the test.
+ */
+@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@EnsureGlobalSettingSet(key = "device_demo_mode", value = "1")
+public @interface EnsureDemoMode {
+    /**
+     * Weight sets the order that annotations will be resolved.
+     *
+     * <p>Annotations with a lower weight will be resolved before annotations with a higher weight.
+     *
+     * <p>If there is an order requirement between annotations, ensure that the weight of the
+     * annotation which must be resolved first is lower than the one which must be resolved later.
+     *
+     * <p>Weight can be set to a {@link AnnotationRunPrecedence} constant, or to any {@link int}.
+     */
+    int weight() default MIDDLE;
+}
diff --git a/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureGlobalSettingSet.java b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureGlobalSettingSet.java
new file mode 100644
index 0000000..6bed7c4
--- /dev/null
+++ b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureGlobalSettingSet.java
@@ -0,0 +1,46 @@
+/*
+ * 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.bedstead.harrier.annotations;
+
+import static com.android.bedstead.harrier.annotations.AnnotationRunPrecedence.MIDDLE;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Repeatable;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@Repeatable(EnsureGlobalSettingSetGroup.class)
+public @interface EnsureGlobalSettingSet {
+    String key();
+
+    String value();
+
+    /**
+     * Weight sets the order that annotations will be resolved.
+     *
+     * <p>Annotations with a lower weight will be resolved before annotations with a higher weight.
+     *
+     * <p>If there is an order requirement between annotations, ensure that the weight of the
+     * annotation which must be resolved first is lower than the one which must be resolved later.
+     *
+     * <p>Weight can be set to a {@link AnnotationRunPrecedence} constant, or to any {@link int}.
+     */
+    int weight() default MIDDLE;
+}
diff --git a/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureGlobalSettingSetGroup.java b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureGlobalSettingSetGroup.java
new file mode 100644
index 0000000..08f90e9
--- /dev/null
+++ b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureGlobalSettingSetGroup.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2021 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.bedstead.harrier.annotations;
+
+import static com.android.bedstead.harrier.annotations.AnnotationRunPrecedence.MIDDLE;
+
+import com.android.bedstead.harrier.annotations.meta.RepeatingAnnotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@RepeatingAnnotation
+public @interface EnsureGlobalSettingSetGroup {
+    EnsureGlobalSettingSet[] value();
+
+    /**
+     * Weight sets the order that annotations will be resolved.
+     *
+     * <p>Annotations with a lower weight will be resolved before annotations with a higher weight.
+     *
+     * <p>If there is an order requirement between annotations, ensure that the weight of the
+     * annotation which must be resolved first is lower than the one which must be resolved later.
+     *
+     * <p>Weight can be set to a {@link AnnotationRunPrecedence} constant, or to any {@link int}.
+     */
+    int weight() default MIDDLE;
+}
diff --git a/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureNotDemoMode.java b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureNotDemoMode.java
new file mode 100644
index 0000000..5010873
--- /dev/null
+++ b/common/device-side/bedstead/harrier/common/src/main/java/com/android/bedstead/harrier/annotations/EnsureNotDemoMode.java
@@ -0,0 +1,45 @@
+/*
+ * 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.bedstead.harrier.annotations;
+
+import static com.android.bedstead.harrier.annotations.AnnotationRunPrecedence.MIDDLE;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+/**
+ * Ensure that the device is not in retail demo mode before running the test.
+ */
+@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@EnsureGlobalSettingSet(key = "device_demo_mode", value = "0")
+public @interface EnsureNotDemoMode {
+    /**
+     * Weight sets the order that annotations will be resolved.
+     *
+     * <p>Annotations with a lower weight will be resolved before annotations with a higher weight.
+     *
+     * <p>If there is an order requirement between annotations, ensure that the weight of the
+     * annotation which must be resolved first is lower than the one which must be resolved later.
+     *
+     * <p>Weight can be set to a {@link AnnotationRunPrecedence} constant, or to any {@link int}.
+     */
+    int weight() default MIDDLE;
+}
diff --git a/common/device-side/bedstead/harrier/src/main/java/com/android/bedstead/harrier/DeviceState.java b/common/device-side/bedstead/harrier/src/main/java/com/android/bedstead/harrier/DeviceState.java
index bf67e58..b28b815 100644
--- a/common/device-side/bedstead/harrier/src/main/java/com/android/bedstead/harrier/DeviceState.java
+++ b/common/device-side/bedstead/harrier/src/main/java/com/android/bedstead/harrier/DeviceState.java
@@ -50,6 +50,7 @@
 import com.android.bedstead.harrier.annotations.EnsureCanGetPermission;
 import com.android.bedstead.harrier.annotations.EnsureDoesNotHaveAppOp;
 import com.android.bedstead.harrier.annotations.EnsureDoesNotHavePermission;
+import com.android.bedstead.harrier.annotations.EnsureGlobalSettingSet;
 import com.android.bedstead.harrier.annotations.EnsureHasAppOp;
 import com.android.bedstead.harrier.annotations.EnsureHasPermission;
 import com.android.bedstead.harrier.annotations.EnsurePackageNotInstalled;
@@ -778,6 +779,14 @@
                 ensureBluetoothDisabled();
                 continue;
             }
+
+            if (annotation instanceof EnsureGlobalSettingSet) {
+                EnsureGlobalSettingSet ensureGlobalSettingSetAnnotation =
+                        (EnsureGlobalSettingSet) annotation;
+                ensureGlobalSettingSet(
+                        ensureGlobalSettingSetAnnotation.key(),
+                        ensureGlobalSettingSetAnnotation.value());
+            }
         }
 
         requireSdkVersion(/* min= */ mMinSdkVersionCurrentTest,
@@ -1152,7 +1161,7 @@
     private Boolean mOriginalBluetoothEnabled;
     private TestAppProvider mTestAppProvider = new TestAppProvider();
     private Map<String, TestAppInstance> mTestApps = new HashMap<>();
-
+    private final Map<String, String> mOriginalGlobalSettings = new HashMap<>();
 
     private static final class RemovedUser {
         // Store the user builder so we can recreate the user later
@@ -1759,6 +1768,11 @@
             TestApis.bluetooth().setEnabled(mOriginalBluetoothEnabled);
             mOriginalBluetoothEnabled = null;
         }
+
+        for (Map.Entry<String, String> s : mOriginalGlobalSettings.entrySet()) {
+            TestApis.settings().global().putString(s.getKey(), s.getValue());
+        }
+        mOriginalGlobalSettings.clear();
     }
 
     private UserReference createProfile(
@@ -2507,4 +2521,11 @@
             mPermissionContext = mPermissionContext.withoutPermission(permission);
         }
     }
+
+    private void ensureGlobalSettingSet(String key, String value) {
+        if (!mOriginalGlobalSettings.containsKey(key)) {
+            mOriginalGlobalSettings.put(key, TestApis.settings().global().getString(value));
+        }
+        TestApis.settings().global().putString(key, value);
+    }
 }
diff --git a/common/device-side/bedstead/harrier/src/test/java/com/android/bedstead/harrier/DeviceStateTest.java b/common/device-side/bedstead/harrier/src/test/java/com/android/bedstead/harrier/DeviceStateTest.java
index a5ec109..8234786 100644
--- a/common/device-side/bedstead/harrier/src/test/java/com/android/bedstead/harrier/DeviceStateTest.java
+++ b/common/device-side/bedstead/harrier/src/test/java/com/android/bedstead/harrier/DeviceStateTest.java
@@ -53,8 +53,10 @@
 
 import com.android.bedstead.harrier.annotations.EnsureBluetoothDisabled;
 import com.android.bedstead.harrier.annotations.EnsureBluetoothEnabled;
+import com.android.bedstead.harrier.annotations.EnsureDemoMode;
 import com.android.bedstead.harrier.annotations.EnsureDoesNotHaveAppOp;
 import com.android.bedstead.harrier.annotations.EnsureDoesNotHavePermission;
+import com.android.bedstead.harrier.annotations.EnsureGlobalSettingSet;
 import com.android.bedstead.harrier.annotations.EnsureHasAppOp;
 import com.android.bedstead.harrier.annotations.EnsureHasNoSecondaryUser;
 import com.android.bedstead.harrier.annotations.EnsureHasNoTvProfile;
@@ -63,6 +65,7 @@
 import com.android.bedstead.harrier.annotations.EnsureHasSecondaryUser;
 import com.android.bedstead.harrier.annotations.EnsureHasTvProfile;
 import com.android.bedstead.harrier.annotations.EnsureHasWorkProfile;
+import com.android.bedstead.harrier.annotations.EnsureNotDemoMode;
 import com.android.bedstead.harrier.annotations.EnsurePackageNotInstalled;
 import com.android.bedstead.harrier.annotations.EnsurePasswordNotSet;
 import com.android.bedstead.harrier.annotations.EnsureScreenIsOn;
@@ -974,4 +977,25 @@
         assertThat(sDeviceState.testApp()
                 .testApp().pkg().appOps().get(OPSTR_START_FOREGROUND)).isEqualTo(ALLOWED);
     }
+
+    @EnsureGlobalSettingSet(key = "testGlobalSetting", value = "testValue")
+    @Test
+    public void ensureGlobalSettingSetAnnotation_globalSettingIsSet() {
+        assertThat(TestApis.settings().global().getString("testGlobalSetting"))
+                .isEqualTo("testValue");
+    }
+
+    @EnsureDemoMode
+    @Test
+    public void ensureDemoModeAnnotation_deviceIsInDemoMode() {
+        assertThat(TestApis.settings().global().getInt("device_demo_mode"))
+                .isEqualTo(1);
+    }
+
+    @EnsureNotDemoMode
+    @Test
+    public void ensureNotDemoModeAnnotation_deviceIsNotInDemoMode() {
+        assertThat(TestApis.settings().global().getInt("device_demo_mode"))
+                .isEqualTo(0);
+    }
 }
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/GestureNavRule.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/GestureNavRule.java
index 9c363d2..f32c682 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/GestureNavRule.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/GestureNavRule.java
@@ -35,6 +35,7 @@
 
 import org.junit.rules.ExternalResource;
 
+import java.io.IOException;
 import java.util.Map;
 
 /**
@@ -44,6 +45,8 @@
     private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
     private static final String NAV_BAR_INTERACTION_MODE_RES_NAME = "config_navBarInteractionMode";
     private static final int NAV_BAR_INTERACTION_MODE_GESTURAL = 2;
+    private static final String GESTURAL_OVERLAY_NAME =
+            "com.android.internal.systemui.navbar.gestural";
 
     /** Most application's res id must be larger than 0x7f000000 */
     public static final int MIN_APPLICATION_RES_ID = 0x7f000000;
@@ -59,6 +62,7 @@
     private String mSystemNavigationTitle;
     private String mGesturePreferenceTitle;
     private boolean mConfiguredInSettings;
+    private boolean mRevertOverlay;
 
     @Override
     protected void before() throws Throwable {
@@ -183,6 +187,19 @@
         if (!hasSystemGestureFeature()) {
             return;
         }
+        try {
+            if (mDevice.executeShellCommand("cmd overlay list").contains(GESTURAL_OVERLAY_NAME)) {
+                mDevice.executeShellCommand("cmd overlay enable " + GESTURAL_OVERLAY_NAME);
+                mDevice.waitForIdle();
+            }
+        } catch (IOException e) {
+            // Do nothing
+        }
+
+        if (isGestureMode()) {
+            mRevertOverlay = true;
+            return;
+        }
 
         // Set up the gesture navigation by enabling it via the Settings app
         boolean isOperatedSettingsToExpectedOption = launchToSettingsSystemGesture();
@@ -214,6 +231,17 @@
             return;
         }
 
+        if (mRevertOverlay) {
+            try {
+                mDevice.executeShellCommand("cmd overlay disable " + GESTURAL_OVERLAY_NAME);
+            } catch (IOException e) {
+                // Do nothing
+            }
+            if (!isGestureMode()) {
+                return;
+            }
+        }
+
         if (mConfiguredInSettings) {
             launchToSettingsSystemGesture();
             for (Map.Entry<String, Boolean> entry : mSystemGestureOptionsMap.entrySet()) {
diff --git a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
index 1993f30..e954ac8 100644
--- a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
+++ b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
@@ -726,6 +726,8 @@
                 PERMISSION_CONTROLLER_APK_IN_APEX_BURNDOWN_LIST)
             .put("/apex/com.android.permission/priv-app/GooglePermissionController/GooglePermissionController.apk",
                 PERMISSION_CONTROLLER_APK_IN_APEX_BURNDOWN_LIST)
+            .put("/apex/com.android.tethering/priv-app/InProcessTethering/InProcessTethering.apk",
+                TETHERING_APK_IN_APEX_BURNDOWN_LIST)
             .put("/apex/com.android.tethering/priv-app/TetheringNextGoogle/TetheringNextGoogle.apk",
                 TETHERING_APK_IN_APEX_BURNDOWN_LIST)
             .put("/apex/com.android.tethering/priv-app/TetheringGoogle/TetheringGoogle.apk",
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java
index ef44158..3f353d0 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java
@@ -810,8 +810,6 @@
                 "verifySignatures_withRotation_succeeds");
     }
 
-    // TODO(b/235407278): fix the prebuilts used for this test and enable it again
-    /*
     @CddTest(requirement="4/C-0-9")
     public void testInstallV41WrongBlockId() throws Exception {
         // V4 is only enabled on devices with Incremental feature
@@ -862,7 +860,6 @@
         assertInstallV4FailsWithError("CtsSignatureQueryService_v2-tgt-33-wrongDigest.apk",
                 "APK digest in V4 signature does not match V2/V3");
     }
-    */
 
     public void testInstallV3KeyRotationSigPerm() throws Exception {
         // tests that a v3 signed APK can still get a signature permission from an app with its
diff --git a/hostsidetests/blobstore/src/com/android/cts/host/blob/BaseBlobStoreHostTest.java b/hostsidetests/blobstore/src/com/android/cts/host/blob/BaseBlobStoreHostTest.java
index fc355af..e9e13a8 100644
--- a/hostsidetests/blobstore/src/com/android/cts/host/blob/BaseBlobStoreHostTest.java
+++ b/hostsidetests/blobstore/src/com/android/cts/host/blob/BaseBlobStoreHostTest.java
@@ -18,6 +18,7 @@
 import static com.google.common.truth.Truth.assertWithMessage;
 
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;
 import com.android.tradefed.util.Pair;
@@ -133,12 +134,25 @@
     protected void addAssistRoleHolder(String pkgName, int userId) throws Exception {
         final String cmd = String.format("cmd role add-role-holder "
                 + "--user %d android.app.role.ASSISTANT %s", userId, pkgName);
-        getDevice().executeShellCommand(cmd).trim();
+        runCommand(cmd);
     }
 
     protected void removeAssistRoleHolder(String pkgName, int userId) throws Exception {
         final String cmd = String.format("cmd role remove-role-holder "
                 + "--user %d android.app.role.ASSISTANT %s", userId, pkgName);
-        getDevice().executeShellCommand(cmd).trim();
+        runCommand(cmd);
+    }
+
+    protected void revokePermission(String pkgName, String permissionName, int userId)
+            throws Exception {
+        final String cmd = String.format("cmd package revoke --user %d %s %s",
+                userId, pkgName, permissionName);
+        runCommand(cmd);
+    }
+
+    protected String runCommand(String command) throws Exception {
+        final String output = getDevice().executeShellCommand(command);
+        CLog.v("Output of cmd '" + command + "': '" + output.trim() + "'");
+        return output;
     }
 }
\ No newline at end of file
diff --git a/hostsidetests/blobstore/src/com/android/cts/host/blob/BlobStoreMultiUserTest.java b/hostsidetests/blobstore/src/com/android/cts/host/blob/BlobStoreMultiUserTest.java
index ec13654..6731383 100644
--- a/hostsidetests/blobstore/src/com/android/cts/host/blob/BlobStoreMultiUserTest.java
+++ b/hostsidetests/blobstore/src/com/android/cts/host/blob/BlobStoreMultiUserTest.java
@@ -15,10 +15,10 @@
  */
 package com.android.cts.host.blob;
 
-import static org.junit.Assume.assumeTrue;
-
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.junit.Assume.assumeTrue;
+
 import com.android.tradefed.invoker.TestInformation;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.AfterClassWithInfo;
@@ -35,6 +35,9 @@
 public class BlobStoreMultiUserTest extends BaseBlobStoreHostTest {
     private static final String TEST_CLASS = TARGET_PKG + ".DataCleanupTest";
 
+    private static final String PERM_ACCESS_BLOBS_ACROSS_USERS =
+            "android.permission.ACCESS_BLOBS_ACROSS_USERS";
+
     private static int mPrimaryUserId;
     private static int mSecondaryUserId;
 
@@ -58,6 +61,10 @@
         // want the ACCESS_BLOBS_ACROSS_USERS permission to be granted by default.
         installPackageAsUser(TARGET_APK_ASSIST, false /* grantPermissions */, mPrimaryUserId);
         installPackageAsUser(TARGET_APK_ASSIST, false /* grantPermissions */, mSecondaryUserId);
+        // Explicitly revoke the permission, in order to deal with
+        // http://b/233710271 which was causing the permission to be pre-granted.
+        revokePermission(TARGET_PKG_ASSIST, PERM_ACCESS_BLOBS_ACROSS_USERS, mPrimaryUserId);
+        revokePermission(TARGET_PKG_ASSIST, PERM_ACCESS_BLOBS_ACROSS_USERS, mSecondaryUserId);
     }
 
     @AfterClassWithInfo
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java
index 31f14cc..1f42d46 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java
@@ -16,7 +16,6 @@
 
 package com.android.cts.devicepolicy;
 
-import com.android.ddmlib.Log.LogLevel;
 import com.android.tradefed.log.LogUtil.CLog;
 
 /**
@@ -33,6 +32,8 @@
     protected static final String LAUNCHER_TESTS_APK = "CtsLauncherAppsTests.apk";
     protected static final String LAUNCHER_TESTS_SUPPORT_PKG =
             "com.android.cts.launchertests.support";
+    protected static final String LAUNCHER_TESTS_SUPPORT_COMPONENT =
+            LAUNCHER_TESTS_SUPPORT_PKG + "/.LauncherCallbackTestsService";
     protected static final String LAUNCHER_TESTS_SUPPORT_APK = "CtsLauncherAppsTestsSupport.apk";
 
     protected void installTestApps(int userId) throws Exception {
@@ -49,7 +50,18 @@
     protected void startCallbackService(int userId) throws Exception {
         String command = "am startservice --user " + userId
                 + " -a " + LAUNCHER_TESTS_SUPPORT_PKG + ".REGISTER_CALLBACK "
-                + LAUNCHER_TESTS_SUPPORT_PKG + "/.LauncherCallbackTestsService";
+                + LAUNCHER_TESTS_SUPPORT_COMPONENT;
         CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
     }
+
+    protected boolean isCallbackServiceReady() throws Exception {
+        String command = "dumpsys activity services " + LAUNCHER_TESTS_SUPPORT_COMPONENT
+                + " | grep 'app=ProcessRecord'";
+        String result = getDevice().executeShellCommand(command);
+        CLog.d("Check service started by " + command + ": " + result);
+        if (result.isEmpty()) {
+            return false;
+        }
+        return true;
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java
index 73f6204..6e9bae5 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java
@@ -104,6 +104,9 @@
         }
         installAppAsUser(SIMPLE_APP_APK, mCurrentUserId);
         startCallbackService(mCurrentUserId);
+        while (!isCallbackServiceReady()) {
+            Thread.sleep(100);
+        }
         getDevice().uninstallPackage(SIMPLE_APP_PKG);
         runDeviceTestsAsUser(LAUNCHER_TESTS_PKG,
                 LAUNCHER_TESTS_CLASS,
diff --git a/hostsidetests/statsdatom/src/android/cts/statsdatom/lib/ConfigUtils.java b/hostsidetests/statsdatom/src/android/cts/statsdatom/lib/ConfigUtils.java
index 23ffc03..be665ba 100644
--- a/hostsidetests/statsdatom/src/android/cts/statsdatom/lib/ConfigUtils.java
+++ b/hostsidetests/statsdatom/src/android/cts/statsdatom/lib/ConfigUtils.java
@@ -68,8 +68,10 @@
                 .setId(CONFIG_ID)
                 .addAllowedLogSource("AID_SYSTEM")
                 .addAllowedLogSource("AID_BLUETOOTH")
-                // TODO(b/134091167): Fix bluetooth source name issue in Auto platform.
+                .addAllowedLogSource("com.android.bluetooth")
+                // TODO(b/236681553): Remove this.
                 .addAllowedLogSource("com.android.bluetooth.services")
+                // TODO(b/236681553): Remove this.
                 .addAllowedLogSource("com.google.android.bluetooth.services")
                 .addAllowedLogSource("AID_LMKD")
                 .addAllowedLogSource("AID_MEDIA")
diff --git a/hostsidetests/statsdatom/src/android/cts/statsdatom/sizecompatrestartbutton/SizeCompatRestartButtonStatsTests.java b/hostsidetests/statsdatom/src/android/cts/statsdatom/sizecompatrestartbutton/SizeCompatRestartButtonStatsTests.java
index a6aaebf..68a7135 100644
--- a/hostsidetests/statsdatom/src/android/cts/statsdatom/sizecompatrestartbutton/SizeCompatRestartButtonStatsTests.java
+++ b/hostsidetests/statsdatom/src/android/cts/statsdatom/sizecompatrestartbutton/SizeCompatRestartButtonStatsTests.java
@@ -28,9 +28,11 @@
 import com.android.os.AtomsProto.SizeCompatRestartButtonEventReported.Event;
 import com.android.os.StatsLog;
 import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.util.Pair;
 
 import java.util.Arrays;
 import java.util.List;
@@ -104,6 +106,11 @@
             return;
         }
 
+        Pair<Integer, Integer> displaySizeClosed = getDisplayRealSize(getDevice());
+        if (displaySizeClosed == null) {
+            CLog.i("Could not determine display size while CLOSED.");
+            return;
+        }
         try (AutoCloseable a = DeviceUtils.withActivity(getDevice(),
                 DeviceUtils.STATSD_ATOM_TEST_PKG, NON_RESIZEABLE_PORTRAIT_ACTIVITY, "action",
                 "action.sleep_top")) {
@@ -112,6 +119,15 @@
             Thread.sleep(AtomTestUtils.WAIT_TIME_LONG);
         }
 
+        Pair<Integer, Integer> displaySizeOpened = getDisplayRealSize(getDevice());
+        if (displaySizeOpened == null) {
+            CLog.i("Could not determine display size while OPENED.");
+            return;
+        }
+        if (displaySizeClosed.equals(displaySizeOpened)) {
+            CLog.i("Display size has not changed.");
+            return;
+        }
         List<StatsLog.EventMetricData> data = ReportUtils.getEventMetricDataList(getDevice());
         assertThat(data.size()).isEqualTo(1);
 
@@ -127,4 +143,25 @@
                 .map(Integer::valueOf)
                 .anyMatch(availableState -> availableState == state);
     }
+
+    /**
+     * Returns the physical size of the current display used.
+     */
+    private Pair<Integer, Integer> getDisplayRealSize(ITestDevice device) throws Exception {
+        final String physicalSize = "Physical size: ";
+        String str = device.executeShellCommand("wm size");
+        if (!str.isEmpty()) {
+            String[] lines = str.split(System.getProperty("line.separator"));
+            for (String s : lines) {
+                if (s.contains(physicalSize)) {
+                    String substring = s.substring(physicalSize.length());
+                    if (!substring.isEmpty()) {
+                        return Pair.create(Integer.parseInt(substring.split("x")[0]),
+                                Integer.parseInt(substring.split("x")[1]));
+                    }
+                }
+            }
+        }
+        return null;
+    }
 }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/NotTouchableWindowTestActivity.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/NotTouchableWindowTestActivity.java
index f4ec5b8..9aca75f 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/NotTouchableWindowTestActivity.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/NotTouchableWindowTestActivity.java
@@ -118,7 +118,7 @@
                 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
         params.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
-
+        params.setFitInsetsTypes(0);
         params.gravity = Gravity.TOP;
         params.setTitle(NON_TOUCHABLE_WINDOW_TITLE);
 
diff --git a/tests/devicepolicy/src/android/devicepolicy/cts/SettingsTest.java b/tests/devicepolicy/src/android/devicepolicy/cts/SettingsTest.java
index a0d37e8..fa1a68f 100644
--- a/tests/devicepolicy/src/android/devicepolicy/cts/SettingsTest.java
+++ b/tests/devicepolicy/src/android/devicepolicy/cts/SettingsTest.java
@@ -28,6 +28,7 @@
 
 import com.android.bedstead.harrier.BedsteadJUnit4;
 import com.android.bedstead.harrier.DeviceState;
+import com.android.bedstead.harrier.annotations.EnsureNotDemoMode;
 import com.android.bedstead.harrier.annotations.Postsubmit;
 import com.android.bedstead.harrier.annotations.enterprise.CanSetPolicyTest;
 import com.android.bedstead.harrier.annotations.enterprise.CannotSetPolicyTest;
@@ -85,6 +86,7 @@
 
     @CanSetPolicyTest(policy = SetGlobalSetting.class)
     @Postsubmit(reason = "new test")
+    @EnsureNotDemoMode // retail demo mode bypasses global setting allowlist
     public void setGlobalSetting_unsupported_throwsSecurityException() {
         assertThrows(SecurityException.class,
                 () -> sDeviceState.dpc().devicePolicyManager().setGlobalSetting(
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricActivityTests.java b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricActivityTests.java
index 07d6cc8..2f7339a 100644
--- a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricActivityTests.java
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricActivityTests.java
@@ -40,6 +40,7 @@
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 
+import org.junit.Ignore;
 import org.junit.Test;
 
 /**
@@ -237,6 +238,8 @@
         assertEquals(callbackState.toString(), 1, callbackState.mNumAuthRejected);
     }
 
+    // TODO(b/236763921): fix this test and unignore.
+    @Ignore
     @Test
     public void testBiometricOnly_negativeButtonInvoked() throws Exception {
         assumeTrue(Utils.isFirstApiLevel29orGreater());
@@ -285,6 +288,8 @@
     }
 
 
+    // TODO(b/236763921): fix this test and unignore.
+    @Ignore
     @Test
     public void testBiometricOrCredential_credentialButtonInvoked_biometricEnrolled()
             throws Exception {
diff --git a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricSimpleTests.java b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricSimpleTests.java
index fd42e71..30af1e7 100644
--- a/tests/framework/base/biometrics/src/android/server/biometrics/BiometricSimpleTests.java
+++ b/tests/framework/base/biometrics/src/android/server/biometrics/BiometricSimpleTests.java
@@ -43,6 +43,7 @@
 
 import com.android.server.biometrics.nano.SensorStateProto;
 
+import org.junit.Ignore;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
 
@@ -301,7 +302,10 @@
      *
      * Upon successful authentication, checks that the result is
      * {@link BiometricPrompt#AUTHENTICATION_RESULT_TYPE_BIOMETRIC}
+     *
+     * TODO(b/236763921): fix this test and unignore.
      */
+    @Ignore
     @Test
     public void testSimpleBiometricAuth_nonConvenience() throws Exception {
         assumeTrue(Utils.isFirstApiLevel29orGreater());
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
index b2790bb..719e666 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
@@ -286,6 +286,8 @@
         }
         final SizeInfo dockedSizes = getLastReportedSizesForActivity(activityName);
         assertSizesAreSane(initialFullscreenSizes, dockedSizes);
+        final boolean orientationChanged =
+                initialFullscreenSizes.orientation != dockedSizes.orientation;
 
         separateTestJournal();
         // Restore to fullscreen.
@@ -298,10 +300,17 @@
         // (dock task was minimized), start the activity again to ensure the activity is at
         // foreground.
         launchActivity(activityName, WINDOWING_MODE_FULLSCREEN);
-        assertActivityLifecycle(activityName, relaunch);
-        final SizeInfo finalFullscreenSizes = getLastReportedSizesForActivity(activityName);
+        if (relaunch && !orientationChanged) {
+            // If there is no orientation changes while moving the non-resizeable activity out of
+            // the split, the Activity won't be relaunched because size changes won't cross the
+            // size config buckets. So, there won't be any lifecycle changes.
+            waitForOnMultiWindowModeChanged(activityName);
+        } else {
+            assertActivityLifecycle(activityName, relaunch);
+        }
 
-        // After activity configuration was changed twice it must report same size as original one.
+        // It must report same size as original one after split-screen dismissed.
+        final SizeInfo finalFullscreenSizes = getLastReportedSizesForActivity(activityName);
         assertSizesAreSame(initialFullscreenSizes, finalFullscreenSizes);
     }
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyGestureTest.java b/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyGestureTest.java
new file mode 100644
index 0000000..b52eca0
--- /dev/null
+++ b/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyGestureTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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 android.server.wm;
+
+import static android.server.wm.WindowManagerState.STATE_RESUMED;
+import static android.server.wm.WindowManagerState.STATE_STOPPED;
+import static android.server.wm.backlegacyapp.Components.BACK_LEGACY;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.app.Instrumentation;
+import android.server.wm.TestJournalProvider.TestJournalContainer;
+import android.server.wm.backlegacyapp.Components;
+import android.support.test.uiautomator.UiDevice;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.GestureNavRule;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+
+/**
+ * Integration test for back navigation legacy mode
+ */
+public class BackNavigationLegacyGestureTest extends ActivityManagerTestBase {
+    private Instrumentation mInstrumentation;
+
+    @ClassRule
+    public static GestureNavRule GESTURE_NAV_RULE = new GestureNavRule();
+    private UiDevice mUiDevice;
+
+    @Before
+    public void setup() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+
+    }
+
+    @Test
+    public void receiveOnBackPressed() {
+        TestJournalContainer.start();
+        launchActivity(BACK_LEGACY);
+        mWmState.assertActivityDisplayed(BACK_LEGACY);
+        waitAndAssertActivityState(BACK_LEGACY, STATE_RESUMED, "Activity should be resumed");
+        mUiDevice = UiDevice.getInstance(mInstrumentation);
+        doBackGesture();
+        waitAndAssertActivityState(BACK_LEGACY, STATE_STOPPED, "Activity should be stopped");
+        assertTrue("OnBackPressed should have been called",
+                TestJournalContainer.get(BACK_LEGACY).extras.getBoolean(
+                        Components.KEY_ON_BACK_PRESSED_CALLED));
+        assertFalse("OnBackInvoked should not have been called",
+                TestJournalContainer.get(BACK_LEGACY).extras.getBoolean(
+                        Components.KEY_ON_BACK_INVOKED_CALLED));
+    }
+
+    /**
+     * Do a back gesture. (Swipe)
+     */
+    private void doBackGesture() {
+        int midHeight = mUiDevice.getDisplayHeight() / 2;
+        int midWidth = mUiDevice.getDisplayWidth() / 2;
+        mUiDevice.swipe(0, midHeight, midWidth, midHeight, 100);
+        mUiDevice.waitForIdle();
+    }
+}
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyTest.java b/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyTest.java
index 38d9e62..e7d6ba8 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/BackNavigationLegacyTest.java
@@ -16,6 +16,7 @@
 package android.server.wm;
 
 import static android.server.wm.WindowManagerState.STATE_RESUMED;
+import static android.server.wm.WindowManagerState.STATE_STOPPED;
 import static android.server.wm.backlegacyapp.Components.BACK_LEGACY;
 
 import static org.junit.Assert.assertFalse;
@@ -38,6 +39,8 @@
 public class BackNavigationLegacyTest extends ActivityManagerTestBase {
     private Instrumentation mInstrumentation;
 
+    private UiDevice mUiDevice;
+
     @Before
     public void setup() {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -50,7 +53,9 @@
         launchActivity(BACK_LEGACY);
         mWmState.assertActivityDisplayed(BACK_LEGACY);
         waitAndAssertActivityState(BACK_LEGACY, STATE_RESUMED, "Activity should be resumed");
-        UiDevice.getInstance(mInstrumentation).pressKeyCode(KeyEvent.KEYCODE_BACK);
+        mUiDevice = UiDevice.getInstance(mInstrumentation);
+        mUiDevice.pressKeyCode(KeyEvent.KEYCODE_BACK);
+        waitAndAssertActivityState(BACK_LEGACY, STATE_STOPPED, "Activity should be stopped");
         assertTrue("OnBackPressed should have been called",
                 TestJournalContainer.get(BACK_LEGACY).extras.getBoolean(
                         Components.KEY_ON_BACK_PRESSED_CALLED));
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java
index 784003b..08b8204 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java
@@ -174,20 +174,6 @@
     }
 
     @Test
-    public void testDismissKeyguardIfInsecure_notAllowed() {
-        final LockScreenSession lockScreenSession = createManagedLockScreenSession();
-        lockScreenSession.setLockCredential().gotoKeyguard();
-
-        mWmState.assertKeyguardShowingAndNotOccluded();
-        launchActivityWithDismissKeyguardIfInsecure(SHOW_WHEN_LOCKED_ACTIVITY);
-        mWmState.computeState(SHOW_WHEN_LOCKED_ACTIVITY);
-        mWmState.assertVisibility(SHOW_WHEN_LOCKED_ACTIVITY, true);
-
-        // Make sure we stay on Keyguard.
-        mWmState.assertKeyguardShowingAndOccluded();
-    }
-
-    @Test
     public void testDismissKeyguardActivity_method() {
         final LockScreenSession lockScreenSession = createManagedLockScreenSession();
         lockScreenSession.setLockCredential();
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardTransitionTests.java b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardTransitionTests.java
index bac67d2..b585c04 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardTransitionTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardTransitionTests.java
@@ -106,15 +106,6 @@
     }
 
     @Test
-    public void testDismissKeyguardIfInsecure() {
-        createManagedLockScreenSession().gotoKeyguard();
-        launchActivityWithDismissKeyguardIfInsecure(SHOW_WHEN_LOCKED_NO_PREVIEW_ACTIVITY);
-        mWmState.computeState(SHOW_WHEN_LOCKED_NO_PREVIEW_ACTIVITY);
-        assertEquals("Picked wrong transition", TRANSIT_KEYGUARD_GOING_AWAY,
-                mWmState.getDefaultDisplayLastTransition());
-    }
-
-    @Test
     public void testNewActivityDuringOccluded() {
         final LockScreenSession lockScreenSession = createManagedLockScreenSession();
         launchActivity(SHOW_WHEN_LOCKED_NO_PREVIEW_ACTIVITY);
@@ -126,18 +117,6 @@
     }
 
     @Test
-    public void testNewDismissKeyguardIfInsecureActivityDuringOccluded() {
-        final LockScreenSession lockScreenSession = createManagedLockScreenSession();
-        launchActivity(SHOW_WHEN_LOCKED_NO_PREVIEW_ACTIVITY);
-        lockScreenSession.gotoKeyguard(SHOW_WHEN_LOCKED_NO_PREVIEW_ACTIVITY);
-        launchActivityWithDismissKeyguardIfInsecure(
-                SHOW_WHEN_LOCKED_WITH_DIALOG_NO_PREVIEW_ACTIVITY);
-        mWmState.computeState(SHOW_WHEN_LOCKED_WITH_DIALOG_NO_PREVIEW_ACTIVITY);
-        assertEquals("Picked wrong transition", TRANSIT_ACTIVITY_OPEN,
-                mWmState.getDefaultDisplayLastTransition());
-    }
-
-    @Test
     public void testOccludeManifestAttr() {
         final LockScreenSession lockScreenSession = createManagedLockScreenSession();
         lockScreenSession.gotoKeyguard();
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java
index be709b4..cfc30ec 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java
@@ -61,6 +61,11 @@
     private static final String STRICT_MODE_ENABLED = "StrictModeEnabled";
     private static final String VERIFY_CONTEXT_APIS_IN_ON_CREATE = "VerifyContextApisInOnCreate";
 
+    /**
+     * Simulate the manifest flag enableOnBackInvokedCallback being true for the IME.
+     */
+    private static final String ON_BACK_CALLBACK_ENABLED = "onBackCallbackEnabled";
+
     @NonNull
     private final PersistableBundle mBundle;
 
@@ -182,6 +187,10 @@
         return mBundle.getBoolean(VERIFY_CONTEXT_APIS_IN_ON_CREATE, false);
     }
 
+    public boolean isOnBackCallbackEnabled() {
+        return mBundle.getBoolean(ON_BACK_CALLBACK_ENABLED, false);
+    }
+
     static Bundle serializeToBundle(@NonNull String eventCallbackActionName,
             @Nullable Builder builder) {
         final Bundle result = new Bundle();
@@ -363,5 +372,15 @@
             mBundle.putBoolean(VERIFY_CONTEXT_APIS_IN_ON_CREATE, enabled);
             return this;
         }
+
+        /**
+         * Sets whether the IME's
+         * {@link android.content.pm.ApplicationInfo#isOnBackInvokedCallbackEnabled()}
+         * should be set to {@code true}.
+         */
+        public Builder setOnBackCallbackEnabled(boolean enabled) {
+            mBundle.putBoolean(ON_BACK_CALLBACK_ENABLED, enabled);
+            return this;
+        }
     }
 }
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
index fc4c05e..528da58 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
@@ -426,10 +426,6 @@
                             return e;
                         }
                     }
-                    case "setEnableOnBackInvokedCallback":
-                        boolean isEnabled = command.getExtras().getBoolean("isEnabled");
-                        getApplicationInfo().setEnableOnBackInvokedCallback(isEnabled);
-                        return ImeEvent.RETURN_VALUE_UNAVAILABLE;
                     case "getDisplayId":
                         return getDisplay().getDisplayId();
                     case "verifyLayoutInflaterContext":
@@ -679,6 +675,10 @@
                             .build());
         }
 
+        if (mSettings.isOnBackCallbackEnabled()) {
+            getApplicationInfo().setEnableOnBackInvokedCallback(true);
+        }
+
         getTracer().onCreate(() -> {
             super.onCreate();
             mHandlerThread.start();
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java
index ac95dc8..d79dcca 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java
@@ -51,6 +51,7 @@
 import android.app.AlertDialog;
 import android.app.Instrumentation;
 import android.app.compat.CompatChanges;
+import android.content.Context;
 import android.content.pm.PackageManager;
 import android.graphics.Color;
 import android.os.SystemClock;
@@ -245,27 +246,38 @@
     }
 
     private void verifyHideImeBackPressed(
-            boolean appRequestsLegacy, boolean imeRequestsLegacy) throws Exception {
+            boolean appRequestsBackCallback, boolean imeRequestsBackCallback) throws Exception {
         final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
-        final InputMethodManager imm = InstrumentationRegistry.getInstrumentation()
-                .getTargetContext().getSystemService(InputMethodManager.class);
+        final Context context = instrumentation.getTargetContext();
+        final InputMethodManager imm = context.getSystemService(InputMethodManager.class);
+
+        // Whether 'OnBackInvokedCallback' or 'onBackPressed' (legacy back) is used is defined by
+        // the 'enableOnBackInvokedCallback' flag in the Application manifest.
+        // Registering a callback is only authorized if the flag is set to true. Since the
+        // WindowOnBackDispatcher is created at the same time as the ViewRootImpl, for test purpose,
+        // we need to manually set the flag on ApplicationInfo before the window is created which
+        // happens during the MockIme creation and TestActivity creation.
 
         try (MockImeSession imeSession = MockImeSession.create(
                 instrumentation.getContext(),
                 instrumentation.getUiAutomation(),
-                new ImeSettings.Builder())) {
+                new ImeSettings.Builder()
+                        .setOnBackCallbackEnabled(imeRequestsBackCallback)
+        )) {
             final ImeEventStream stream = imeSession.openEventStream();
 
             final String marker = getTestMarker();
+
+            if (appRequestsBackCallback) {
+                context.getApplicationInfo().setEnableOnBackInvokedCallback(true);
+            }
+
             final EditText editText = launchTestActivity(marker);
             final TestActivity testActivity = (TestActivity) editText.getContext();
-            if (appRequestsLegacy) {
-                testActivity.getApplicationInfo().setEnableOnBackInvokedCallback(true);
+
+            if (!appRequestsBackCallback) {
                 testActivity.setIgnoreBackKey(true);
             }
-            if (imeRequestsLegacy) {
-                imeSession.callSetEnableOnBackInvokedCallback(true);
-            }
 
             expectEvent(stream, editorMatcher("onStartInput", marker), TIMEOUT);
             notExpectEvent(stream, editorMatcher("onStartInputView", marker), TIMEOUT);
@@ -296,22 +308,26 @@
 
     @Test
     public void testHideImeAfterBackPressed_legacyAppLegacyIme() throws Exception {
-        verifyHideImeBackPressed(true /* appRequestsLegacy */, true /* imeRequestsLegacy */);
+        verifyHideImeBackPressed(false/* appRequestsBackCallback */,
+                false/* imeRequestsBackCallback */);
     }
 
     @Test
     public void testHideImeAfterBackPressed_migratedAppLegacyIme() throws Exception {
-        verifyHideImeBackPressed(false /* appRequestsLegacy */, true /* imeRequestsLegacy */);
+        verifyHideImeBackPressed(true/* appRequestsBackCallback */,
+                false/* imeRequestsBackCallback */);
     }
 
     @Test
     public void testHideImeAfterBackPressed_migratedAppMigratedIme() throws Exception {
-        verifyHideImeBackPressed(false /* appRequestsLegacy */, false /* imeRequestsLegacy */);
+        verifyHideImeBackPressed(true/* appRequestsBackCallback */,
+                true/* imeRequestsBackCallback */);
     }
 
     @Test
     public void testHideImeAfterBackPressed_legacyAppMigratedIme() throws Exception {
-        verifyHideImeBackPressed(true /* appRequestsLegacy */, false /* imeRequestsLegacy */);
+        verifyHideImeBackPressed(false/* appRequestsBackCallback */,
+                true/* imeRequestsBackCallback */);
     }
 
     @Test
diff --git a/tests/media/AndroidTest.xml b/tests/media/AndroidTest.xml
index 6dc4631..588ddf8 100644
--- a/tests/media/AndroidTest.xml
+++ b/tests/media/AndroidTest.xml
@@ -26,7 +26,7 @@
     </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.MediaPreparer">
         <option name="push-all" value="true" />
-        <option name="media-folder-name" value="CtsMediaV2TestCases-2.3" />
+        <option name="media-folder-name" value="CtsMediaV2TestCases-2.4" />
         <option name="dynamic-config-module" value="CtsMediaV2TestCases" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
diff --git a/tests/media/DynamicConfig.xml b/tests/media/DynamicConfig.xml
index 74f76c5..72f13e0 100644
--- a/tests/media/DynamicConfig.xml
+++ b/tests/media/DynamicConfig.xml
@@ -1,5 +1,5 @@
 <dynamicConfig>
     <entry key="media_files_url">
-      <value>https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-2.3.zip</value>
+      <value>https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-2.4.zip</value>
     </entry>
 </dynamicConfig>
diff --git a/tests/media/README.md b/tests/media/README.md
index 00fd0c1..525379c 100644
--- a/tests/media/README.md
+++ b/tests/media/README.md
@@ -3,7 +3,7 @@
 
 The aim of these tests is not solely to verify the CDD requirements but also to test components, their plugins and their interactions with media framework.
 
-The test vectors used by the test suite is available at [link](https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-2.3.zip) and is downloaded automatically while running tests. Manual installation of these can be done using copy_media.sh script in this directory.
+The test vectors used by the test suite is available at [link](https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-2.4.zip) and is downloaded automatically while running tests. Manual installation of these can be done using copy_media.sh script in this directory.
 
 All Big Buck Bunny(bbb) test vectors are of 8-bit format. They are downloaded from [link](https://peach.blender.org/download/) and resampled according to the test requirements.
 All Cosmos Laundromat(cosmat) test vectors are of 10-bit format. They are downloaded from [link](https://media.xiph.org/) and resampled according to the test requirements.
diff --git a/tests/media/copy_media.sh b/tests/media/copy_media.sh
index df67e307..d7e5d88 100755
--- a/tests/media/copy_media.sh
+++ b/tests/media/copy_media.sh
@@ -17,7 +17,7 @@
 ## script to install mediav2 test files manually
 
 adbOptions=" "
-resLabel=CtsMediaV2TestCases-2.3
+resLabel=CtsMediaV2TestCases-2.4
 srcDir="/tmp/$resLabel"
 tgtDir="/sdcard/test"
 usage="Usage: $0 [-h] [-s serial]"
diff --git a/tests/media/src/android/mediav2/cts/DecodeGlAccuracyTest.java b/tests/media/src/android/mediav2/cts/DecodeGlAccuracyTest.java
index eff5860..96836e6 100644
--- a/tests/media/src/android/mediav2/cts/DecodeGlAccuracyTest.java
+++ b/tests/media/src/android/mediav2/cts/DecodeGlAccuracyTest.java
@@ -222,23 +222,23 @@
                         MediaFormat.COLOR_TRANSFER_SDR_VIDEO},
 
                 // 601FR
-                {MediaFormat.MIMETYPE_VIDEO_AVC, "color_bands_176x176_h264_8bit.mp4",
+                {MediaFormat.MIMETYPE_VIDEO_AVC, "color_bands_176x176_h264_8bit_fr.mp4",
                         MediaFormat.COLOR_RANGE_FULL,
                         MediaFormat.COLOR_STANDARD_BT601_NTSC,
                         MediaFormat.COLOR_TRANSFER_SDR_VIDEO},
-                {MediaFormat.MIMETYPE_VIDEO_HEVC, "color_bands_176x176_hevc_8bit.mp4",
+                {MediaFormat.MIMETYPE_VIDEO_HEVC, "color_bands_176x176_hevc_8bit_fr.mp4",
                         MediaFormat.COLOR_RANGE_FULL,
                         MediaFormat.COLOR_STANDARD_BT601_NTSC,
                         MediaFormat.COLOR_TRANSFER_SDR_VIDEO},
-                {MediaFormat.MIMETYPE_VIDEO_VP8, "color_bands_176x176_vp8_8bit.webm",
+                {MediaFormat.MIMETYPE_VIDEO_VP8, "color_bands_176x176_vp8_8bit_fr.webm",
                         MediaFormat.COLOR_RANGE_FULL,
                         MediaFormat.COLOR_STANDARD_BT601_NTSC,
                         MediaFormat.COLOR_TRANSFER_SDR_VIDEO},
-                {MediaFormat.MIMETYPE_VIDEO_VP9, "color_bands_176x176_vp9_8bit.webm",
+                {MediaFormat.MIMETYPE_VIDEO_VP9, "color_bands_176x176_vp9_8bit_fr.webm",
                         MediaFormat.COLOR_RANGE_FULL,
                         MediaFormat.COLOR_STANDARD_BT601_NTSC,
                         MediaFormat.COLOR_TRANSFER_SDR_VIDEO},
-                {MediaFormat.MIMETYPE_VIDEO_AV1, "color_bands_176x176_av1_8bit.webm",
+                {MediaFormat.MIMETYPE_VIDEO_AV1, "color_bands_176x176_av1_8bit_fr.webm",
                         MediaFormat.COLOR_RANGE_FULL,
                         MediaFormat.COLOR_STANDARD_BT601_NTSC,
                         MediaFormat.COLOR_TRANSFER_SDR_VIDEO},
diff --git a/tests/media/src/android/mediav2/cts/WorkDir.java b/tests/media/src/android/mediav2/cts/WorkDir.java
index 9011b62..774595c 100644
--- a/tests/media/src/android/mediav2/cts/WorkDir.java
+++ b/tests/media/src/android/mediav2/cts/WorkDir.java
@@ -40,7 +40,7 @@
             // user has specified the mediaDirString via instrumentation-arg
             return mediaDirString + ((mediaDirString.endsWith("/")) ? "" : "/");
         } else {
-            return (getTopDirString() + "test/CtsMediaV2TestCases-2.3/");
+            return (getTopDirString() + "test/CtsMediaV2TestCases-2.4/");
         }
     }
 }
diff --git a/tests/tests/companion/uiautomation/src/android/companion/cts/uiautomation/UiAutomationTestBase.kt b/tests/tests/companion/uiautomation/src/android/companion/cts/uiautomation/UiAutomationTestBase.kt
index c961624..0919575 100644
--- a/tests/tests/companion/uiautomation/src/android/companion/cts/uiautomation/UiAutomationTestBase.kt
+++ b/tests/tests/companion/uiautomation/src/android/companion/cts/uiautomation/UiAutomationTestBase.kt
@@ -159,9 +159,11 @@
     }
 
     protected fun test_timeout(singleDevice: Boolean = false) {
-        setDiscoveryTimeout(1.seconds)
+        // Set discovery timeout to 2 seconds to avoid flaky that
+        // there's a chance CDM UI is disappeared before waitUntilVisible
+        // is called.
+        setDiscoveryTimeout(2.seconds)
 
-        // The discovery timeout is 1 sec, but let's give it 2.
         callback.assertInvokedByActions(2.seconds) {
             // Make sure no device will match the request
             sendRequestAndLaunchConfirmation(
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
index 9600df2..4766268 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
@@ -35,6 +35,8 @@
 import android.graphics.BitmapFactory.Options;
 import android.graphics.Color;
 import android.graphics.Rect;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecList;
 import android.media.MediaFormat;
 import android.os.Build;
 import android.os.Parcel;
@@ -1010,9 +1012,8 @@
     public void testDecode10BitHEIFTo10BitBitmap() {
         assumeTrue(
             "Test needs Android T.", ApiLevelUtil.isFirstApiAtLeast(Build.VERSION_CODES.TIRAMISU));
-        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
-            return;
-        }
+        assumeTrue("No 10-bit HEVC decoder, skip the test.", has10BitHEVCDecoder());
+
         BitmapFactory.Options opt = new BitmapFactory.Options();
         opt.inPreferredConfig = Config.RGBA_1010102;
         Bitmap bm = BitmapFactory.decodeStream(obtainInputStream(R.raw.heifimage_10bit), null, opt);
@@ -1027,9 +1028,8 @@
     public void testDecode10BitHEIFTo8BitBitmap() {
         assumeTrue(
             "Test needs Android T.", ApiLevelUtil.isFirstApiAtLeast(Build.VERSION_CODES.TIRAMISU));
-        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
-            return;
-        }
+        assumeTrue("No 10-bit HEVC decoder, skip the test.", has10BitHEVCDecoder());
+
         BitmapFactory.Options opt = new BitmapFactory.Options();
         opt.inPreferredConfig = Config.ARGB_8888;
         Bitmap bm1 =
@@ -1091,4 +1091,19 @@
     private String obtainPath() throws IOException {
         return Utils.obtainPath(R.drawable.start, 0);
     }
+
+    private static boolean has10BitHEVCDecoder() {
+        MediaFormat format = new MediaFormat();
+        format.setString(MediaFormat.KEY_MIME, "video/hevc");
+        format.setInteger(
+            MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.HEVCProfileMain10);
+        format.setInteger(
+            MediaFormat.KEY_LEVEL, MediaCodecInfo.CodecProfileLevel.HEVCMainTierLevel5);
+
+        MediaCodecList mcl = new MediaCodecList(MediaCodecList.ALL_CODECS);
+        if (mcl.findDecoderForFormat(format) == null) {
+            return false;
+        }
+        return true;
+    }
 }
diff --git a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
index 5b179d6..6741c07 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
@@ -44,6 +44,8 @@
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.NinePatchDrawable;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecList;
 import android.media.MediaFormat;
 import android.net.Uri;
 import android.os.Build;
@@ -244,9 +246,8 @@
     public void testDecode10BitHeif() {
         assumeTrue(
             "Test needs Android T.", ApiLevelUtil.isFirstApiAtLeast(Build.VERSION_CODES.TIRAMISU));
-        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
-            return;
-        }
+        assumeTrue("No 10-bit HEVC decoder, skip the test.", has10BitHEVCDecoder());
+
         try {
             ImageDecoder.Source src = ImageDecoder
                 .createSource(getResources(), R.raw.heifimage_10bit);
@@ -266,9 +267,8 @@
     @Test
     @RequiresDevice
     public void testDecode10BitHeifWithLowRam() {
-        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
-            return;
-        }
+        assumeTrue("No 10-bit HEVC decoder, skip the test.", has10BitHEVCDecoder());
+
         ImageDecoder.Source src = ImageDecoder.createSource(getResources(), R.raw.heifimage_10bit);
         assertNotNull(src);
         try {
@@ -2770,4 +2770,19 @@
         ImageDecoder.Source src = ImageDecoder.createSource(() -> null);
         ImageDecoder.decodeDrawable(src);
     }
+
+    private static boolean has10BitHEVCDecoder() {
+        MediaFormat format = new MediaFormat();
+        format.setString(MediaFormat.KEY_MIME, "video/hevc");
+        format.setInteger(
+            MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.HEVCProfileMain10);
+        format.setInteger(
+            MediaFormat.KEY_LEVEL, MediaCodecInfo.CodecProfileLevel.HEVCMainTierLevel5);
+
+        MediaCodecList mcl = new MediaCodecList(MediaCodecList.ALL_CODECS);
+        if (mcl.findDecoderForFormat(format) == null) {
+            return false;
+        }
+        return true;
+    }
 }
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index ae87bdc..043b5de 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -1104,7 +1104,10 @@
             boolean requireCreationDateTime =
                 attestation.getKeymasterVersion() >= Attestation.KM_VERSION_KEYMINT_1;
 
-            if (requireCreationDateTime || creationDateTime != null) {
+            // b/232078430: skip time checks in Android T due to unfixed bug.
+            boolean doTimeChecks = false;
+
+            if (doTimeChecks && (requireCreationDateTime || creationDateTime != null)) {
                 assertNotNull(creationDateTime);
 
                 assertTrue("Test start time (" + startTime.getTime() + ") and key creation time (" +
@@ -1489,6 +1492,7 @@
     public static void verifyCertificateChain(Certificate[] certChain, boolean expectStrongBox)
             throws GeneralSecurityException {
         assertNotNull(certChain);
+        boolean strongBoxSubjectFound = false;
         for (int i = 1; i < certChain.length; ++i) {
             try {
                 PublicKey pubKey = certChain[i].getPublicKey();
@@ -1515,19 +1519,19 @@
                 if (i == 1) {
                     // First cert should have subject "CN=Android Keystore Key".
                     assertEquals(signedCertSubject, new X500Name("CN=Android Keystore Key"));
-                } else {
-                    // Only strongbox implementations should have strongbox in the subject line
-                    assertEquals(expectStrongBox, signedCertSubject.toString()
-                                                                   .toLowerCase()
-                                                                   .contains("strongbox"));
+                } else if (signedCertSubject.toString().toLowerCase().contains("strongbox")) {
+                    strongBoxSubjectFound = true;
                 }
             } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException
                     | NoSuchProviderException | SignatureException e) {
                 throw new GeneralSecurityException("Using StrongBox: " + expectStrongBox + "\n"
-                        + "Failed to verify certificate "
-                        + certChain[i - 1] + " with public key " + certChain[i].getPublicKey(), e);
+                                + "Failed to verify certificate " + certChain[i - 1]
+                                + " with public key " + certChain[i].getPublicKey(),
+                        e);
             }
         }
+        // At least one intermediate in a StrongBox chain must have "strongbox" in the subject.
+        assertEquals(expectStrongBox, strongBoxSubjectFound);
     }
 
     private void testDeviceIdAttestationFailure(int idType,
diff --git a/tests/tests/widget/src/android/widget/cts/BackInvokedOnWidgetsTest.java b/tests/tests/widget/src/android/widget/cts/BackInvokedOnWidgetsTest.java
index dc56f57..7f76912 100644
--- a/tests/tests/widget/src/android/widget/cts/BackInvokedOnWidgetsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/BackInvokedOnWidgetsTest.java
@@ -36,7 +36,6 @@
 
 import org.junit.Before;
 import org.junit.ClassRule;
-import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -62,7 +61,6 @@
         mUiDevice = UiDevice.getInstance(mInstrumentation);
     }
 
-    @Ignore("b/229946481")
     @Test
     public void popupWindowDismissedOnBackGesture() {
         PopupWindow[] popupWindow = new PopupWindow[1];