Merge "update cect_4_2_2_ignoreMessagesFromAddressF" into android13-tests-dev
diff --git a/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py b/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py
index 257ff3e..92d6f86 100644
--- a/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py
+++ b/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py
@@ -85,7 +85,8 @@
       props = cam.override_with_hidden_physical_camera_props(props)
       camera_properties_utils.skip_unless(
           camera_properties_utils.compute_target_exposure(props) and
-          camera_properties_utils.per_frame_control(props))
+          camera_properties_utils.per_frame_control(props) and
+          camera_properties_utils.tonemap_mode(props, 0))
       log_path = self.log_path
 
       # Load chart for scene
diff --git a/apps/CameraITS/tests/scene3/test_3a_consistency.py b/apps/CameraITS/tests/scene3/test_3a_consistency.py
index 71469fe..1ab129d 100644
--- a/apps/CameraITS/tests/scene3/test_3a_consistency.py
+++ b/apps/CameraITS/tests/scene3/test_3a_consistency.py
@@ -136,7 +136,7 @@
       fd_min = np.amin(fds)
       fd_max = np.amax(fds)
       if not np.isclose(fd_max, fd_min, _FD_TOL):
-        raise AssertionError(f'FD min: {fd_min}, max: {fd_min} TOL: {_FD_TOL}')
+        raise AssertionError(f'FD min: {fd_min}, max: {fd_max} TOL: {_FD_TOL}')
       for g in awb_gains:
         if np.isnan(g):
           raise AssertionError('AWB gain entry is not a number.')
diff --git a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
index 7283f20..184c9aa 100644
--- a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
+++ b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
@@ -15,6 +15,7 @@
 
 
 import logging
+import math
 import os.path
 from mobly import test_runner
 import numpy as np
@@ -37,6 +38,8 @@
 # needs to pass the test for all resolutions within these aspect ratios.
 _AR_CHECKED_PRE_API_30 = ('4:3', '16:9', '18:9')
 _AR_DIFF_ATOL = 0.01
+# If RAW reference capture aspect ratio is ~4:3 or ~16:9, use JPEG, else RAW
+_AR_FOR_JPEG_REFERENCE = (4/3, 16/9)
 
 
 def _check_skip_conditions(first_api_level, props):
@@ -235,14 +238,34 @@
       debug = self.debug_mode
 
       # Converge 3A.
-      cam.do_3a()
-      req = capture_request_utils.auto_capture_request()
+      if camera_properties_utils.manual_sensor(props):
+        logging.debug('Manual sensor, using manual capture request')
+        s, e, _, _, f_d = cam.do_3a(get_results=True)
+        req = capture_request_utils.manual_capture_request(
+            s, e, f_distance=f_d)
+      else:
+        logging.debug('Using auto capture request')
+        cam.do_3a()
+        req = capture_request_utils.auto_capture_request()
 
-      # If raw available, use as ground truth.
+      # For main camera: if RAW available, use it as ground truth, else JPEG
+      # For physical sub-camera: if RAW available, only use if not 4:3 or 16:9
+      use_raw_fov = False
+      if raw_avlb:
+        pixel_array_w = props['android.sensor.info.pixelArraySize']['width']
+        pixel_array_h = props['android.sensor.info.pixelArraySize']['height']
+        logging.debug('Pixel array size: %dx%d', pixel_array_w, pixel_array_h)
+        raw_aspect_ratio = pixel_array_w / pixel_array_h
+        use_raw_fov = (
+            fls_physical == fls_logical or not
+            any(math.isclose(raw_aspect_ratio, jpeg_ar, abs_tol=_AR_DIFF_ATOL)
+                for jpeg_ar in _AR_FOR_JPEG_REFERENCE)
+        )
+
       ref_img_name_stem = f'{os.path.join(log_path, _NAME)}'
       ref_fov, cc_ct_gt, aspect_ratio_gt = (
           image_fov_utils.find_fov_reference(
-              cam, req, props, raw_avlb, ref_img_name_stem))
+              cam, req, props, use_raw_fov, ref_img_name_stem))
 
       run_crop_test = full_or_better and raw_avlb
       if run_crop_test:
@@ -273,7 +296,6 @@
                           'format': fmt_iter}]
           out_surface.append({'width': w_cmpr, 'height': h_cmpr,
                               'format': fmt_cmpr})
-          cam.do_3a()
           cap = cam.do_capture(req, out_surface)[0]
           _check_basic_correctness(cap, fmt_iter, w_iter, h_iter)
           logging.debug('Captured %s with %s %dx%d. Compared size: %dx%d',
diff --git a/apps/CameraITS/tests/scene4/test_video_aspect_ratio_and_crop.py b/apps/CameraITS/tests/scene4/test_video_aspect_ratio_and_crop.py
index 844807b..592a6e6 100644
--- a/apps/CameraITS/tests/scene4/test_video_aspect_ratio_and_crop.py
+++ b/apps/CameraITS/tests/scene4/test_video_aspect_ratio_and_crop.py
@@ -14,6 +14,7 @@
 """Validate video aspect ratio, crop and FoV vs format."""
 
 import logging
+import math
 import os.path
 
 from mobly import test_runner
@@ -33,6 +34,7 @@
 _FOV_PERCENT_RTOL = 0.15  # Relative tolerance on circle FoV % to expected.
 _AR_CHECKED_PRE_API_30 = ('4:3', '16:9', '18:9')
 _AR_DIFF_ATOL = 0.01
+_AR_FOR_JPEG_REFERENCE = (4/3, 16/9)
 _MAX_8BIT_IMGS = 255
 _MAX_10BIT_IMGS = 1023
 
@@ -139,9 +141,9 @@
       logging.debug('physical available focal lengths: %s', str(fls_physical))
 
       # Check SKIP conditions.
-      vendor_api_level = its_session_utils.get_vendor_api_level(self.dut.serial)
+      first_api_level = its_session_utils.get_first_api_level(self.dut.serial)
       camera_properties_utils.skip_unless(
-          vendor_api_level >= its_session_utils.ANDROID13_API_LEVEL)
+          first_api_level >= its_session_utils.ANDROID13_API_LEVEL)
 
       # Load scene.
       its_session_utils.load_scene(cam, props, self.scene,
@@ -160,13 +162,27 @@
       req = capture_request_utils.auto_capture_request()
       ref_img_name_stem = f'{os.path.join(self.log_path, _NAME)}'
 
-      if raw_avlb and (fls_physical == fls_logical):
-        logging.debug('RAW')
+      # For main camera: if RAW available, use it as ground truth, else JPEG
+      # For physical sub-camera: if RAW available, only use if not 4:3 or 16:9
+      if raw_avlb:
+        pixel_array_w = props['android.sensor.info.pixelArraySize']['width']
+        pixel_array_h = props['android.sensor.info.pixelArraySize']['height']
+        logging.debug('Pixel array size: %dx%d', pixel_array_w, pixel_array_h)
+        raw_aspect_ratio = pixel_array_w / pixel_array_h
+        if (fls_physical == fls_logical or not
+            any(math.isclose(raw_aspect_ratio, jpeg_ar, abs_tol=_AR_DIFF_ATOL)
+                for jpeg_ar in _AR_FOR_JPEG_REFERENCE)):
+          logging.debug('RAW')
+          use_raw_fov = True
+        else:
+          logging.debug('RAW available, but using JPEG as ground truth')
+          use_raw_fov = False
       else:
         logging.debug('JPEG')
+        use_raw_fov = False
 
       ref_fov, cc_ct_gt, aspect_ratio_gt = image_fov_utils.find_fov_reference(
-          cam, req, props, raw_avlb, ref_img_name_stem)
+          cam, req, props, use_raw_fov, ref_img_name_stem)
 
       run_crop_test = full_or_better and raw_avlb
 
diff --git a/apps/CameraITS/tests/scene6/test_zoom.py b/apps/CameraITS/tests/scene6/test_zoom.py
index 34b2215..fbc882e 100644
--- a/apps/CameraITS/tests/scene6/test_zoom.py
+++ b/apps/CameraITS/tests/scene6/test_zoom.py
@@ -244,11 +244,18 @@
       logging.debug('test TOLs: %s', str(test_tols))
 
       # do captures over zoom range and find circles with cv2
-      req = capture_request_utils.auto_capture_request()
+      if camera_properties_utils.manual_sensor(props):
+        logging.debug('Manual sensor, using manual capture request')
+        s, e, _, _, f_d = cam.do_3a(get_results=True)
+        req = capture_request_utils.manual_capture_request(
+            s, e, f_distance=f_d)
+      else:
+        logging.debug('Using auto capture request')
+        cam.do_3a()
+        req = capture_request_utils.auto_capture_request()
       for i, z in enumerate(z_list):
         logging.debug('zoom ratio: %.2f', z)
         req['android.control.zoomRatio'] = z
-        cam.do_3a()
         cap = cam.do_capture(
             req, {'format': 'yuv', 'width': size[0], 'height': size[1]})
         img = image_processing_utils.convert_capture_to_rgb_image(
diff --git a/apps/CameraITS/utils/camera_properties_utils.py b/apps/CameraITS/utils/camera_properties_utils.py
index 261c03e..44aa510 100644
--- a/apps/CameraITS/utils/camera_properties_utils.py
+++ b/apps/CameraITS/utils/camera_properties_utils.py
@@ -557,6 +557,20 @@
       'android.edge.availableEdgeModes']
 
 
+def tonemap_mode(props, mode):
+    """Returns whether a device supports the tonemap mode.
+
+    Args:
+        props: Camera properties object.
+        mode: Integer, indicating the tonemap mode to check for availability.
+
+    Return:
+        Boolean.
+    """
+    return 'android.edge.availableToneMapModes' in props and mode in props[
+        'android.tonemap.availableToneMapModes']
+
+
 def yuv_reprocess(props):
   """Returns whether a device supports YUV reprocessing.
 
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 5cc98fd..9c6d4b8 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -3026,8 +3026,7 @@
         <activity android:name=".camera.bokeh.CameraBokehActivity"
                   android:label="@string/camera_bokeh_test"
                   android:configChanges="keyboardHidden|screenSize"
-                  android:exported="true"
-                  android:screenOrientation="landscape">
+                  android:exported="true">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
@@ -5293,6 +5292,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_tv"/>
             <meta-data android:name="test_required_features"
                        android:value="android.software.leanback"/>
+            <meta-data android:name="test_required_configs"
+                       android:value="config_hdmi_source"/>
             <meta-data android:name="display_mode"
                        android:value="multi_display_mode" />
             <meta-data android:name="ApiTest"
diff --git a/apps/CtsVerifier/res/layout-port/cb_main.xml b/apps/CtsVerifier/res/layout-port/cb_main.xml
new file mode 100644
index 0000000..9a3ae1f
--- /dev/null
+++ b/apps/CtsVerifier/res/layout-port/cb_main.xml
@@ -0,0 +1,114 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- Copyright (C) 2023 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.
+-->
+
+<!-- Portrait orientation layout for the Camera Bokeh activity.
+     Provides a different view of the controls than the default (landscape)
+     layout.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent">
+
+    <LinearLayout
+        android:orientation="horizontal"
+        android:layout_width="fill_parent"
+        android:layout_height="0dp"
+        android:layout_weight="1" >
+
+        <LinearLayout
+            android:orientation="vertical"
+            android:layout_width="0dp"
+            android:layout_height="fill_parent"
+            android:layout_weight="2" >
+
+            <Spinner
+                android:id="@+id/cameras_selection"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"/>
+
+            <TextView
+                android:id="@+id/test_label"
+                android:layout_height="wrap_content"
+                android:layout_width="fill_parent"
+                android:padding="2dp"
+                android:textSize="16sp"
+                android:gravity="left" />
+
+            <Button
+                android:id="@+id/next_button"
+                android:layout_height="wrap_content"
+                android:layout_width="wrap_content"
+                android:text="@string/next_button_text" />
+
+        </LinearLayout>
+
+    </LinearLayout>
+
+    <LinearLayout
+        android:orientation="horizontal"
+        android:layout_width="fill_parent"
+        android:layout_height="0dp"
+        android:layout_weight="1" >
+
+        <LinearLayout
+            android:orientation="vertical"
+            android:layout_width="0dp"
+            android:layout_height="fill_parent"
+            android:layout_weight="3" >
+
+            <TextureView
+                android:id="@+id/preview_view"
+                android:layout_height="0dp"
+                android:layout_width="fill_parent"
+                android:layout_weight="3" />
+            <TextView
+                android:id="@+id/preview_label"
+                android:layout_height="wrap_content"
+                android:layout_width="fill_parent"
+                android:padding="2dp"
+                android:textSize="16sp"
+                android:gravity="center" />
+
+        </LinearLayout>
+
+        <LinearLayout
+            android:orientation="vertical"
+            android:layout_width="0dp"
+            android:layout_height="fill_parent"
+            android:layout_weight="3" >
+
+            <ImageView
+                android:id="@+id/image_view"
+                android:layout_height="0dp"
+                android:layout_width="fill_parent"
+                android:layout_weight="3" />
+            <TextView
+                android:id="@+id/image_label"
+                android:layout_height="wrap_content"
+                android:layout_width="fill_parent"
+                android:padding="2dp"
+                android:textSize="16sp"
+                android:gravity="center" />
+
+        </LinearLayout>
+
+    </LinearLayout>
+
+    <include layout="@layout/pass_fail_buttons" />
+
+</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/OWNERS b/apps/CtsVerifier/res/layout/OWNERS
index f4217d9..349a259 100644
--- a/apps/CtsVerifier/res/layout/OWNERS
+++ b/apps/CtsVerifier/res/layout/OWNERS
@@ -1,5 +1,7 @@
 # Bug component: 41727 = per-file camera_*.xml
 # Bug component: 41727 = per-file cam_*.xml
+# Bug component: 41727 = per-file co_main.xml,ci_main.xml,cb_main.xml,cf_main.xml
 
 per-file camera_*.xml = file:platform/frameworks/av:/camera/OWNERS
-per-file cam_*.xml = file:platform/frameworks/av:/camera/OWNERS
\ No newline at end of file
+per-file cam_*.xml = file:platform/frameworks/av:/camera/OWNERS
+per-file co_main.xml,ci_main.xml,cb_main.xml,cf_main.xml = file:platform/frameworks/av:/camera/OWNERS
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
index 9e27cb3..73fc742 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
@@ -68,7 +68,9 @@
     private final static String PKG = "com.android.cts.verifier";
     private final static long TIME_TO_PLAY = 2000;
     private final static int MP3_TO_PLAY = R.raw.testmp3;
-    private final static int ASYNC_TIMING_TOLERANCE_MS = 50;
+    // TODO replace sleeps with blocking receiver of ACTION_VOLUME_CHANGED intent for
+    //      volume operations (AudioManager.setStreamVolume and .adjustVolume)
+    private static final int ASYNC_TIMING_TOLERANCE_MS = 150;
 
     private AudioManager mAudioManager;
     private boolean mHasVibrator;
@@ -781,7 +783,7 @@
             // 7 to 1: success
             mAudioManager.setStreamVolume(
                     AudioManager.STREAM_SYSTEM, 1, AudioManager.FLAG_ALLOW_RINGER_MODES);
-            if (1 !=  mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM)) {
+            if (1 != mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM)) {
                 setFailed();
                 return;
             }
@@ -911,6 +913,11 @@
                 }
 
                 mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
+                try {
+                    Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
 
                 // volume raise
                 mAudioManager.setStreamVolume(stream, 1, 0);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java
index 55791c6..3a7bc72 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java
@@ -15,16 +15,8 @@
  */
 package com.android.cts.verifier.camera.bokeh;
 
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import com.android.ex.camera2.blocking.BlockingCameraManager;
-import com.android.ex.camera2.blocking.BlockingCameraManager.BlockingOpenException;
-import com.android.ex.camera2.blocking.BlockingStateCallback;
-import com.android.ex.camera2.blocking.BlockingSessionCallback;
-
 import android.app.AlertDialog;
-import android.content.res.Configuration;
+import android.content.Context;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.Color;
@@ -32,6 +24,7 @@
 import android.graphics.ColorMatrixColorFilter;
 import android.graphics.ImageFormat;
 import android.graphics.Matrix;
+import android.graphics.PointF;
 import android.graphics.RectF;
 import android.graphics.SurfaceTexture;
 import android.hardware.camera2.CameraAccessException;
@@ -43,9 +36,9 @@
 import android.hardware.camera2.CameraMetadata;
 import android.hardware.camera2.CaptureRequest;
 import android.hardware.camera2.CaptureResult;
+import android.hardware.camera2.TotalCaptureResult;
 import android.hardware.camera2.params.Capability;
 import android.hardware.camera2.params.StreamConfigurationMap;
-import android.hardware.camera2.TotalCaptureResult;
 import android.media.Image;
 import android.media.ImageReader;
 import android.os.Bundle;
@@ -56,9 +49,10 @@
 import android.util.SparseArray;
 import android.view.Menu;
 import android.view.MenuItem;
-import android.view.View;
+import android.view.OrientationEventListener;
 import android.view.Surface;
 import android.view.TextureView;
+import android.view.View;
 import android.widget.Adapter;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
@@ -68,14 +62,19 @@
 import android.widget.Spinner;
 import android.widget.TextView;
 import android.widget.Toast;
-import android.content.Context;
 
-import java.lang.Math;
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+import com.android.ex.camera2.blocking.BlockingCameraManager;
+import com.android.ex.camera2.blocking.BlockingCameraManager.BlockingOpenException;
+import com.android.ex.camera2.blocking.BlockingSessionCallback;
+import com.android.ex.camera2.blocking.BlockingStateCallback;
+
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.Comparator;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
@@ -131,6 +130,8 @@
     private HashMap<String, ArrayList<Capability>> mTestCases = new HashMap<>();
     private int mCurrentCameraIndex = -1;
     private String mCameraId;
+    private int mCameraSensorOrientation;
+    private int mCameraLensFacing;
     private CameraCaptureSession mCaptureSession;
     private CameraDevice mCameraDevice;
 
@@ -204,6 +205,8 @@
         }
     };
 
+    private OrientationEventListener mOrientationEventListener = null;
+
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
@@ -305,6 +308,13 @@
 
         mBlockingCameraManager = new BlockingCameraManager(mCameraManager);
         mCameraListener = new BlockingStateCallback();
+
+        mOrientationEventListener = new OrientationEventListener(getApplicationContext()) {
+            @Override
+            public void onOrientationChanged(int orientation) {
+                configurePreviewTextureTransform();
+            }
+        };
     }
 
     /**
@@ -417,6 +427,12 @@
     }
 
     @Override
+    public void onDestroy() {
+        super.onDestroy();
+        mOrientationEventListener.disable();
+    }
+
+    @Override
     public String getTestDetails() {
         StringBuilder reportBuilder = new StringBuilder();
         reportBuilder.append("Tested combinations:\n");
@@ -550,7 +566,11 @@
                             mCurrentColorFilter = null;
                             mImageView.clearColorFilter();
                         }
+
                         mImageView.setImageBitmap(bitmap);
+                        if (format == ImageFormat.YUV_420_888) {
+                            configureImageViewTransform();
+                        }
                     }
                 });
             }
@@ -611,6 +631,10 @@
         // Update untested cameras
         mUntestedCameras.remove("All combinations for Camera " + mCameraId);
 
+        mCameraSensorOrientation =
+                mCameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
+        mCameraLensFacing = mCameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
+
         StreamConfigurationMap config =
                 mCameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
         Size[] jpegSizes = config.getOutputSizes(ImageFormat.JPEG);
@@ -691,9 +715,8 @@
         }
     }
 
-    private void configurePreviewTextureTransform() {
+    private int getDisplayRotation() {
         int rotation = getWindowManager().getDefaultDisplay().getRotation();
-        Configuration config = getResources().getConfiguration();
         int degrees = 0;
         switch (rotation) {
             case Surface.ROTATION_0: degrees = 0; break;
@@ -701,42 +724,117 @@
             case Surface.ROTATION_180: degrees = 180; break;
             case Surface.ROTATION_270: degrees = 270; break;
         }
-        Matrix matrix = mPreviewView.getTransform(null);
-        int deviceOrientation = Configuration.ORIENTATION_PORTRAIT;
-        if ((degrees % 180 == 0 && config.orientation == Configuration.ORIENTATION_LANDSCAPE) ||
-                (degrees % 180 == 90 && config.orientation == Configuration.ORIENTATION_PORTRAIT)) {
-            deviceOrientation = Configuration.ORIENTATION_LANDSCAPE;
-        }
-        int effectiveWidth = mPreviewSize.getWidth();
-        int effectiveHeight = mPreviewSize.getHeight();
-        if (deviceOrientation == Configuration.ORIENTATION_PORTRAIT) {
-            int temp = effectiveWidth;
-            effectiveWidth = effectiveHeight;
-            effectiveHeight = temp;
+        return degrees;
+    }
+
+    /**
+     * Calculate the matrix required to center the preview with the correct rotation, such that
+     * the image is not cropped and either the width or height perfectly fills the available space.
+     * This is to compensate for the default behavior of TextureView, which is to not rotate the
+     * image and to completely fill the texture in both dimensions.
+     */
+    private void configurePreviewTextureTransform() {
+        int displayRotation = getDisplayRotation();
+
+        Matrix matrix = new Matrix();
+
+        mPreviewView.getSurfaceTexture().setDefaultBufferSize(mPreviewSize.getWidth(),
+                mPreviewSize.getHeight());
+        RectF viewRect = new RectF(0, 0, mPreviewView.getWidth(), mPreviewView.getHeight());
+
+        float expectedPreviewWidth, expectedPreviewHeight;
+        if ((360 + mCameraSensorOrientation - displayRotation) % 180 == 0) {
+            expectedPreviewWidth = mPreviewSize.getWidth();
+            expectedPreviewHeight = mPreviewSize.getHeight();
+        } else {
+            expectedPreviewWidth = mPreviewSize.getHeight();
+            expectedPreviewHeight = mPreviewSize.getWidth();
         }
 
-        RectF viewRect = new RectF(0, 0, mPreviewTexWidth, mPreviewTexHeight);
-        RectF bufferRect = new RectF(0, 0, effectiveWidth, effectiveHeight);
-        float centerX = viewRect.centerX();
-        float centerY = viewRect.centerY();
-        bufferRect.offset(centerX - bufferRect.centerX(),
-                centerY - bufferRect.centerY());
+        float viewAspectRatio = viewRect.width() / viewRect.height();
+        float imageAspectRatio = expectedPreviewWidth / expectedPreviewHeight;
+        final PointF scale;
 
-        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
-
-        matrix.postRotate((360 - degrees) % 360, centerX, centerY);
-        if ((degrees % 180) == 90) {
-            int temp = effectiveWidth;
-            effectiveWidth = effectiveHeight;
-            effectiveHeight = temp;
+        if (viewAspectRatio > imageAspectRatio) {
+            scale = new PointF((viewRect.height() / viewRect.width())
+                    * ((float) mPreviewSize.getHeight() / (float) mPreviewSize.getWidth()), 1f);
+        } else {
+            scale = new PointF(1f, (viewRect.width() / viewRect.height())
+                    * ((float) mPreviewSize.getWidth() / (float) mPreviewSize.getHeight()));
         }
-        // Scale to fit view, avoiding any crop
-        float scale = Math.min(mPreviewTexWidth / (float) effectiveWidth,
-                mPreviewTexHeight / (float) effectiveHeight);
-        matrix.postScale(scale, scale, centerX, centerY);
+
+        if (displayRotation % 180 != 0) {
+            float multiplier = viewAspectRatio > imageAspectRatio
+                    ? expectedPreviewWidth / expectedPreviewHeight
+                    : expectedPreviewHeight / expectedPreviewWidth;
+            scale.x *= multiplier;
+            scale.y *= multiplier;
+        }
+
+        matrix.setScale(scale.x, scale.y, viewRect.centerX(), viewRect.centerY());
+        if (displayRotation != 0) {
+            matrix.postRotate(360 - displayRotation, viewRect.centerX(), viewRect.centerY());
+        }
 
         mPreviewView.setTransform(matrix);
     }
+
+    /**
+     * Calculate the matrix required to center the capture with the correct rotation, such that
+     * the image is not cropped and either the width or height perfectly fills the available space.
+     * This is to compensate for the default behavior of ImageView, which is to not rotate the
+     * image and to render it in its original size, positioned at 0, 0.
+     */
+    private void configureImageViewTransform() {
+        int displayRotation = getDisplayRotation();
+        int rotation = (360 + mCameraSensorOrientation - displayRotation) % 360;
+        if (mCameraLensFacing == CameraMetadata.LENS_FACING_FRONT) {
+            rotation = (mCameraSensorOrientation + displayRotation) % 360;
+        }
+
+        Matrix matrix = new Matrix();
+
+        RectF viewRect = new RectF(0, 0, mImageView.getMeasuredWidth(),
+                mImageView.getMeasuredHeight());
+
+        float expectedPreviewWidth, expectedPreviewHeight;
+        if (rotation % 180 == 0) {
+            expectedPreviewWidth = mPreviewSize.getWidth();
+            expectedPreviewHeight = mPreviewSize.getHeight();
+        } else {
+            expectedPreviewWidth = mPreviewSize.getHeight();
+            expectedPreviewHeight = mPreviewSize.getWidth();
+        }
+
+        final PointF scale = new PointF(0, 0);
+
+        float widthRatio = expectedPreviewWidth / viewRect.width();
+        float heightRatio = expectedPreviewHeight / viewRect.height();
+        if (widthRatio / heightRatio > 1.0f) {
+            // Scale width to fit
+            scale.x = 1.0f / widthRatio;
+            scale.y = 1.0f / widthRatio;
+        } else {
+            // Scale height to fit
+            scale.x = 1.0f / heightRatio;
+            scale.y = 1.0f / heightRatio;
+        }
+
+        matrix.setScale(scale.x, scale.y, 0, 0);
+        if (rotation % 360 != 0) {
+            matrix.postRotate(rotation, 0, 0);
+        }
+
+        RectF imageRect = new RectF(0, 0, mPreviewSize.getWidth(), mPreviewSize.getHeight());
+        matrix.mapRect(imageRect, imageRect);
+        matrix.postTranslate(-imageRect.left, -imageRect.top);
+        matrix.postTranslate(viewRect.width() / 2 - imageRect.width() / 2,
+                viewRect.height() / 2 - imageRect.height() / 2);
+
+        mImageView.setScaleType(ImageView.ScaleType.MATRIX);
+        mImageView.setImageMatrix(matrix);
+    }
+
     /**
      * Starts a background thread and its {@link Handler}.
      */
@@ -762,6 +860,8 @@
 
     private void startPreview() {
         try {
+            mOrientationEventListener.disable();
+
             if (mPreviewSize == null || !mPreviewSize.equals(mNextCombination.mPreviewSize) ||
                     mYuvImageReader == null) {
                 mPreviewSize = mNextCombination.mPreviewSize;
@@ -800,6 +900,10 @@
             mStillCaptureRequest = mStillCaptureRequestBuilder.build();
 
             mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mCameraHandler);
+
+            if (mOrientationEventListener.canDetectOrientation()) {
+                mOrientationEventListener.enable();
+            }
         } catch (CameraAccessException e) {
             e.printStackTrace();
         }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java
index 26be321..e258c13 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java
@@ -57,6 +57,7 @@
     private static final String DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI_ID =
             "DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI";
 
+    private WifiManager mWifiManager;
     private WifiConfigCreator mConfigCreator;
     private ButtonInfo[] mSwitchLockdownOffButtonInfos;
     private ButtonInfo[] mSwitchLockdownOnButtonInfos;
@@ -64,9 +65,9 @@
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        WifiManager wifiManager = TestAppSystemServiceFactory.getWifiManager(this,
+        mWifiManager = TestAppSystemServiceFactory.getWifiManager(this,
                 DeviceAdminTestReceiver.class);
-        mConfigCreator = new WifiConfigCreator(this, wifiManager);
+        mConfigCreator = new WifiConfigCreator(this, mWifiManager);
         setContentView(R.layout.wifi_lockdown);
         setInfoResources(R.string.device_owner_wifi_lockdown_test,
                 R.string.device_owner_wifi_lockdown_info, 0);
@@ -159,23 +160,27 @@
                 R.string.device_owner_wifi_config_unlocked_removal_test,
                 R.string.device_owner_wifi_config_unlocked_removal_test_info,
                 mSwitchLockdownOffButtonInfos));
-        adapter.add(Utils.createInteractiveTestItem(this,
-                DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI_ID,
-                R.string.device_owner_disallow_sharing_admin_configure_wifi,
-                R.string.device_owner_disallow_sharing_admin_configure_wifi_info,
-                new ButtonInfo[] {
+
+        boolean isDppSupported = mWifiManager.isEasyConnectSupported();
+        if (isDppSupported) {
+            adapter.add(Utils.createInteractiveTestItem(this,
+                    DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI_ID,
+                    R.string.device_owner_disallow_sharing_admin_configure_wifi,
+                    R.string.device_owner_disallow_sharing_admin_configure_wifi_info,
+                    new ButtonInfo[] {
                         new ButtonInfo(
                                 R.string.device_owner_user_restriction_set,
                                 CommandReceiverActivity.createSetCurrentUserRestrictionIntent(
-                                        UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, true)),
+                                    UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, true)),
                         new ButtonInfo(
                                 R.string.device_owner_settings_go,
                                 new Intent(Settings.ACTION_WIFI_SETTINGS)),
                         new ButtonInfo(
                                 R.string.device_owner_user_restriction_unset,
                                 CommandReceiverActivity.createSetCurrentUserRestrictionIntent(
-                                        UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, false))
-                }));
+                                    UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, false))
+                    }));
+        }
     }
 
     private int convertKeyManagement(int radioButtonId) {
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 8860f00..fb0b429 100644
--- a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
+++ b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
@@ -744,6 +744,8 @@
         new ImmutableMap.Builder<String, ImmutableSet<String>>()
             .put("/apex/com.android.btservices/app/Bluetooth/Bluetooth.apk",
                 BLUETOOTH_APK_IN_APEX_BURNDOWN_LIST)
+            .put("/apex/com.android.btservices/app/BluetoothArc/BluetoothArc.apk",
+                BLUETOOTH_APK_IN_APEX_BURNDOWN_LIST)
             .put("/apex/com.android.btservices/app/BluetoothGoogle/BluetoothGoogle.apk",
                 BLUETOOTH_APK_IN_APEX_BURNDOWN_LIST)
             .put("/apex/com.android.permission/priv-app/PermissionController/PermissionController.apk",
@@ -1058,6 +1060,7 @@
             + "bootclasspath. Please use alternatives provided by the platform instead. "
             + "See go/androidx-api-guidelines#module-naming.")
                 .that(sJarsToClasses.entries().stream()
+                        .filter(e -> e.getKey().endsWith(".jar"))
                         .filter(e -> e.getValue().startsWith("Landroidx/"))
                         .filter(e -> !isLegacyAndroidxDependency(
                             LegacyExemptAndroidxSharedLibsNamesToClasses, e.getKey(), e.getValue()))
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 2ec37fd..c1fa58b 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -602,7 +602,7 @@
             assertActivityInForeground("android/com.android.internal.app.ResolverActivity", userId);
         } catch (AssertionError e) {
             CLog.v("ResolverActivity is not the default: " + e);
-            assertActivityInForeground(resolveActivity("android.intent.action.SEND"), userId);
+            assertActivityInForeground(getCustomResolverActivity(), userId);
         }
     }
 
@@ -647,4 +647,16 @@
 
         return outputs[1];
     }
+
+    private String getCustomResolverActivity() throws Exception {
+        final String[] outputs = getDevice().executeShellCommand(
+                "cmd overlay lookup android android:string/config_customResolverActivity")
+                .split("\n");
+
+        String customResolverActivity = resolveActivity("android.intent.action.SEND");
+        if (outputs != null && outputs.length >= 1 && outputs[0] != null && !outputs[0].isEmpty()) {
+            customResolverActivity = outputs[0];
+        }
+        return customResolverActivity;
+    }
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java
index a5be8bf..38765c2 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java
@@ -56,6 +56,7 @@
     VENDOR_COMMAND(0x89),
     GIVE_DEVICE_VENDOR_ID(0x8c),
     MENU_REQUEST(0x8d),
+    MENU_STATUS(0x8e),
     GIVE_POWER_STATUS(0x8f),
     REPORT_POWER_STATUS(0x90),
     GET_MENU_LANGUAGE(0x91),
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java
index cf9ea39..3ca4ee0 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java
@@ -461,10 +461,12 @@
             TimeUnit.SECONDS.sleep(waitSeconds);
             waitForTransitionTo(HdmiCecConstants.CEC_POWER_STATUS_ON);
 
-            // Send <UCP> [Power]. DUT should go to standby.
+            // Send <UCP> [Power]. DUT should remain in ON state.
             hdmiCecClient.sendUserControlPressAndRelease(
                     source, HdmiCecConstants.CEC_KEYCODE_POWER, false);
-            waitForTransitionTo(HdmiCecConstants.CEC_POWER_STATUS_STANDBY);
+            waitForTransitionTo(HdmiCecConstants.CEC_POWER_STATUS_ON);
+
+            sendDeviceToSleep();
 
             // Send <UCP> [Power]. DUT should wakeup.
             hdmiCecClient.sendUserControlPressAndRelease(
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecStartupTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecStartupTest.java
index 93d8100..7cd2e1f 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecStartupTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecStartupTest.java
@@ -66,7 +66,7 @@
                         CecOperand.DEVICE_VENDOR_ID, CecOperand.GIVE_POWER_STATUS,
                         CecOperand.GET_MENU_LANGUAGE, CecOperand.ACTIVE_SOURCE,
                         CecOperand.REQUEST_ACTIVE_SOURCE, CecOperand.GIVE_PHYSICAL_ADDRESS,
-                        CecOperand.GIVE_SYSTEM_AUDIO_MODE_STATUS));
+                        CecOperand.REPORT_POWER_STATUS, CecOperand.GIVE_SYSTEM_AUDIO_MODE_STATUS));
         allowedMessages.addAll(expectedMessages);
 
         device.reboot();
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java
index 96e026d..d44f44c 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java
@@ -22,8 +22,8 @@
 import android.hdmicec.cts.CecMessage;
 import android.hdmicec.cts.CecOperand;
 import android.hdmicec.cts.HdmiControlManagerUtility;
-import android.hdmicec.cts.LogicalAddress;
 import android.hdmicec.cts.LogHelper;
+import android.hdmicec.cts.LogicalAddress;
 
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
@@ -31,9 +31,9 @@
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import org.junit.Rule;
+import org.junit.Test;
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
-import org.junit.Test;
 
 /** HDMI CEC test to verify device vendor specific commands (Section 11.2.9) */
 @RunWith(DeviceJUnit4ClassRunner.class)
@@ -157,7 +157,7 @@
             String params = CecMessage.formatParams(VENDOR_ID);
             params += CecMessage.formatParams("010203");
             hdmiCecClient.sendCecMessage(
-                    LogicalAddress.TV, CecOperand.VENDOR_COMMAND_WITH_ID, params);
+                    hdmiCecClient.getSelfDevice(), CecOperand.VENDOR_COMMAND_WITH_ID, params);
 
             LogHelper.assertLog(
                     device, TEST_LOG_TAG, "Received vendor command with correct vendor ID");
@@ -176,7 +176,8 @@
             LogHelper.waitForLog(getDevice(), TEST_LOG_TAG, 10, REGISTERED_LISTENER);
 
             String params = CecMessage.formatParams("010203");
-            hdmiCecClient.sendCecMessage(LogicalAddress.TV, CecOperand.VENDOR_COMMAND, params);
+            hdmiCecClient.sendCecMessage(
+                    hdmiCecClient.getSelfDevice(), CecOperand.VENDOR_COMMAND, params);
 
             LogHelper.assertLog(device, TEST_LOG_TAG, "Received vendor command without vendor ID");
         } finally {
@@ -194,7 +195,8 @@
             LogHelper.waitForLog(getDevice(), TEST_LOG_TAG, 10, REGISTERED_LISTENER);
 
             String params = CecMessage.formatParams("010203");
-            hdmiCecClient.sendCecMessage(LogicalAddress.TV, CecOperand.VENDOR_COMMAND, params);
+            hdmiCecClient.sendCecMessage(
+                    hdmiCecClient.getSelfDevice(), CecOperand.VENDOR_COMMAND, params);
 
             LogHelper.assertLog(device, TEST_LOG_TAG, "Received vendor command without vendor ID");
         } finally {
@@ -214,7 +216,7 @@
             String params = CecMessage.formatParams(VENDOR_ID);
             params += CecMessage.formatParams("010203");
             hdmiCecClient.sendCecMessage(
-                    LogicalAddress.TV, CecOperand.VENDOR_COMMAND_WITH_ID, params);
+                    hdmiCecClient.getSelfDevice(), CecOperand.VENDOR_COMMAND_WITH_ID, params);
 
             LogHelper.assertLogDoesNotContain(
                     device, TEST_LOG_TAG, "Received vendor command with correct vendor ID");
diff --git a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
index 814363d..44e616d 100644
--- a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
+++ b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
@@ -207,7 +207,7 @@
                     break;
                 }
                 /* Samsung Exynos SoCs */
-                else if (line.startsWith("EXYNOS") || line.startsWith("S5E")) {
+                else if (line.startsWith("EXYNOS")) {
                     hardware = line;
                     break;
                 }
@@ -237,8 +237,6 @@
         put("EXYNOS7872", null);
         put("EXYNOS7885", null);
         put("EXYNOS9610", null);
-        put("S5E8825", null);
-        put("S5E9925", null);
         put("Kirin980", null);
         put("Kirin970", null);
         put("Kirin810", null);
diff --git a/hostsidetests/securitybulletin/Android.bp b/hostsidetests/securitybulletin/Android.bp
index 323d5b7..30b6161 100644
--- a/hostsidetests/securitybulletin/Android.bp
+++ b/hostsidetests/securitybulletin/Android.bp
@@ -23,7 +23,6 @@
     java_resource_dirs: ["res"],
     // tag this module as a cts test artifact
     test_suites: [
-        "cts",
         "general-tests",
         "sts",
     ],
@@ -60,7 +59,6 @@
         },
     },
     test_suites: [
-        "cts",
         "sts",
         "general-tests",
     ],
diff --git a/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerHostTest.java b/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerHostTest.java
index b716174..5d2beb3 100644
--- a/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerHostTest.java
+++ b/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerHostTest.java
@@ -59,10 +59,24 @@
 import java.util.Arrays;
 import java.util.List;
 
-/** Host-side CTS tests for the location time zone manager service. */
+/**
+ * Host-side CTS tests for the location time zone manager service. There are plenty of unit tests
+ * for individual components but manufacturers don't have to run them. This test is intended to
+ * provide confidence that the specific device configuration is likely to work as it should, i.e.
+ * this tests the actual location_time_zone_manager service on a given device.
+ *
+ * <p>Because there are a large set of possibilities, this test has to handle them all:
+ * <ul>
+ *     <li>location_time_zone_manager service disabled</li>
+ *     <li>location_time_zone_manager service enabled, but no LTZPs configured</li>
+ *     <li>location_time_zone_manager service enabled, with LTZPs configured</li>
+ * </ul>
+ */
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class LocationTimeZoneManagerHostTest extends BaseHostJUnit4Test {
 
+    private static final String NON_EXISTENT_TZPS_APP_PACKAGE = "foobar";
+
     private boolean mOriginalLocationEnabled;
     private boolean mOriginalAutoDetectionEnabled;
     private boolean mOriginalGeoDetectionEnabled;
@@ -80,8 +94,8 @@
         mLocationTimeZoneManagerShellHelper =
                 new LocationTimeZoneManagerShellHelper(shellCommandExecutor);
 
-        // Confirm the service being tested is present. It can be turned off, in which case there's
-        // nothing to test.
+        // Confirm the service being tested is present. It can be turned off permanently in config,
+        // in which case there's nothing about it to test.
         mLocationTimeZoneManagerShellHelper.assumeLocationTimeZoneManagerIsPresent();
 
         // Install the app that hosts the fake providers.
@@ -96,28 +110,50 @@
         mDeviceConfigPreTestState = mDeviceConfigShellHelper.setSyncModeForTest(
                 SYNC_DISABLED_MODE_UNTIL_REBOOT, NAMESPACE_SYSTEM_TIME);
 
-        // All tests start with the location_time_zone_manager disabled so that providers can be
-        // configured.
+        // These original values try to record the raw value of the settings before the test ran:
+        // they may be ignored by the location_time_zone_manager service when they have no meaning.
+        // Unfortunately, we cannot tell if the value returned is the result of setting defaults or
+        // real values, which means we may not return things exactly as they were. To do better
+        // would require looking at raw settings values and use internal knowledge of settings keys.
+        mOriginalAutoDetectionEnabled = mTimeZoneDetectorShellHelper.isAutoDetectionEnabled();
+        mOriginalGeoDetectionEnabled = mTimeZoneDetectorShellHelper.isGeoDetectionEnabled();
+
         mLocationTimeZoneManagerShellHelper.stop();
 
-        // Make sure locations is enabled, otherwise the geo detection feature will be disabled
-        // whatever the geolocation detection setting is set to.
+        // Make sure location is enabled, otherwise the geo detection feature cannot operate.
         mOriginalLocationEnabled = mLocationShellHelper.isLocationEnabledForCurrentUser();
         if (!mOriginalLocationEnabled) {
             mLocationShellHelper.setLocationEnabledForCurrentUser(true);
         }
 
-        // Make sure automatic time zone detection is enabled, otherwise the geo detection feature
-        // will be disabled whatever the geolocation detection setting is set to.
-        mOriginalAutoDetectionEnabled = mTimeZoneDetectorShellHelper.isAutoDetectionEnabled();
-        if (!mOriginalAutoDetectionEnabled) {
-            mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
+        // Restart the location_time_zone_manager with a do-nothing test config; some settings
+        // values cannot be set when the service knows that the settings won't be used. Devices
+        // can be encountered with the location_time_zone_manager enabled but with no providers
+        // installed. Starting the service with a valid-looking test provider config means we know
+        // settings changes will be accepted regardless of the real config.
+        String testPrimaryLocationTimeZoneProviderPackageName = NON_EXISTENT_TZPS_APP_PACKAGE;
+        String testSecondaryLocationTimeZoneProviderPackageName = null;
+        mLocationTimeZoneManagerShellHelper.startWithTestProviders(
+                testPrimaryLocationTimeZoneProviderPackageName,
+                testSecondaryLocationTimeZoneProviderPackageName,
+                false /* recordProviderStates */);
+
+        // Begin all tests with auto detection turned off.
+        if (mOriginalAutoDetectionEnabled) {
+            mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(false);
         }
 
-        // On devices with no location time zone providers (e.g. AOSP), we cannot turn geo detection
-        // on until the test LTZPs are configured as the time_zone_detector will refuse.
-        mOriginalGeoDetectionEnabled = mTimeZoneDetectorShellHelper.isGeoDetectionEnabled();
+        // We set the device settings so that location detection will be used.
+        if (!mOriginalGeoDetectionEnabled) {
+            mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+        }
 
+        // All tests begin with the location_time_zone_manager stopped so that fake providers can be
+        // configured.
+        mLocationTimeZoneManagerShellHelper.stop();
+
+        // Make sure the fake provider APK install started above has completed before tests try to
+        // use the fake providers.
         FakeTimeZoneProviderAppShellHelper fakeTimeZoneProviderAppShellHelper =
                 new FakeTimeZoneProviderAppShellHelper(shellCommandExecutor);
         // Delay until the fake TZPS app can be found.
@@ -135,24 +171,33 @@
             return;
         }
 
-        // Reset the geoDetectionEnabled state while there is at least one LTZP configured: this
-        // setting cannot be modified if there are no LTZPs on the device, e.g. on AOSP.
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(mOriginalGeoDetectionEnabled);
-
-        // Turn off the service before we reset configuration, otherwise it will restart itself
-        // repeatedly.
+        // Restart the location_time_zone_manager with a test config so that the device can be set
+        // back to the starting state regardless of how the test left things.
         mLocationTimeZoneManagerShellHelper.stop();
+        String testPrimaryLocationTimeZoneProviderPackageName = NON_EXISTENT_TZPS_APP_PACKAGE;
+        String testSecondaryLocationTimeZoneProviderPackageName = null;
+        mLocationTimeZoneManagerShellHelper.startWithTestProviders(
+                testPrimaryLocationTimeZoneProviderPackageName,
+                testSecondaryLocationTimeZoneProviderPackageName,
+                false /* recordProviderStates */);
 
-        // Reset settings and server flags as best we can.
+        if (mTimeZoneDetectorShellHelper.isGeoDetectionEnabled() != mOriginalGeoDetectionEnabled) {
+            mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(mOriginalGeoDetectionEnabled);
+        }
+
         if (mTimeZoneDetectorShellHelper.isAutoDetectionEnabled()
                 != mOriginalAutoDetectionEnabled) {
             mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(mOriginalAutoDetectionEnabled);
         }
+
+        // Everything else can be reset without worrying about the providers.
+        mLocationTimeZoneManagerShellHelper.stop();
+
         mLocationShellHelper.setLocationEnabledForCurrentUser(mOriginalLocationEnabled);
         mDeviceConfigShellHelper.restoreDeviceConfigStateForTest(mDeviceConfigPreTestState);
 
-        // Attempt to start the service. It may not start if there are no providers configured,
-        // but that is ok.
+        // Attempt to start the service without test providers. It may not start if there are no
+        // providers configured, but that is ok.
         mLocationTimeZoneManagerShellHelper.start();
     }
 
@@ -165,7 +210,10 @@
                 testPrimaryLocationTimeZoneProviderPackageName,
                 testSecondaryLocationTimeZoneProviderPackageName,
                 true /* recordProviderStates */);
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+
+        // Turn on auto detection, which should activate the location time zone algorithm.
+        mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
+
         mPrimaryFakeTimeZoneProviderShellHelper.assertCreated();
         mSecondaryFakeTimeZoneProviderShellHelper.assertNotCreated();
 
@@ -219,7 +267,8 @@
                 testPrimaryLocationTimeZoneProviderPackageName,
                 testSecondaryLocationTimeZoneProviderPackageName,
                 true /* recordProviderStates */);
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+        // Turn on auto detection, which should activate the location time zone algorithm.
+        mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
 
         mPrimaryFakeTimeZoneProviderShellHelper.assertCreated();
         mSecondaryFakeTimeZoneProviderShellHelper.assertNotCreated();
@@ -280,7 +329,8 @@
                 testPrimaryLocationTimeZoneProviderPackageName,
                 testSecondaryLocationTimeZoneProviderPackageName,
                 true /* recordProviderStates */);
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+        // Turn on auto detection, which should activate the location time zone algorithm.
+        mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
         mPrimaryFakeTimeZoneProviderShellHelper.assertCreated();
         mSecondaryFakeTimeZoneProviderShellHelper.assertNotCreated();
 
@@ -333,7 +383,8 @@
                 testPrimaryLocationTimeZoneProviderPackageName,
                 testSecondaryLocationTimeZoneProviderPackageName,
                 true /* recordProviderStates */);
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+        // Turn on auto detection, which should activate the location time zone algorithm.
+        mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
         mPrimaryFakeTimeZoneProviderShellHelper.assertNotCreated();
         mSecondaryFakeTimeZoneProviderShellHelper.assertCreated();
 
@@ -382,7 +433,8 @@
                 testPrimaryLocationTimeZoneProviderPackageName,
                 testSecondaryLocationTimeZoneProviderPackageName,
                 true /* recordProviderStates*/);
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+        // Turn on auto detection, which should activate the location time zone algorithm.
+        mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
         mPrimaryFakeTimeZoneProviderShellHelper.assertCreated();
         mSecondaryFakeTimeZoneProviderShellHelper.assertCreated();
 
diff --git a/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerStatsTest.java b/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerStatsTest.java
index e591d2d..9ab524d 100644
--- a/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerStatsTest.java
+++ b/hostsidetests/time/host/src/android/time/cts/host/LocationTimeZoneManagerStatsTest.java
@@ -53,10 +53,15 @@
 import java.util.Set;
 import java.util.function.Function;
 
-/** Host-side CTS tests for the location time zone manager service stats logging. */
+/**
+ * Host-side CTS tests for the location time zone manager service stats logging. Very similar to
+ * {@link LocationTimeZoneManagerHostTest} but focused on stats logging.
+ */
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class LocationTimeZoneManagerStatsTest extends BaseHostJUnit4Test {
 
+    private static final String NON_EXISTENT_TZPS_APP_PACKAGE = "foobar";
+
     private static final int PRIMARY_PROVIDER_INDEX = 0;
     private static final int SECONDARY_PROVIDER_INDEX = 1;
 
@@ -80,8 +85,8 @@
         mLocationTimeZoneManagerShellHelper =
                 new LocationTimeZoneManagerShellHelper(shellCommandExecutor);
 
-        // Confirm the service being tested is present. It can be turned off, in which case there's
-        // nothing to test.
+        // Confirm the service being tested is present. It can be turned off permanently in config,
+        // in which case there's nothing about it to test.
         mLocationTimeZoneManagerShellHelper.assumeLocationTimeZoneManagerIsPresent();
 
         // Install the app that hosts the fake providers.
@@ -92,34 +97,57 @@
         mLocationShellHelper = new LocationShellHelper(shellCommandExecutor);
         mDeviceConfigShellHelper = new DeviceConfigShellHelper(shellCommandExecutor);
 
+        // Stop device_config updates for the duration of the test.
         mDeviceConfigPreTestState = mDeviceConfigShellHelper.setSyncModeForTest(
                 SYNC_DISABLED_MODE_UNTIL_REBOOT, NAMESPACE_SYSTEM_TIME);
 
-        // All tests start with the location_time_zone_manager disabled so that providers can be
-        // configured.
+        // These original values try to record the raw value of the settings before the test ran:
+        // they may be ignored by the location_time_zone_manager service when they have no meaning.
+        // Unfortunately, we cannot tell if the value returned is the result of setting defaults or
+        // real values, which means we may not return things exactly as they were. To do better
+        // would require looking at raw settings values and use internal knowledge of settings keys.
+        mOriginalAutoDetectionEnabled = mTimeZoneDetectorShellHelper.isAutoDetectionEnabled();
+        mOriginalGeoDetectionEnabled = mTimeZoneDetectorShellHelper.isGeoDetectionEnabled();
+
         mLocationTimeZoneManagerShellHelper.stop();
 
-        // Make sure locations is enabled, otherwise the geo detection feature will be disabled
-        // whatever the geolocation detection setting is set to.
+        // Make sure location is enabled, otherwise the geo detection feature cannot operate.
         mOriginalLocationEnabled = mLocationShellHelper.isLocationEnabledForCurrentUser();
         if (!mOriginalLocationEnabled) {
             mLocationShellHelper.setLocationEnabledForCurrentUser(true);
         }
 
-        // Make sure automatic time zone detection is enabled, otherwise the geo detection feature
-        // will be disabled whatever the geolocation detection setting is set to
-        mOriginalAutoDetectionEnabled = mTimeZoneDetectorShellHelper.isAutoDetectionEnabled();
-        if (!mOriginalAutoDetectionEnabled) {
-            mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
+        // Restart the location_time_zone_manager with a do-nothing test config; some settings
+        // values cannot be set when the service knows that the settings won't be used. Devices
+        // can be encountered with the location_time_zone_manager enabled but with no providers
+        // installed. Starting the service with a valid-looking test provider config means we know
+        // settings changes will be accepted regardless of the real config.
+        String testPrimaryLocationTimeZoneProviderPackageName = NON_EXISTENT_TZPS_APP_PACKAGE;
+        String testSecondaryLocationTimeZoneProviderPackageName = null;
+        mLocationTimeZoneManagerShellHelper.startWithTestProviders(
+                testPrimaryLocationTimeZoneProviderPackageName,
+                testSecondaryLocationTimeZoneProviderPackageName,
+                false /* recordProviderStates */);
+
+        // Begin all tests with auto detection turned off.
+        if (mOriginalAutoDetectionEnabled) {
+            mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(false);
         }
 
-        // On devices with no location time zone providers (e.g. AOSP), we cannot turn geo detection
-        // on until the test LTZPs are configured as the time_zone_detector will refuse.
-        mOriginalGeoDetectionEnabled = mTimeZoneDetectorShellHelper.isGeoDetectionEnabled();
+        // We set the device settings so that location detection will be used.
+        if (!mOriginalGeoDetectionEnabled) {
+            mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+        }
 
-        // Make sure that the fake providers used in the tests are available.
+        // All tests begin with the location_time_zone_manager stopped so that fake providers can be
+        // configured.
+        mLocationTimeZoneManagerShellHelper.stop();
+
+        // Make sure the fake provider APK install started above has completed before tests try to
+        // use the fake providers.
         FakeTimeZoneProviderAppShellHelper fakeTimeZoneProviderAppShellHelper =
                 new FakeTimeZoneProviderAppShellHelper(shellCommandExecutor);
+        // Delay until the fake TZPS app can be found.
         fakeTimeZoneProviderAppShellHelper.waitForInstallation();
 
         ConfigUtils.removeConfig(device);
@@ -133,27 +161,36 @@
             return;
         }
 
-        // Reset the geoDetectionEnabled state while there is at least one LTZP configured: this
-        // setting cannot be modified if there are no LTZPs on the device, e.g. on AOSP.
-        mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(mOriginalGeoDetectionEnabled);
-
-        // Turn off the service before we reset configuration, otherwise it will restart itself
-        // repeatedly.
+        // Restart the location_time_zone_manager with a test config so that the device can be set
+        // back to the starting state regardless of how the test left things.
         mLocationTimeZoneManagerShellHelper.stop();
+        String testPrimaryLocationTimeZoneProviderPackageName = NON_EXISTENT_TZPS_APP_PACKAGE;
+        String testSecondaryLocationTimeZoneProviderPackageName = null;
+        mLocationTimeZoneManagerShellHelper.startWithTestProviders(
+                testPrimaryLocationTimeZoneProviderPackageName,
+                testSecondaryLocationTimeZoneProviderPackageName,
+                false /* recordProviderStates */);
 
-        // Reset settings and server flags as best we can.
+        if (mTimeZoneDetectorShellHelper.isGeoDetectionEnabled() != mOriginalGeoDetectionEnabled) {
+            mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(mOriginalGeoDetectionEnabled);
+        }
+
         if (mTimeZoneDetectorShellHelper.isAutoDetectionEnabled()
                 != mOriginalAutoDetectionEnabled) {
             mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(mOriginalAutoDetectionEnabled);
         }
+
+        // Everything else can be reset without worrying about the providers.
+        mLocationTimeZoneManagerShellHelper.stop();
+
         mLocationShellHelper.setLocationEnabledForCurrentUser(mOriginalLocationEnabled);
 
         ConfigUtils.removeConfig(getDevice());
         ReportUtils.clearReports(getDevice());
         mDeviceConfigShellHelper.restoreDeviceConfigStateForTest(mDeviceConfigPreTestState);
 
-        // Attempt to start the service. It may not start if there are no providers configured,
-        // but that is ok.
+        // Attempt to start the service without test providers. It may not start if there are no
+        // providers configured, but that is ok.
         mLocationTimeZoneManagerShellHelper.start();
     }
 
@@ -169,12 +206,12 @@
                 testSecondaryLocationTimeZoneProviderPackageName,
                 true /* recordProviderStates */);
 
-        // Turn geo detection on and off, twice.
+        // Turn the location detection algorithm on and off, twice.
         for (int i = 0; i < 2; i++) {
             Thread.sleep(AtomTestUtils.WAIT_TIME_SHORT);
-            mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(true);
+            mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(true);
             Thread.sleep(AtomTestUtils.WAIT_TIME_SHORT);
-            mTimeZoneDetectorShellHelper.setGeoDetectionEnabled(false);
+            mTimeZoneDetectorShellHelper.setAutoDetectionEnabled(false);
         }
 
         // Sorted list of events in order in which they occurred.
diff --git a/tests/backup/AndroidManifest.xml b/tests/backup/AndroidManifest.xml
index 22c2531..71a0925 100644
--- a/tests/backup/AndroidManifest.xml
+++ b/tests/backup/AndroidManifest.xml
@@ -19,6 +19,8 @@
     package="android.backup.cts">
 
     <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
+
     <application>
         <uses-library android:name="android.test.runner" />
         <uses-library android:name="org.apache.http.legacy" />
diff --git a/tests/backup/src/android/backup/cts/AppLocalesBackupTest.java b/tests/backup/src/android/backup/cts/AppLocalesBackupTest.java
index aab4159..d51b7ae 100644
--- a/tests/backup/src/android/backup/cts/AppLocalesBackupTest.java
+++ b/tests/backup/src/android/backup/cts/AppLocalesBackupTest.java
@@ -23,7 +23,6 @@
 import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
 
 import android.Manifest;
-import android.app.Instrumentation;
 import android.app.LocaleManager;
 import android.app.time.ExternalTimeSuggestion;
 import android.app.time.TimeManager;
@@ -38,6 +37,7 @@
 import android.os.LocaleList;
 import android.os.SystemClock;
 import android.platform.test.annotations.AppModeFull;
+import android.provider.Settings;
 
 import androidx.test.InstrumentationRegistry;
 
@@ -72,8 +72,13 @@
 
     private static final Duration RETENTION_PERIOD = Duration.ofDays(3);
 
+    private static final String SHELL_COMMAND_IS_AUTO_DETECTION_ENABLED =
+            "cmd time_detector is_auto_detection_enabled";
+
     private Context mContext;
     private LocaleManager mLocaleManager;
+    private boolean mOriginalAutoTime;
+    private DeviceShellCommandExecutor mShellCommandExecutor;
 
     @Before
     @Override
@@ -82,6 +87,14 @@
 
         mContext = InstrumentationRegistry.getTargetContext();
         mLocaleManager = mContext.getSystemService(LocaleManager.class);
+        mShellCommandExecutor = new InstrumentationShellCommandExecutor(
+                InstrumentationRegistry.getInstrumentation().getUiAutomation());
+
+        mOriginalAutoTime = isAutoDetectionEnabled(mShellCommandExecutor);
+        // Auto time needs to be enabled to be able to suggest external time
+        if (!mOriginalAutoTime) {
+            assertTrue(setAutoTimeEnabled(/*enabled*/ true, mShellCommandExecutor));
+        }
 
         install(TEST_APP_APK_1);
         install(TEST_APP_APK_2);
@@ -89,6 +102,11 @@
 
     @After
     public void tearDown() throws Exception {
+        // reset auto time to its original value
+        if (!mOriginalAutoTime) {
+            setAutoTimeEnabled(/*enabled*/ false, mShellCommandExecutor);
+        }
+
         uninstall(TEST_APP_PACKAGE_1);
         uninstall(TEST_APP_PACKAGE_2);
     }
@@ -239,11 +257,8 @@
         // Locales for App1 should be restored immediately since that's present already.
         assertLocalesForApp(TEST_APP_PACKAGE_1, DEFAULT_LOCALES_1);
 
-        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
-        DeviceShellCommandExecutor shellCommandExecutor = new InstrumentationShellCommandExecutor(
-                instrumentation.getUiAutomation());
         DeviceConfigShellHelper deviceConfigShellHelper = new DeviceConfigShellHelper(
-                shellCommandExecutor);
+                mShellCommandExecutor);
 
         // This anticipates a future state where a generally applied target preparer may disable
         // device_config sync for all CTS tests: only suspend syncing if it isn't already suspended,
@@ -337,11 +352,9 @@
 
         getBackupUtils().restoreAndAssertSuccess(RESTORE_TOKEN, SYSTEM_PACKAGE);
 
-        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
-        DeviceShellCommandExecutor shellCommandExecutor = new InstrumentationShellCommandExecutor(
-                instrumentation.getUiAutomation());
+
         DeviceConfigShellHelper deviceConfigShellHelper = new DeviceConfigShellHelper(
-                shellCommandExecutor);
+                mShellCommandExecutor);
 
         // This anticipates a future state where a generally applied target preparer may disable
         // device_config sync for all CTS tests: only suspend syncing if it isn't already suspended,
@@ -482,6 +495,23 @@
         setApplicationLocalesAndVerify(TEST_APP_PACKAGE_2, EMPTY_LOCALES);
     }
 
+    private boolean isAutoDetectionEnabled(
+            DeviceShellCommandExecutor shellCommandExecutor) throws Exception {
+        return shellCommandExecutor.executeToBoolean(SHELL_COMMAND_IS_AUTO_DETECTION_ENABLED);
+    }
+
+    private boolean setAutoTimeEnabled(
+            boolean enabled, DeviceShellCommandExecutor shellCommandExecutor) throws Exception {
+        // Android T does not have a dedicated shell command or API to change time auto detection
+        // setting, so direct Settings changes are used.
+        Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME,
+                enabled ? 1 : 0);
+
+        sleepForAsyncOperation();
+
+        return isAutoDetectionEnabled(shellCommandExecutor) == enabled;
+    }
+
     private static final class BlockingBroadcastReceiver extends BroadcastReceiver {
         private CountDownLatch mLatch = new CountDownLatch(1);
         private String mPackageName;
diff --git a/tests/camera/src/android/hardware/camera2/cts/MultiResolutionImageReaderTest.java b/tests/camera/src/android/hardware/camera2/cts/MultiResolutionImageReaderTest.java
index 35edd77..e7cb07a 100644
--- a/tests/camera/src/android/hardware/camera2/cts/MultiResolutionImageReaderTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/MultiResolutionImageReaderTest.java
@@ -18,8 +18,8 @@
 
 import android.graphics.ImageFormat;
 import android.hardware.HardwareBuffer;
-import android.hardware.camera2.CameraCharacteristics;
 import android.hardware.camera2.CameraCaptureSession;
+import android.hardware.camera2.CameraCharacteristics;
 import android.hardware.camera2.CameraDevice;
 import android.hardware.camera2.CaptureFailure;
 import android.hardware.camera2.CaptureRequest;
@@ -28,41 +28,37 @@
 import android.hardware.camera2.TotalCaptureResult;
 import android.hardware.camera2.cts.CameraTestUtils.HandlerExecutor;
 import android.hardware.camera2.cts.CameraTestUtils.SimpleCaptureCallback;
-import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
 import android.hardware.camera2.cts.helpers.StaticMetadata;
+import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
 import android.hardware.camera2.params.MandatoryStreamCombination;
-import android.hardware.camera2.params.MandatoryStreamCombination.MandatoryStreamInformation;
 import android.hardware.camera2.params.MultiResolutionStreamConfigurationMap;
 import android.hardware.camera2.params.MultiResolutionStreamInfo;
 import android.hardware.camera2.params.OutputConfiguration;
 import android.hardware.camera2.params.SessionConfiguration;
 import android.hardware.camera2.params.StreamConfigurationMap;
 import android.media.Image;
-import android.media.ImageReader;
 import android.util.Log;
-import android.util.Range;
 import android.util.Size;
 import android.view.Surface;
 
-import java.util.Arrays;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.LinkedBlockingQueue;
 
+import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
-import org.junit.Test;
 
-import static android.hardware.camera2.cts.CameraTestUtils.checkSessionConfigurationSupported;
 import static android.hardware.camera2.cts.CameraTestUtils.ImageAndMultiResStreamInfo;
-import static android.hardware.camera2.cts.CameraTestUtils.StreamCombinationTargets;
 import static android.hardware.camera2.cts.CameraTestUtils.SimpleMultiResolutionImageReaderListener;
+import static android.hardware.camera2.cts.CameraTestUtils.StreamCombinationTargets;
+import static android.hardware.camera2.cts.CameraTestUtils.checkSessionConfigurationSupported;
+
 import static junit.framework.Assert.assertNotNull;
 import static junit.framework.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+
 import static org.mockito.Mockito.*;
 
 /**
@@ -128,9 +124,15 @@
                     isLogicalCamera || isUltraHighResCamera);
 
             for (int format : multiResolutionOutputFormats) {
-                assertTrue(String.format("Camera %s: multi-resolution output format %d "
-                        + "isn't a supported format", id, format),
-                        CameraTestUtils.contains(outputFormats, format));
+                // Multi-resolution output format must be one of the supports stream configuration
+                // map formats, with the exception of RAW. It's valid for the camera device not to
+                // support RAW, but the multi-resolution ImageReader does.
+                if (format != ImageFormat.RAW_SENSOR && format != ImageFormat.RAW10
+                        && format != ImageFormat.RAW12 && format != ImageFormat.RAW_PRIVATE) {
+                    assertTrue(String.format("Camera %s: multi-resolution output format %d "
+                            + "isn't a supported format", id, format),
+                            CameraTestUtils.contains(outputFormats, format));
+                }
 
                 Collection<MultiResolutionStreamInfo> multiResolutionStreams =
                         multiResolutionMap.getOutputInfo(format);
@@ -522,6 +524,7 @@
 
             img.close();
             numImageVerified++;
+            retryCount = 0;
         }
     }
 }
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
index 37f6fa4..282269c 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -761,9 +761,6 @@
                             image = mLastReader.acquireLatestImage();
                             if (VERBOSE) Log.v(TAG, "acquireLatestImage from "
                                     + mLastReader.toString() + " produces " + image);
-                            if (image == null) {
-                                return null;
-                            }
                         } else {
                             fail("invalid image reader");
                         }
@@ -772,7 +769,7 @@
                 } else {
                     fail("wait for image available time out after " + timeoutMs + "ms");
                 }
-                return new ImageAndMultiResStreamInfo(image,
+                return image == null ? null : new ImageAndMultiResStreamInfo(image,
                         mOwner.getStreamInfoForImageReader(mLastReader));
             } else {
                 ImageAndMultiResStreamInfo imageAndInfo = mQueue.poll(timeoutMs,
diff --git a/tests/devicepolicy/src/android/devicepolicy/cts/DevicePolicyManagerTest.java b/tests/devicepolicy/src/android/devicepolicy/cts/DevicePolicyManagerTest.java
index ae9ced5..7a056de 100644
--- a/tests/devicepolicy/src/android/devicepolicy/cts/DevicePolicyManagerTest.java
+++ b/tests/devicepolicy/src/android/devicepolicy/cts/DevicePolicyManagerTest.java
@@ -1150,6 +1150,7 @@
     @Postsubmit(reason = "New test")
     @Test
     @EnsureHasPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS)
+    @RequireFeature(FEATURE_MANAGED_USERS)
     @RequireDoesNotHaveFeature(FEATURE_DEVICE_ADMIN)
     public void checkProvisioningPreCondition_withoutDeviceAdminFeature_returnsDeviceAdminNotSupported() {
         assertThat(
diff --git a/tests/devicestate/src/android/hardware/devicestate/cts/DeviceStateManagerTests.java b/tests/devicestate/src/android/hardware/devicestate/cts/DeviceStateManagerTests.java
index 230b75a..f6ff303 100644
--- a/tests/devicestate/src/android/hardware/devicestate/cts/DeviceStateManagerTests.java
+++ b/tests/devicestate/src/android/hardware/devicestate/cts/DeviceStateManagerTests.java
@@ -176,7 +176,8 @@
      * triggered with a value equal to the requested state.
      */
     @Test
-    public void testRequestStateSucceedsAsTopApp_ifStateDefinedAsAvailableForAppsToRequest() {
+    public void testRequestStateSucceedsAsTopApp_ifStateDefinedAsAvailableForAppsToRequest()
+            throws Throwable {
         final DeviceStateManager manager = getDeviceStateManager();
         final int[] supportedStates = manager.getSupportedStates();
 
@@ -209,7 +210,7 @@
         // checks that we were able to find a valid state to request.
         assumeTrue(nextState != INVALID_DEVICE_STATE);
 
-        activity.requestDeviceStateChange(nextState);
+        runWithControlDeviceStatePermission(() -> activity.requestDeviceStateChange(nextState));
 
         PollingCheck.waitFor(TIMEOUT, () -> callback.mCurrentState == nextState);
 
@@ -269,7 +270,7 @@
      * in a registered callback being triggered with a value equal to the base state.
      */
     @Test
-    public void testCancelStateRequestFromNewActivity() throws IllegalArgumentException {
+    public void testCancelStateRequestFromNewActivity() throws Throwable {
         final DeviceStateManager manager = getDeviceStateManager();
         final int[] supportedStates = manager.getSupportedStates();
         // We want to verify that the app can change device state
@@ -292,7 +293,7 @@
                 DEFAULT_DISPLAY
         );
 
-        DeviceStateTestActivity activity = activitySession.getActivity();
+        final DeviceStateTestActivity activity = activitySession.getActivity();
 
         int originalState = callback.mCurrentState;
 
@@ -303,7 +304,7 @@
         // checks that we were able to find a valid state to request.
         assumeTrue(nextState != INVALID_DEVICE_STATE);
 
-        activity.requestDeviceStateChange(nextState);
+        runWithControlDeviceStatePermission(() -> activity.requestDeviceStateChange(nextState));
 
         PollingCheck.waitFor(TIMEOUT, () -> callback.mCurrentState == nextState);
 
@@ -322,8 +323,8 @@
         // and launching the second activity.
         assertEquals(nextState, callback.mCurrentState);
 
-        activity = secondActivitySession.getActivity();
-        activity.cancelOverriddenState();
+        final DeviceStateTestActivity activity2 = secondActivitySession.getActivity();
+        activity2.cancelOverriddenState();
 
         PollingCheck.waitFor(TIMEOUT, () -> callback.mCurrentState == originalState);
 
diff --git a/tests/framework/base/windowmanager/jetpack/SecondApp/src/android/server/wm/jetpack/second/SecondActivityKnownEmbeddingCerts.java b/tests/framework/base/windowmanager/jetpack/SecondApp/src/android/server/wm/jetpack/second/SecondActivityUnknownEmbeddingCerts.java
similarity index 92%
rename from tests/framework/base/windowmanager/jetpack/SecondApp/src/android/server/wm/jetpack/second/SecondActivityKnownEmbeddingCerts.java
rename to tests/framework/base/windowmanager/jetpack/SecondApp/src/android/server/wm/jetpack/second/SecondActivityUnknownEmbeddingCerts.java
index 9bf28dc..c6a7c9b 100644
--- a/tests/framework/base/windowmanager/jetpack/SecondApp/src/android/server/wm/jetpack/second/SecondActivityKnownEmbeddingCerts.java
+++ b/tests/framework/base/windowmanager/jetpack/SecondApp/src/android/server/wm/jetpack/second/SecondActivityUnknownEmbeddingCerts.java
@@ -22,5 +22,5 @@
  * A test activity that requests trusted host certificates for embedding that does not match the
  * certificate of the host in CTS tests from 'android.server.wm.jetpack'.
  */
-public class SecondActivityKnownEmbeddingCerts extends Activity {
+public class SecondActivityUnknownEmbeddingCerts extends Activity {
 }
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingBoundsTests.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingBoundsTests.java
index 18fe90e..57a9fd5 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingBoundsTests.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingBoundsTests.java
@@ -69,13 +69,15 @@
         final Activity primaryActivity = startActivityNewTask(
                 TestConfigChangeHandlingActivity.class);
 
-        // Set split pair rule such that if the parent width is any smaller than it is now, then
+        // Set split pair rule such that if the parent bounds is any smaller than it is now, then
         // the parent cannot support a split.
         final int originalTaskWidth = getTaskWidth();
+        final int originalTaskHeight = getTaskHeight();
         final SplitPairRule splitPairRule = createSplitPairRuleBuilderWithJava8Predicate(
                 activityActivityPair -> true /* activityPairPredicate */,
                 activityIntentPair -> true /* activityIntentPredicate */,
-                parentWindowMetrics -> parentWindowMetrics.getBounds().width() >= originalTaskWidth)
+                parentWindowMetrics -> parentWindowMetrics.getBounds().width() >= originalTaskWidth
+                        && parentWindowMetrics.getBounds().height() >= originalTaskHeight)
                 .setSplitRatio(DEFAULT_SPLIT_RATIO).build();
         mActivityEmbeddingComponent.setEmbeddingRules(Collections.singleton(splitPairRule));
 
@@ -93,7 +95,7 @@
         for (int i = 0; i < numTimesToResize; i++) {
             // Shrink the display by 10% to make the activities stacked
             mReportedDisplayMetrics.setSize(new Size((int) (originalDisplaySize.getWidth() * 0.9),
-                    originalDisplaySize.getHeight()));
+                    (int) (originalDisplaySize.getHeight() * 0.9)));
             waitForFillsTask(secondaryActivity);
             waitAndAssertNotVisible(primaryActivity);
 
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingPlaceholderTests.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingPlaceholderTests.java
index e7235a2..0a105cf 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingPlaceholderTests.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ActivityEmbeddingPlaceholderTests.java
@@ -172,14 +172,16 @@
     @Test
     public void testPlaceholderFinishedWhenTaskWidthDecreased() {
         final int taskWidth = getTaskWidth();
+        final int taskHeight = getTaskHeight();
 
         // Set embedding rules with the parent window metrics only allowing side-by-side activities
-        // on a task width at least the current width.
+        // on a task bounds at least the current bounds.
         final SplitPlaceholderRule splitPlaceholderRule =
                 new SplitPlaceholderRuleBuilderWithDefaults(PRIMARY_ACTIVITY_ID,
                         PLACEHOLDER_ACTIVITY_ID)
-                        .setParentWindowMetrics(
-                                windowMetrics -> windowMetrics.getBounds().width() >= taskWidth)
+                        .setParentWindowMetrics(windowMetrics ->
+                                windowMetrics.getBounds().width() >= taskWidth
+                                        && windowMetrics.getBounds().height() >= taskHeight)
                         .build();
         mActivityEmbeddingComponent.setEmbeddingRules(Collections.singleton(splitPlaceholderRule));
 
@@ -189,11 +191,11 @@
         final TestActivity primaryActivity = (TestActivity) activityPair.first;
         final Activity placeholderActivity = activityPair.second;
 
-        // Shrink display width by 10% so that the primary and placeholder activities are stacked
+        // Shrink display size by 10% so that the primary and placeholder activities are stacked
         primaryActivity.resetBoundsChangeCounter();
         final Size currentSize = mReportedDisplayMetrics.getSize();
         mReportedDisplayMetrics.setSize(new Size((int) (currentSize.getWidth() * 0.9),
-                currentSize.getHeight()));
+                (int) (currentSize.getHeight() * 0.9)));
 
         // Verify that the placeholder activity was finished and that the primary activity now
         // fills the task.
@@ -208,16 +210,17 @@
      */
     @Test
     public void testPlaceholderLaunchedWhenTaskWidthIncreased() {
-        final int taskWidth = getTaskWidth();
+        final double splitTaskWidth = getTaskWidth() * 1.05;
+        final double splitTaskHeight = getTaskHeight() * 1.05;
 
         // Set embedding rules with the parent window metrics only allowing side-by-side activities
-        // on a task width 5% wider than the current task width.
+        // on a task bounds 5% larger than the current task bounds.
         final SplitPlaceholderRule splitPlaceholderRule =
                 new SplitPlaceholderRuleBuilderWithDefaults(PRIMARY_ACTIVITY_ID,
                         PLACEHOLDER_ACTIVITY_ID)
-                        .setParentWindowMetrics(
-                                windowMetrics ->
-                                        windowMetrics.getBounds().width() >= taskWidth * 1.05)
+                        .setParentWindowMetrics(windowMetrics ->
+                                windowMetrics.getBounds().width() >= splitTaskWidth
+                                        && windowMetrics.getBounds().height() >= splitTaskHeight)
                         .build();
         mActivityEmbeddingComponent.setEmbeddingRules(Collections.singleton(splitPlaceholderRule));
 
@@ -228,10 +231,10 @@
         verifyFillsTask(primaryActivity);
         waitAndAssertNotResumed(PLACEHOLDER_ACTIVITY_ID);
 
-        // Increase display width by 10% so that the primary and placeholder activities are stacked
+        // Increase display size by 10% so that the primary and placeholder activities are stacked
         final Size currentSize = mReportedDisplayMetrics.getSize();
         mReportedDisplayMetrics.setSize(new Size((int) (currentSize.getWidth() * 1.1),
-                currentSize.getHeight()));
+                (int) (currentSize.getHeight() * 1.1)));
 
         // Verify that the placeholder activity is launched into a split with the primary activity
         waitAndAssertResumed(PLACEHOLDER_ACTIVITY_ID);
@@ -247,14 +250,16 @@
     @Test
     public void testStickyPlaceholder() {
         final int taskWidth = getTaskWidth();
+        final int taskHeight = getTaskHeight();
 
         // Set embedding rules with isSticky set to true and the parent window metrics only allowing
         // side-by-side activities on a task width at least the current width.
         final SplitPlaceholderRule splitPlaceholderRule =
                 new SplitPlaceholderRuleBuilderWithDefaults(PRIMARY_ACTIVITY_ID,
                         PLACEHOLDER_ACTIVITY_ID).setIsSticky(true)
-                        .setParentWindowMetrics(
-                                windowMetrics -> windowMetrics.getBounds().width() >= taskWidth)
+                        .setParentWindowMetrics(windowMetrics ->
+                                windowMetrics.getBounds().width() >= taskWidth
+                                        && windowMetrics.getBounds().height() >= taskHeight)
                         .build();
         mActivityEmbeddingComponent.setEmbeddingRules(Collections.singleton(splitPlaceholderRule));
 
@@ -267,7 +272,7 @@
         placeholderActivity.resetBoundsChangeCounter();
         final Size currentSize = mReportedDisplayMetrics.getSize();
         mReportedDisplayMetrics.setSize(new Size((int) (currentSize.getWidth() * 0.9),
-                currentSize.getHeight()));
+                (int) (currentSize.getHeight() * 0.9)));
 
         // Verify that the placeholder was not finished and fills the task
         assertTrue(placeholderActivity.waitForBoundsChange());
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/WindowManagerJetpackTestBase.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/WindowManagerJetpackTestBase.java
index fb9f5e8..2c8c843 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/WindowManagerJetpackTestBase.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/WindowManagerJetpackTestBase.java
@@ -186,6 +186,11 @@
                 .width();
     }
 
+    public int getTaskHeight() {
+        return mContext.getSystemService(WindowManager.class).getMaximumWindowMetrics().getBounds()
+                .height();
+    }
+
     public static void setActivityOrientationActivityHandlesOrientationChanges(
             TestActivity activity, int orientation) {
         // Make sure that the provided orientation is a fixed orientation
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/ActivityMetricsLoggerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/ActivityMetricsLoggerTests.java
index 9293ed9..ff195a1 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/ActivityMetricsLoggerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/ActivityMetricsLoggerTests.java
@@ -162,6 +162,7 @@
     }
 
     private void assertTransitionIsStartingWindow(LogMaker log) {
+        if (isLeanBack()) return;
         assertEquals("transition should be started because of starting window",
                 1 /* APP_TRANSITION_STARTING_WINDOW */, log.getSubtype());
         assertNotNull("log should have starting window delay",
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 b585c04..4463efe 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardTransitionTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardTransitionTests.java
@@ -155,7 +155,7 @@
     @Test
     public void testNewActivityDuringOccludedWithAttr() {
         final LockScreenSession lockScreenSession = createManagedLockScreenSession();
-        launchActivity(SHOW_WHEN_LOCKED_ATTR_NO_PREVIEW_ACTIVITY);
+        launchActivityInFullscreen(SHOW_WHEN_LOCKED_ATTR_NO_PREVIEW_ACTIVITY);
         lockScreenSession.gotoKeyguard(SHOW_WHEN_LOCKED_ATTR_NO_PREVIEW_ACTIVITY);
         launchActivity(SHOW_WHEN_LOCKED_WITH_DIALOG_NO_PREVIEW_ACTIVITY);
         mWmState.computeState(SHOW_WHEN_LOCKED_WITH_DIALOG_NO_PREVIEW_ACTIVITY);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/RoundedCornerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/RoundedCornerTests.java
index 5f96dd3..1a452c0 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/RoundedCornerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/RoundedCornerTests.java
@@ -136,8 +136,6 @@
         });
 
         // Make sure the child window has been laid out.
-        final View childWindowRoot = activity.getChildWindowRoot();
-        PollingCheck.waitFor(TIMEOUT, () -> childWindowRoot.getWidth() > 0);
         PollingCheck.waitFor(TIMEOUT, () -> activity.getDispatchedInsets() != null);
         final WindowInsets insets = activity.getDispatchedInsets();
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
index 4958cc1..f6c1312 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
@@ -167,6 +167,7 @@
         // TODO(b/192431448): Allow Automotive to skip this test until Splash Screen is properly
         // applied insets by system bars in AAOS.
         assumeFalse(isCar());
+        assumeFalse(isLeanBack());
 
         final CommandSession.ActivitySession starter = prepareTestStarter();
         final ActivityOptions noIconOptions = ActivityOptions.makeBasic()
@@ -438,6 +439,7 @@
         // TODO(b/192431448): Allow Automotive to skip this test until Splash Screen is properly
         // applied insets by system bars in AAOS.
         assumeFalse(isCar());
+        assumeFalse(isLeanBack());
 
         final CommandSession.ActivitySession starter = prepareTestStarter();
         final ActivityOptions noIconOptions = ActivityOptions.makeBasic()
@@ -506,6 +508,7 @@
         // TODO(b/192431448): Allow Automotive to skip this test until Splash Screen is properly
         // applied insets by system bars in AAOS.
         assumeFalse(isCar());
+        assumeFalse(isLeanBack());
 
         final LauncherApps launcherApps = mContext.getSystemService(LauncherApps.class);
         final ShortcutManager shortcutManager = mContext.getSystemService(ShortcutManager.class);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowUntrustedTouchTest.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowUntrustedTouchTest.java
index cc4552d..04d18fa 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowUntrustedTouchTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowUntrustedTouchTest.java
@@ -33,6 +33,7 @@
 import static junit.framework.Assert.assertTrue;
 import static junit.framework.Assert.fail;
 
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import android.app.Activity;
@@ -76,6 +77,7 @@
 import androidx.test.ext.junit.rules.ActivityScenarioRule;
 
 import com.android.compatibility.common.util.AppOpsUtils;
+import com.android.compatibility.common.util.FeatureUtil;
 import com.android.compatibility.common.util.SystemUtil;
 
 import org.junit.After;
@@ -805,6 +807,7 @@
 
     @Test
     public void testWhenTextToastWindow_allowsTouch() throws Throwable {
+        assumeFalse("Watch does not support new Toast behavior yet.", FeatureUtil.isWatch());
         addToastOverlay(APP_A, /* custom */ false);
         Rect toast = mWmState.waitForResult("toast bounds",
                 state -> state.findFirstWindowWithType(LayoutParams.TYPE_TOAST).getFrame());
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index 03988ea..4608161 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -23,6 +23,7 @@
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.content.Intent.ACTION_MAIN;
 import static android.content.Intent.CATEGORY_HOME;
@@ -348,6 +349,11 @@
                 extras);
     }
 
+    protected static String getAmStartCmdWithWindowingMode(
+            final ComponentName activityName, int windowingMode) {
+        return getAmStartCmdInNewTask(activityName) + " --windowingMode " + windowingMode;
+    }
+
     protected WindowManagerStateHelper mWmState = new WindowManagerStateHelper();
     protected TouchHelper mTouchHelper = new TouchHelper(mInstrumentation, mWmState);
     // Initialized in setUp to execute with proper permission, such as MANAGE_ACTIVITY_TASKS
@@ -829,6 +835,12 @@
         mWmState.waitForValidState(activityName);
     }
 
+    protected void launchActivityInFullscreen(final ComponentName activityName) {
+        executeShellCommand(
+                getAmStartCmdWithWindowingMode(activityName, WINDOWING_MODE_FULLSCREEN));
+        mWmState.waitForValidState(activityName);
+    }
+
     protected static void waitForIdle() {
         getInstrumentation().waitForIdleSync();
     }
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodServiceTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodServiceTest.java
index 8e18ec1..a9cec51 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodServiceTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/InputMethodServiceTest.java
@@ -41,10 +41,12 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 
 import android.app.Activity;
 import android.app.Instrumentation;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.graphics.Matrix;
 import android.graphics.RectF;
 import android.inputmethodservice.InputMethodService;
@@ -713,6 +715,8 @@
 
     @Test
     public void testBatchEdit_commitAndSetComposingRegion_webView() throws Exception {
+        assumeTrue(hasFeatureWebView());
+
         getCommitAndSetComposingRegionTest(TIMEOUT,
                 "testBatchEdit_commitAndSetComposingRegion_webView/")
                 .setTestTextView(false)
@@ -729,6 +733,8 @@
 
     @Test
     public void testBatchEdit_commitSpaceThenSetComposingRegion_webView() throws Exception {
+        assumeTrue(hasFeatureWebView());
+
         getCommitSpaceAndSetComposingRegionTest(TIMEOUT,
                 "testBatchEdit_commitSpaceThenSetComposingRegion_webView/")
                 .setTestTextView(false)
@@ -747,12 +753,20 @@
     @Test
     public void testBatchEdit_getCommitSpaceAndSetComposingRegionTestInSelectionTest_webView()
             throws Exception {
+        assumeTrue(hasFeatureWebView());
+
         getCommitSpaceAndSetComposingRegionInSelectionTest(TIMEOUT,
                 "testBatchEdit_getCommitSpaceAndSetComposingRegionTestInSelectionTest_webView/")
                 .setTestTextView(false)
                 .runTest();
     }
 
+    private boolean hasFeatureWebView() {
+        final PackageManager pm =
+                InstrumentationRegistry.getInstrumentation().getContext().getPackageManager();
+        return pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW);
+    }
+
     @Test
     public void testImeVisibleAfterRotation() throws Exception {
         try (MockImeSession imeSession = MockImeSession.create(
diff --git a/tests/location/location_none/src/android/location/cts/none/LocationDisabledAppOpsTest.java b/tests/location/location_none/src/android/location/cts/none/LocationDisabledAppOpsTest.java
index ded4eca..b4c5c83 100644
--- a/tests/location/location_none/src/android/location/cts/none/LocationDisabledAppOpsTest.java
+++ b/tests/location/location_none/src/android/location/cts/none/LocationDisabledAppOpsTest.java
@@ -86,13 +86,16 @@
                 List<String> bypassedCheckOps = new ArrayList<>();
                 for (PackageInfo pi : pkgs) {
                     ApplicationInfo ai = pi.applicationInfo;
-                    if (ai.uid != Process.SYSTEM_UID) {
+                    int appId = UserHandle.getAppId(ai.uid);
+                    if (appId != Process.SYSTEM_UID) {
                         final int[] mode = {MODE_ALLOWED};
+                        final boolean[] isProvider = {false};
                         runWithShellPermissionIdentity(() -> {
                             mode[0] = mAom.noteOpNoThrow(
                                     OPSTR_FINE_LOCATION, ai.uid, ai.packageName);
+                            isProvider[0] = mLm.isProviderPackage(null, pi.packageName, null);
                             if (mode[0] == MODE_ALLOWED && !ignoreList.containsAll(pi.packageName)
-                                    && !mLm.isProviderPackage(null, pi.packageName, null)) {
+                                    && !isProvider[0]) {
                                 bypassedNoteOps.add(pi.packageName);
                             }
                         });
@@ -102,8 +105,9 @@
                         runWithShellPermissionIdentity(() -> {
                             mode[0] = mAom
                                     .checkOpNoThrow(OPSTR_FINE_LOCATION, ai.uid, ai.packageName);
+                            isProvider[0] = mLm.isProviderPackage(null, pi.packageName, null);
                             if (mode[0] == MODE_ALLOWED && !ignoreList.includes(pi.packageName)
-                                    && !mLm.isProviderPackage(null, pi.packageName, null)) {
+                                    && !isProvider[0]) {
                                 bypassedCheckOps.add(pi.packageName);
                             }
                         });
diff --git a/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java b/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java
index 1e44a00..155161a 100644
--- a/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java
+++ b/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java
@@ -29,6 +29,7 @@
 import androidx.test.filters.SmallTest;
 
 import com.android.compatibility.common.util.ApiLevelUtil;
+import com.android.compatibility.common.util.MediaUtils;
 
 import org.junit.Assume;
 import org.junit.Test;
@@ -305,6 +306,13 @@
                 mCodec.release();
                 return;
             }
+            /* TODO(b/181126614, b/268175825) */
+            if (MediaUtils.isPc()) {
+                Log.d(LOG_TAG, "test skipped due to b/181126614, b/268175825");
+                mCodec.release();
+                return;
+            }
+
             String log = String.format("format: %s \n codec: %s:: ", mConfigFormat, mCodecName);
             File tmpFile;
             int muxerFormat;
diff --git a/tests/tests/app/AndroidManifest.xml b/tests/tests/app/AndroidManifest.xml
index ef8c1a8..3eab632 100644
--- a/tests/tests/app/AndroidManifest.xml
+++ b/tests/tests/app/AndroidManifest.xml
@@ -22,7 +22,7 @@
         <uses-library android:name="android.test.runner" />
 
         <activity android:name=".ApplyOverrideConfigurationActivity"
-                  android:configChanges="orientation|screenSize" />
+                  android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout" />
 
         <activity android:name=".PictureInPictureActivity"
                   android:resizeableActivity="false"
diff --git a/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java b/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
index 755ac44..6ea6023 100644
--- a/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
+++ b/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
@@ -17,6 +17,7 @@
 package android.appenumeration.cts;
 
 import static android.Manifest.permission.SET_PREFERRED_APPLICATIONS;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.appenumeration.cts.Constants.ACTION_AWAIT_LAUNCHER_APPS_CALLBACK;
 import static android.appenumeration.cts.Constants.ACTION_AWAIT_LAUNCHER_APPS_SESSION_CALLBACK;
 import static android.appenumeration.cts.Constants.ACTION_BIND_SERVICE;
@@ -163,6 +164,7 @@
 import android.Manifest;
 import android.accounts.Account;
 import android.accounts.AccountManager;
+import android.app.ActivityOptions;
 import android.app.PendingIntent;
 import android.appwidget.AppWidgetProviderInfo;
 import android.content.ComponentName;
@@ -2532,7 +2534,10 @@
             AmUtils.waitForBroadcastIdle();
             startAndWaitForCommandReady(intent);
         } else {
-            InstrumentationRegistry.getInstrumentation().getContext().startActivity(intent);
+            final ActivityOptions options = ActivityOptions.makeBasic();
+            options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
+            InstrumentationRegistry.getInstrumentation().getContext().startActivity(
+                    intent, options.toBundle());
         }
         return () -> {
             if (!latch.block(TimeUnit.SECONDS.toMillis(10))) {
diff --git a/tests/tests/car/src/android/car/cts/CarServiceHelperServiceUpdatableTest.java b/tests/tests/car/src/android/car/cts/CarServiceHelperServiceUpdatableTest.java
index ed42e79..80229ec 100644
--- a/tests/tests/car/src/android/car/cts/CarServiceHelperServiceUpdatableTest.java
+++ b/tests/tests/car/src/android/car/cts/CarServiceHelperServiceUpdatableTest.java
@@ -43,6 +43,7 @@
 import com.android.compatibility.common.util.SystemUtil;
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 
 import java.io.BufferedReader;
@@ -66,6 +67,7 @@
     }
 
     @Test
+    @Ignore("b/234674080")
     public void testCarServiceHelperServiceDump() throws Exception {
         assumeThat("System_server_dumper not implemented.",
                 executeShellCommand("service check system_server_dumper"),
diff --git a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContractIntentsTest.java b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContractIntentsTest.java
index 488547d..9edc805 100644
--- a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContractIntentsTest.java
+++ b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContractIntentsTest.java
@@ -56,8 +56,12 @@
     }
 
     public void testSetDefaultAccount() {
-        Intent intent = new Intent(ContactsContract.Settings.ACTION_SET_DEFAULT_ACCOUNT);
         PackageManager packageManager = getContext().getPackageManager();
+        if (packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+            return; // Skip test on watch since the intent is not required.
+        }
+
+        Intent intent = new Intent(ContactsContract.Settings.ACTION_SET_DEFAULT_ACCOUNT);
         List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
         assertNotNull("Missing ResolveInfo", resolveInfoList);
         int handlerCount = 0;
diff --git a/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java b/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java
index 5db5f66..d3e4c91 100644
--- a/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java
+++ b/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java
@@ -28,6 +28,8 @@
 import static android.view.WindowInsets.Type.navigationBars;
 import static android.view.WindowInsets.Type.systemBars;
 
+import static android.server.wm.ActivityManagerTestBase.isTablet;
+
 import android.app.Activity;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
diff --git a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
index db58721..4c2d2fd 100644
--- a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
+++ b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
@@ -98,6 +98,8 @@
 
     companion object {
         const val LOG_TAG = "AutoRevokeTest"
+        const val REQUEST_ALLOWLIST_BTN_TEXT = "Request allowlist"
+        const val ALLOWLIST_TEXTVIEW_STATUS = "Auto-revoke allowlisted: "
 
         @JvmStatic
         @BeforeClass
@@ -314,7 +316,14 @@
                 assertAllowlistState(false)
 
                 // Verify
-                waitFindObject(byTextIgnoreCase("Request allowlist")).click()
+                if (hasFeatureWatch()) {
+                    waitFindNode(hasTextThat(
+                            containsStringIgnoringCase(
+                                REQUEST_ALLOWLIST_BTN_TEXT))).click()
+                } else {
+                    waitFindObject(byTextIgnoreCase(
+                            REQUEST_ALLOWLIST_BTN_TEXT)).click()
+                }
                 waitFindObject(byTextIgnoreCase("Permissions")).click()
                 val autoRevokeEnabledToggle = getAllowlistToggle()
                 assertTrue(autoRevokeEnabledToggle.isChecked())
@@ -523,9 +532,14 @@
     }
 
     private fun assertAllowlistState(state: Boolean) {
-        assertThat(
-            waitFindObject(By.textStartsWith("Auto-revoke allowlisted: ")).text,
-            containsString(state.toString()))
+        if (hasFeatureWatch()) {
+            waitFindNode(hasTextThat(containsStringIgnoringCase(
+                    ALLOWLIST_TEXTVIEW_STATUS + state.toString())))
+        } else {
+            assertThat(
+                    waitFindObject(By.textStartsWith(ALLOWLIST_TEXTVIEW_STATUS)).text,
+                    containsString(state.toString()))
+        }
     }
 
     private fun getAllowlistToggle(): UiObject2 {
diff --git a/tests/tests/permission2/res/raw/automotive_android_manifest.xml b/tests/tests/permission2/res/raw/automotive_android_manifest.xml
index aa263ea..d275ef4 100644
--- a/tests/tests/permission2/res/raw/automotive_android_manifest.xml
+++ b/tests/tests/permission2/res/raw/automotive_android_manifest.xml
@@ -482,4 +482,8 @@
         android:protectionLevel="signature|privileged"
         android:label="@string/car_permission_label_manage_thread_priority"
         android:description="@string/car_permission_desc_manage_thread_priority"/>
+    <permission android:name="android.car.permission.BIND_OEM_CAR_SERVICE"
+        android:protectionLevel="signature|privileged"
+        android:label="@string/car_permission_label_bind_oem_car_service"
+        android:description="@string/car_permission_desc_bind_oem_car_service"/>
 </manifest>
diff --git a/tests/tests/permission2/res/raw/wear_android_manifest.xml b/tests/tests/permission2/res/raw/wear_android_manifest.xml
new file mode 100644
index 0000000..08488bc
--- /dev/null
+++ b/tests/tests/permission2/res/raw/wear_android_manifest.xml
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2023 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.
+  -->
+<!-- This file contains permissions which were back ported.
+     These permissions are already present on future platform releases.
+    -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android" coreApp="true" android:sharedUserId="android.uid.system"
+          android:sharedUserLabel="@string/android_system_label">
+
+   <!-- @hide Allows an application to access wrist temperature data from the watch sensors.
+   <p class="note"><strong>Note: </strong> This permission is for Wear OS only.
+   <p>Protection level: dangerous -->
+    <permission android:name="android.permission.BODY_SENSORS_WRIST_TEMPERATURE"
+                android:permissionGroup="android.permission-group.UNDEFINED"
+                android:label="@string/permlab_bodySensorsWristTemperature"
+                android:description="@string/permdesc_bodySensorsWristTemperature"
+                android:backgroundPermission="android.permission.BODY_SENSORS_WRIST_TEMPERATURE_BACKGROUND"
+                android:protectionLevel="dangerous" />
+
+    <!-- @hide Allows an application to access wrist temperature data from the watch sensors.
+         If you're requesting this permission, you must also request
+         {@link #BODY_SENSORS_WRIST_TEMPERATURE}. Requesting this permission by itself doesn't
+         give you wrist temperature body sensors access.
+         <p class="note"><strong>Note: </strong> This permission is for Wear OS only.
+         <p>Protection level: dangerous
+
+         <p> This is a hard restricted permission which cannot be held by an app until
+         the installer on record allowlists the permission. For more details see
+         {@link android.content.pm.PackageInstaller.SessionParams#setWhitelistedRestrictedPermissions(Set)}.
+    -->
+    <permission android:name="android.permission.BODY_SENSORS_WRIST_TEMPERATURE_BACKGROUND"
+                android:permissionGroup="android.permission-group.UNDEFINED"
+                android:label="@string/permlab_bodySensors_wristTemperature_background"
+                android:description="@string/permdesc_bodySensors_wristTemperature_background"
+                android:protectionLevel="dangerous"
+                android:permissionFlags="hardRestricted" />
+
+</manifest>
\ No newline at end of file
diff --git a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
index 8e32636..6373803 100644
--- a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
@@ -20,6 +20,8 @@
 import static android.content.pm.PermissionInfo.PROTECTION_MASK_BASE;
 import static android.os.Build.VERSION.SECURITY_PATCH;
 
+import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
+
 import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.Manifest;
@@ -29,6 +31,7 @@
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.PermissionGroupInfo;
 import android.content.pm.PermissionInfo;
+import android.os.Build;
 import android.os.Process;
 import android.os.SystemProperties;
 import android.platform.test.annotations.AppModeFull;
@@ -74,6 +77,9 @@
     private static final String SET_UNRESTRICTED_GESTURE_EXCLUSION
             = "android.permission.SET_UNRESTRICTED_GESTURE_EXCLUSION";
 
+    private static final String BIND_OEM_CAR_SERVICE =
+            "android.car.permission.BIND_OEM_CAR_SERVICE";
+
     private static final String RECEIVE_KEYCODE_EVENTS_PERMISSION =
             "android.permission.RECEIVE_KEYCODE_EVENTS";
 
@@ -170,6 +176,9 @@
             }
             declaredPermissionsMap.putAll(carServiceBuiltInPermissionsMap);
         }
+        if (sContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+            expectedPermissions.addAll(loadExpectedPermissions(R.raw.wear_android_manifest));
+        }
 
         for (ExpectedPermissionInfo expectedPermission : expectedPermissions) {
             String expectedPermissionName = expectedPermission.name;
@@ -538,6 +547,8 @@
                 return parseDate(SECURITY_PATCH).before(MANAGE_COMPANION_DEVICES_PATCH_DATE);
             case SET_UNRESTRICTED_GESTURE_EXCLUSION:
                 return true;
+            case BIND_OEM_CAR_SERVICE:
+                return shoudldSkipBindOemCarService();
             case RECEIVE_KEYCODE_EVENTS_PERMISSION:
                 return true;
             default:
@@ -545,6 +556,21 @@
         }
     }
 
+    /**
+     * check should be skipped only for T and T-QPR1
+     */
+    private boolean shoudldSkipBindOemCarService() {
+        if (Build.VERSION.SDK_INT > 33) {
+            return false;
+        }
+        String output = runShellCommand("dumpsys car_service --version");
+        if (output.contains("Car API minor: 0") || output.contains("Car API minor: 1")) {
+            return true;
+        }
+
+        return false;
+    }
+
     private static boolean shouldAllowProtectionFlagsChange(
             String permissionName, int expectedFlags, int actualFlags) {
         return (ACCESS_SHORTCUTS_PERMISSION.equals(permissionName)
diff --git a/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt b/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt
index a1eca49..feaf20e 100644
--- a/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt
+++ b/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt
@@ -54,6 +54,7 @@
 import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
 import android.Manifest.permission_group.UNDEFINED
 import android.app.AppOpsManager.permissionToOp
+import android.content.pm.PackageManager
 import android.content.pm.PackageManager.GET_PERMISSIONS
 import android.content.pm.PermissionInfo.PROTECTION_DANGEROUS
 import android.content.pm.PermissionInfo.PROTECTION_FLAG_APPOP
@@ -161,6 +162,23 @@
         expectedPerms.add(POST_NOTIFICATIONS)
         expectedPerms.add(NEARBY_WIFI_DEVICES)
 
+        // Add runtime permissions added in V (back ported from U) which were _not_ split from a
+        // previously existing runtime permission
+        if (context.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+            expectedPerms.add(BODY_SENSORS_WRIST_TEMPERATURE)
+            expectedPerms.add(BODY_SENSORS_WRIST_TEMPERATURE_BACKGROUND)
+        }
+
         assertThat(expectedPerms).containsExactlyElementsIn(platformRuntimePerms.map { it.name })
     }
+
+    companion object {
+        // These permissions are back ported from Android U to tm-wear, hidden in the
+        // "core/res/AndroidManifest.xml" file of /framework/base repo. Added these 2 constants here
+        // because hidden permissions can't be imported like other imported permissions in this file
+        private const val BODY_SENSORS_WRIST_TEMPERATURE =
+                "android.permission.BODY_SENSORS_WRIST_TEMPERATURE"
+        private const val BODY_SENSORS_WRIST_TEMPERATURE_BACKGROUND =
+                "android.permission.BODY_SENSORS_WRIST_TEMPERATURE_BACKGROUND"
+    }
 }
diff --git a/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java b/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
index 84707ea..69d0586 100644
--- a/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
+++ b/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
@@ -1634,11 +1634,8 @@
         mTuner.close();
         mTuner = null;
 
-        // check the sharee is also closed
-        // tune() would have failed even before close() but still..
-        // TODO: fix this once callback sharing is implemented
-        res = sharee.tune(feSettings);
-        assertEquals(Tuner.RESULT_UNAVAILABLE, res);
+        // check the frontend of sharee is also released
+        assertNull(sharee.getFrontendInfo());
 
         sharee.close();
 
@@ -1660,7 +1657,6 @@
         assertNotNull(statusCapabilities);
         FrontendStatus status = mTuner.getFrontendStatus(statusCapabilities);
         assertNotNull(status);
-
     }
 
     @Test
diff --git a/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java b/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
index fa4833c..8326962 100644
--- a/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
+++ b/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
@@ -392,15 +392,17 @@
         CtsTouchUtils.emulateLongPressOnViewCenter(mInstrumentation, mActivityRule, mEditText);
         verify(onLongClickListener, within(1000)).onLongClick(mEditText);
 
+        // Wait for the UI Thread to become idle.
+        final UiDevice device = UiDevice.getInstance(mInstrumentation);
+
         // click the Cancel button
         mActivityRule.runOnUiThread(() -> mEditText.setText("Germany"));
         mInstrumentation.waitForIdleSync();
+        device.waitForIdle();
 
         CtsTouchUtils.emulateTapOnViewCenter(mInstrumentation, mActivityRule, mButtonCancel);
         assertEquals("", mEditText.getText().toString());
 
-        // Wait for the UI Thread to become idle.
-        final UiDevice device = UiDevice.getInstance(mInstrumentation);
         mInstrumentation.waitForIdleSync();
         device.waitForIdle();
 
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
index d170559..45f5325 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
@@ -18,6 +18,7 @@
 
 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
+import static android.net.wifi.SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD;
 import static android.net.wifi.WifiAvailableChannel.OP_MODE_SAP;
 import static android.net.wifi.WifiAvailableChannel.OP_MODE_STA;
 import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
@@ -2743,6 +2744,10 @@
                     () -> mWifiManager.isWifiEnabled() == true);
                 turnOffWifiAndTetheredHotspotIfEnabled();
                 verifyRegisterSoftApCallback(executor, callback);
+                if (!callback.getCurrentSoftApCapability()
+                        .areFeaturesSupported(SOFTAP_FEATURE_ACS_OFFLOAD)) {
+                    return;
+                }
                 int[] testBands = {SoftApConfiguration.BAND_2GHZ,
                         SoftApConfiguration.BAND_5GHZ};
                 int[] expectedBands = {SoftApConfiguration.BAND_2GHZ,