Merge "Ignore OneTimePermissionTest on Automotive" into rvc-dev
diff --git a/apps/CameraITS/build/scripts/gpylint_rcfile b/apps/CameraITS/build/scripts/gpylint_rcfile
index f92c613..b9c16f4 100644
--- a/apps/CameraITS/build/scripts/gpylint_rcfile
+++ b/apps/CameraITS/build/scripts/gpylint_rcfile
@@ -318,7 +318,7 @@
 
 [MASTER]
 
-# Add files or directories to the blacklist. They should be base names, not
+# Add files or directories to the ignorelist. They should be base names, not
 # paths.
 ignore=CVS
 
diff --git a/apps/CameraITS/tests/scene3/test_flip_mirror.py b/apps/CameraITS/tests/scene3/test_flip_mirror.py
index b4677c7..0a90712 100644
--- a/apps/CameraITS/tests/scene3/test_flip_mirror.py
+++ b/apps/CameraITS/tests/scene3/test_flip_mirror.py
@@ -64,7 +64,7 @@
     patch = 255 * its.cv2image.gray_scale_img(patch)
     patch = its.cv2image.scale_img(patch.astype(np.uint8), chart.scale)
 
-    # sanity check on image
+    # validity check on image
     assert np.max(patch)-np.min(patch) > 255/8
 
     # save full images if in debug
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 dcca509..14e381c 100644
--- a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
+++ b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
@@ -1,4 +1,4 @@
-# Copyright 2015 The Android Open Source Project
+# Copyright 2015 The Android Open Source Project (lint as: python2)
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -41,6 +41,40 @@
 AR_DIFF_ATOL = 0.01
 
 
+def print_failed_test_results(failed_ar, failed_fov, failed_crop):
+    """Print failed test results."""
+    if failed_ar:
+        print "\nAspect ratio test summary"
+        print "Images failed in the aspect ratio test:"
+        print "Aspect ratio value: width / height"
+        for fa in failed_ar:
+            print "%s with %s %dx%d: %.3f;" % (
+                    fa["fmt_iter"], fa["fmt_cmpr"],
+                    fa["w"], fa["h"], fa["ar"]),
+            print "valid range: %.3f ~ %.3f" % (
+                    fa["valid_range"][0], fa["valid_range"][1])
+
+    if failed_fov:
+        print "\nFoV test summary"
+        print "Images failed in the FoV test:"
+        for fov in failed_fov:
+            print fov
+
+    if failed_crop:
+        print "\nCrop test summary"
+        print "Images failed in the crop test:"
+        print "Circle center position, (horizontal x vertical), listed",
+        print "below is relative to the image center."
+        for fc in failed_crop:
+            print "%s with %s %dx%d: %.3f x %.3f;" % (
+                    fc["fmt_iter"], fc["fmt_cmpr"], fc["w"], fc["h"],
+                    fc["ct_hori"], fc["ct_vert"]),
+            print "valid horizontal range: %.3f ~ %.3f;" % (
+                    fc["valid_range_h"][0], fc["valid_range_h"][1]),
+            print "valid vertical range: %.3f ~ %.3f" % (
+                    fc["valid_range_v"][0], fc["valid_range_v"][1])
+
+
 def is_checked_aspect_ratio(first_api_level, w, h):
     if first_api_level >= 30:
         return True
@@ -182,6 +216,7 @@
 
     Returns:
         ref_fov:    dict with [fmt, % coverage, w, h, circle_w, circle_h]
+        cc_ct_gt:   circle center position relative to the center of image.
     """
     ref_fov = {}
     fmt = its.objects.get_largest_jpeg_format(props)
@@ -193,8 +228,8 @@
     img = its.image.convert_capture_to_rgb_image(cap, props=props)
     print "Captured JPEG %dx%d" % (w, h)
     img_name = "%s_jpeg_w%d_h%d.png" % (NAME, w, h)
-    # Set debug to True to save the debug image
-    _, _, circle_size = measure_aspect_ratio(img, img_name, False, debug=True)
+    # Set debug to True to save the reference image
+    _, cc_ct_gt, circle_size = measure_aspect_ratio(img, img_name, False, debug=True)
     fov_percent = calc_circle_image_ratio(circle_size[0], circle_size[1], w, h)
     ref_fov["fmt"] = "JPEG"
     ref_fov["percent"] = fov_percent
@@ -203,7 +238,7 @@
     ref_fov["circle_w"] = circle_size[0]
     ref_fov["circle_h"] = circle_size[1]
     print "Using JPEG reference:", ref_fov
-    return ref_fov
+    return ref_fov, cc_ct_gt
 
 
 def calc_circle_image_ratio(circle_w, circle_h, image_w, image_h):
@@ -284,7 +319,7 @@
         # 3. Child"s width > 0.1*Image width
         # 4. Child"s height > 0.1*Image height
         # 5. 0.25*Parent"s area < Child"s area < 0.45*Parent"s area
-        # 6. Child is a black, and Parent is white
+        # 6. Child == 0, and Parent == 255
         # 7. Center of Child and center of parent should overlap
         if (prt_shape["width"] * 0.56 < child_shape["width"]
                     < prt_shape["width"] * 0.76
@@ -469,7 +504,11 @@
                   # as reference frame; otherwise the highest resolution JPEG is used.
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
+        fls_logical = props['android.lens.info.availableFocalLengths']
+        print 'logical available focal lengths: %s', str(fls_logical)
         props = cam.override_with_hidden_physical_camera_props(props)
+        fls_physical = props['android.lens.info.availableFocalLengths']
+        print 'physical available focal lengths: %s', str(fls_physical)
         # determine skip conditions
         first_api = its.device.get_first_api_level(its.device.get_device_id())
         if first_api < 30:  # original constraint
@@ -491,11 +530,11 @@
         cam.do_3a()
         req = its.objects.auto_capture_request()
 
-        # If raw capture is available, use it as ground truth.
-        if raw_avlb:
+        # If raw is available and main camera, use it as ground truth.
+        if raw_avlb and (fls_physical == fls_logical):
             ref_fov, cc_ct_gt, aspect_ratio_gt = find_raw_fov_reference(cam, req, props, debug)
         else:
-            ref_fov = find_jpeg_fov_reference(cam, req, props)
+            ref_fov, cc_ct_gt = find_jpeg_fov_reference(cam, req, props)
 
         if run_crop_test:
             # Normalize the circle size to 1/4 of the image size, so that
@@ -624,47 +663,12 @@
                                             "valid_range_v": thres_range_v_cp})
                         its.image.write_image(img/255, img_name, True)
 
-        # Print aspect ratio test results
-        failed_image_number_for_aspect_ratio_test = len(failed_ar)
-        if failed_image_number_for_aspect_ratio_test > 0:
-            print "\nAspect ratio test summary"
-            print "Images failed in the aspect ratio test:"
-            print "Aspect ratio value: width / height"
-            for fa in failed_ar:
-                print "%s with %s %dx%d: %.3f;" % (
-                        fa["fmt_iter"], fa["fmt_cmpr"],
-                        fa["w"], fa["h"], fa["ar"]),
-                print "valid range: %.3f ~ %.3f" % (
-                        fa["valid_range"][0], fa["valid_range"][1])
-
-        # Print FoV test results
-        failed_image_number_for_fov_test = len(failed_fov)
-        if failed_image_number_for_fov_test > 0:
-            print "\nFoV test summary"
-            print "Images failed in the FoV test:"
-            for fov in failed_fov:
-                print fov
-
-        # Print crop test results
-        failed_image_number_for_crop_test = len(failed_crop)
-        if failed_image_number_for_crop_test > 0:
-            print "\nCrop test summary"
-            print "Images failed in the crop test:"
-            print "Circle center position, (horizontal x vertical), listed",
-            print "below is relative to the image center."
-            for fc in failed_crop:
-                print "%s with %s %dx%d: %.3f x %.3f;" % (
-                        fc["fmt_iter"], fc["fmt_cmpr"], fc["w"], fc["h"],
-                        fc["ct_hori"], fc["ct_vert"]),
-                print "valid horizontal range: %.3f ~ %.3f;" % (
-                        fc["valid_range_h"][0], fc["valid_range_h"][1]),
-                print "valid vertical range: %.3f ~ %.3f" % (
-                        fc["valid_range_v"][0], fc["valid_range_v"][1])
-
-        assert failed_image_number_for_aspect_ratio_test == 0
-        assert failed_image_number_for_fov_test == 0
+        # Print failed any test results
+        print_failed_test_results(failed_ar, failed_fov, failed_crop)
+        assert not failed_ar
+        assert not failed_fov
         if level3_device:
-            assert failed_image_number_for_crop_test == 0
+            assert not failed_crop
 
 
 if __name__ == "__main__":
diff --git a/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py b/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
index 94e5c6b..2d08267 100644
--- a/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
+++ b/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
@@ -26,8 +26,8 @@
 
 import numpy as np
 
-ALIGN_TOL_MM = 4.0E-3  # mm
-ALIGN_TOL = 0.01  # multiplied by sensor diagonal to convert to pixels
+ALIGN_ATOL_MM = 10E-3  # mm
+ALIGN_RTOL = 0.01  # multiplied by sensor diagonal to convert to pixels
 CIRCLE_RTOL = 0.1
 GYRO_REFERENCE = 1
 LENS_FACING_BACK = 1  # 0: FRONT, 1: BACK, 2: EXTERNAL
@@ -241,7 +241,7 @@
         gray:           numpy grayscale array with pixel values in [0,255].
         name:           string of file name.
     Returns:
-        circle:         (circle_center_x, circle_center_y, radius)
+        circle:         {'x': val, 'y': val, 'r': val}
     """
     size = gray.shape
     # otsu threshold to binarize the image
@@ -282,7 +282,7 @@
         # 3. Child's width > 0.1*Image width
         # 4. Child's height > 0.1*Image height
         # 5. 0.25*Parent's area < Child's area < 0.45*Parent's area
-        # 6. Child is a black, and Parent is white
+        # 6. Child == 0, and Parent == 255
         # 7. Center of Child and center of parent should overlap
         if (prt_shape['width'] * 0.56 < child_shape['width']
                     < prt_shape['width'] * 0.76
@@ -315,7 +315,7 @@
         print 'More than one black circle was detected. Background of scene',
         print 'may be too complex.\n'
         assert num_circle == 1
-    return [circle_ctx, circle_cty, (circle_w+circle_h)/4.0]
+    return {'x': circle_ctx, 'y': circle_cty, 'r': (circle_w+circle_h)/4.0}
 
 
 def define_reference_camera(pose_reference, cam_reference):
@@ -335,6 +335,9 @@
         i_2nd = list(cam_reference.keys())[1]
     else:
         print 'pose_reference is CAMERA'
+        num_ref_cameras = len([v for v in cam_reference.itervalues() if v])
+        e_msg = 'Too many/few reference cameras: %s' % str(cam_reference)
+        assert num_ref_cameras == 1, e_msg
         i_ref = (k for (k, v) in cam_reference.iteritems() if v).next()
         i_2nd = (k for (k, v) in cam_reference.iteritems() if not v).next()
     return i_ref, i_2nd
@@ -357,7 +360,7 @@
     world coordinates.
 
     Reproject the world coordinates back to pixel coordinates and compare
-    against originals as a sanity check.
+    against originals as a validity check.
 
     Compare the circle sizes if the focal lengths of the cameras are
     different using
@@ -378,7 +381,6 @@
                              its.caps.logical_multi_camera(props) and
                              its.caps.backward_compatible(props))
         debug = its.caps.debug_mode()
-        avail_fls = props['android.lens.info.availableFocalLengths']
         pose_reference = props['android.lens.poseReference']
 
         # Convert chart_distance for lens facing back
@@ -458,6 +460,7 @@
         circle = {}
         fl = {}
         sensor_diag = {}
+        pixel_sizes = {}
         capture_cam_ids = physical_ids
         if fmt == 'raw':
             capture_cam_ids = physical_raw_ids
@@ -519,7 +522,7 @@
                 print 't:', t[i]
                 print 'r:', r[i]
 
-            # Correct lens distortion to image (if available)
+            # Correct lens distortion to RAW image (if available)
             if its.caps.distortion_correction(physical_props[i]) and fmt == 'raw':
                 distort = np.array(physical_props[i]['android.lens.distortion'])
                 assert len(distort) == 5, 'distortion has wrong # of params.'
@@ -536,26 +539,37 @@
             # Find the circles in grayscale image
             circle[i] = find_circle(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),
                                     '%s_%s_gray_%s.jpg' % (NAME, fmt, i))
-            print 'Circle radius ', i, ': ', circle[i][2]
+            print 'Circle %s radius: %.3f' % (i, circle[i]['r'])
 
             # Undo zoom to image (if applicable). Assume that the maximum
             # physical YUV image size is close to active array size.
             if fmt == 'yuv':
-                ar = physical_props[i]['android.sensor.info.activeArraySize']
-                arw = ar['right'] - ar['left']
-                arh = ar['bottom'] - ar['top']
+                yuv_w = caps[(fmt, i)]['width']
+                yuv_h = caps[(fmt, i)]['height']
+                print 'cap size: %d x %d' % (yuv_w, yuv_h)
                 cr = caps[(fmt, i)]['metadata']['android.scaler.cropRegion']
                 crw = cr['right'] - cr['left']
                 crh = cr['bottom'] - cr['top']
                 # Assume pixels remain square after zoom, so use same zoom
                 # ratios for x and y.
-                zoom_ratio = min(1.0 * arw / crw, 1.0 * arh / crh)
-                circle[i][0] = cr['left'] + circle[i][0] / zoom_ratio
-                circle[i][1] = cr['top'] + circle[i][1] / zoom_ratio
-                circle[i][2] = circle[i][2] / zoom_ratio
+                zoom_ratio = min(1.0 * yuv_w / crw, 1.0 * yuv_h / crh)
+                circle[i]['x'] = cr['left'] + circle[i]['x'] / zoom_ratio
+                circle[i]['y'] = cr['top'] + circle[i]['y'] / zoom_ratio
+                circle[i]['r'] = circle[i]['r'] / zoom_ratio
+                print ' Calculated zoom_ratio:', zoom_ratio
+                print ' Corrected circle X:', circle[i]['x']
+                print ' Corrected circle Y:', circle[i]['y']
+                print ' Corrected circle radius : %.3f'  % circle[i]['r']
 
-            # Find focal length & sensor size
+            # Find focal length and pixel & sensor size
             fl[i] = physical_props[i]['android.lens.info.availableFocalLengths'][0]
+            ar = physical_props[i]['android.sensor.info.activeArraySize']
+            sensor_size = physical_props[i]['android.sensor.info.physicalSize']
+            pixel_size_w = sensor_size['width'] / (ar['right'] - ar['left'])
+            pixel_size_h = sensor_size['height'] / (ar['bottom'] - ar['top'])
+            print 'pixel size(um): %.2f x %.2f' % (
+                pixel_size_w*1E3, pixel_size_h*1E3)
+            pixel_sizes[i] = (pixel_size_w + pixel_size_h) / 2 * 1E3
             sensor_diag[i] = math.sqrt(size[i][0] ** 2 + size[i][1] ** 2)
 
         i_ref, i_2nd = define_reference_camera(pose_reference, cam_reference)
@@ -566,10 +580,10 @@
         y_w = {}
         for i in [i_ref, i_2nd]:
             x_w[i], y_w[i] = convert_to_world_coordinates(
-                    circle[i][0], circle[i][1], r[i], t[i], k[i],
+                    circle[i]['x'], circle[i]['y'], r[i], t[i], k[i],
                     chart_distance)
 
-        # Back convert to image coordinates for sanity check
+        # Back convert to image coordinates for round-trip check
         x_p = {}
         y_p = {}
         x_p[i_2nd], y_p[i_2nd] = convert_to_image_coordinates(
@@ -582,7 +596,7 @@
         # Summarize results
         for i in [i_ref, i_2nd]:
             print ' Camera: %s' % i
-            print ' x, y (pixels): %.1f, %.1f' % (circle[i][0], circle[i][1])
+            print ' x, y (pixels): %.1f, %.1f' % (circle[i]['x'], circle[i]['y'])
             print ' x_w, y_w (mm): %.2f, %.2f' % (x_w[i]*1.0E3, y_w[i]*1.0E3)
             print ' x_p, y_p (pixels): %.1f, %.1f' % (x_p[i], y_p[i])
 
@@ -591,31 +605,31 @@
                              np.array([x_w[i_2nd], y_w[i_2nd]]))
         print 'Center location err (mm): %.2f' % (err*1E3)
         msg = 'Center locations %s <-> %s too different!' % (i_ref, i_2nd)
-        msg += ' val=%.2fmm, THRESH=%.fmm' % (err*1E3, ALIGN_TOL_MM*1E3)
-        assert err < ALIGN_TOL, msg
+        msg += ' val=%.2fmm, THRESH=%.fmm' % (err*1E3, ALIGN_ATOL_MM*1E3)
+        assert err < ALIGN_ATOL_MM, msg
 
         # Check projections back into pixel space
         for i in [i_ref, i_2nd]:
-            err = np.linalg.norm(np.array([circle[i][0], circle[i][1]]) -
+            err = np.linalg.norm(np.array([circle[i]['x'], circle[i]['y']]) -
                                  np.array([x_p[i], y_p[i]]))
-            print 'Camera %s projection error (pixels): %.1f' % (i, err)
-            tol = ALIGN_TOL * sensor_diag[i]
+            print 'Camera %s projection error (pixels): %.2f' % (i, err)
+            tol = ALIGN_RTOL * sensor_diag[i]
             msg = 'Camera %s project locations too different!' % i
             msg += ' diff=%.2f, TOL=%.2f' % (err, tol)
             assert err < tol, msg
 
         # Check focal length and circle size if more than 1 focal length
-        if len(avail_fls) > 1:
+        if len(fl) > 1:
             print 'Circle radii (pixels); ref: %.1f, 2nd: %.1f' % (
-                    circle[i_ref][2], circle[i_2nd][2])
+                    circle[i_ref]['r'], circle[i_2nd]['r'])
             print 'Focal lengths (diopters); ref: %.2f, 2nd: %.2f' % (
                     fl[i_ref], fl[i_2nd])
-            print 'Sensor diagonals (pixels); ref: %.2f, 2nd: %.2f' % (
-                    sensor_diag[i_ref], sensor_diag[i_2nd])
+            print 'Pixel size (um); ref: %.2f, 2nd: %.2f' % (
+                    pixel_sizes[i_ref], pixel_sizes[i_2nd])
             msg = 'Circle size scales improperly! RTOL=%.1f' % CIRCLE_RTOL
-            msg += '\nMetric: radius/focal_length*sensor_diag should be equal.'
-            assert np.isclose(circle[i_ref][2]/fl[i_ref]*sensor_diag[i_ref],
-                              circle[i_2nd][2]/fl[i_2nd]*sensor_diag[i_2nd],
+            msg += '\nMetric: radius*pixel_size/focal_length should be equal.'
+            assert np.isclose(circle[i_ref]['r']*pixel_sizes[i_ref]/fl[i_ref],
+                              circle[i_2nd]['r']*pixel_sizes[i_2nd]/fl[i_2nd],
                               rtol=CIRCLE_RTOL), msg
 
 if __name__ == '__main__':
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index 9292f6a3..f1b1d36 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -128,7 +128,7 @@
     else:
         events, frames, _, h = load_data()
 
-    # Sanity check camera timestamps are enclosed by sensor timestamps
+    # Check that camera timestamps are enclosed by sensor timestamps
     # This will catch bugs where camera and gyro timestamps go completely out
     # of sync
     cam_times = get_cam_times(events["cam"])
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index b6579a8..36e6b71 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -30,7 +30,7 @@
 import its.image
 import rotation_rig as rot
 
-# For sanity checking the installed APK's target SDK version
+# For checking the installed APK's target SDK version
 MIN_SUPPORTED_SDK_VERSION = 28  # P
 
 CHART_DELAY = 1  # seconds
@@ -429,7 +429,7 @@
     device_id_arg = "device=" + device_id
     print "Testing device " + device_id
 
-    # Sanity check CtsVerifier SDK level
+    # Check CtsVerifier SDK level
     # Here we only do warning as there is no guarantee on pm dump output formt not changed
     # Also sometimes it's intentional to run mismatched versions
     cmd = "adb -s %s shell pm dump com.android.cts.verifier" % (device_id)
@@ -473,7 +473,7 @@
     with ItsSession() as cam:
         cam.check_its_version_compatible()
 
-    # Sanity Check for devices
+    # Correctness check for devices
     device_bfp = its.device.get_device_fingerprint(device_id)
     assert device_bfp is not None
 
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 8b45f84..6cdbb3e 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -169,6 +169,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_other" />
+            <meta-data android:name="test_excluded_features" android:value="android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".forcestop.RecentTaskRemovalTestActivity"
@@ -179,6 +180,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_required_configs" android:value="config_has_recents"/>
+            <meta-data android:name="test_excluded_features" android:value="android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".companion.CompanionDeviceTestActivity"
@@ -2209,6 +2211,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
 
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any"/>
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity android:name=".camera.intents.CameraIntentsActivity"
@@ -2220,6 +2224,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
 
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any"/>
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <service android:name=".camera.intents.CameraContentJobService"
@@ -2235,6 +2241,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
 
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any"/>
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity
@@ -2248,16 +2256,22 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any"/>
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
         <activity
             android:name=".camera.fov.DetermineFovActivity"
             android:label="@string/camera_fov_calibration"
             android:screenOrientation="landscape"
             android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" >
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
         <activity
             android:name=".camera.fov.CalibrationPreferenceActivity"
             android:label="@string/camera_fov_label_options" >
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
 
@@ -2271,6 +2285,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
             <meta-data android:name="test_required_features"
                     android:value="android.hardware.camera.any"/>
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity android:name=".camera.its.ItsTestActivity"
@@ -2284,6 +2300,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity android:name=".camera.flashlight.CameraFlashlightActivity"
@@ -2295,6 +2313,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.flash" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity android:name=".camera.performance.CameraPerformanceActivity"
@@ -2306,6 +2326,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity android:name=".camera.bokeh.CameraBokehActivity"
@@ -2318,6 +2340,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_camera" />
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.automotive"/>
         </activity>
 
         <activity android:name=".usb.accessory.UsbAccessoryTestActivity"
@@ -2551,7 +2575,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_tiles" />
             <meta-data android:name="test_excluded_features"
-                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
+                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch:android.hardware.type.automotive" />
         </activity>
 
         <service android:name=".qstiles.MockTileService"
@@ -4318,6 +4342,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_instant_apps" />
+            <meta-data android:name="test_excluded_features" android:value="android.hardware.type.automotive" />
         </activity>
         <activity android:name=".instantapps.RecentAppsTestActivity"
                  android:label="@string/ia_recents">
@@ -4326,6 +4351,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_instant_apps" />
+            <meta-data android:name="test_excluded_features" android:value="android.hardware.type.automotive" />
         </activity>
         <activity android:name=".instantapps.AppInfoTestActivity"
                  android:label="@string/ia_app_info">
@@ -4335,7 +4361,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_instant_apps" />
             <meta-data android:name="test_excluded_features"
-                android:value="android.hardware.type.television:android.software.leanback" />
+                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".displaycutout.DisplayCutoutTestActivity"
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java b/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
index 7776d27..c8a667b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
@@ -35,6 +35,8 @@
 import android.view.View.OnClickListener;
 import android.widget.ImageButton;
 import android.widget.Toast;
+import android.app.ActionBar;
+import android.view.MenuItem;
 
 import java.util.List;
 import java.util.stream.Collectors;
@@ -180,6 +182,25 @@
 
         @Override
         public TestResultHistoryCollection getHistoryCollection() { return mHistoryCollection; }
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ActionBar actBar = getActionBar();
+            if (actBar != null) {
+                actBar.setDisplayHomeAsUpEnabled(true);
+            }
+        }
+
+        @Override
+        public boolean onOptionsItemSelected(MenuItem item) {
+            if (item.getItemId() == android.R.id.home) {
+                onBackPressed();
+                return true;
+            }
+            return super.onOptionsItemSelected(item);
+        }
+
     }
 
     public static class ListActivity extends android.app.ListActivity implements PassFailActivity {
@@ -234,6 +255,25 @@
 
         @Override
         public TestResultHistoryCollection getHistoryCollection() { return mHistoryCollection; }
+
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ActionBar actBar = getActionBar();
+            if (actBar != null) {
+                actBar.setDisplayHomeAsUpEnabled(true);
+            }
+        }
+
+        @Override
+        public boolean onOptionsItemSelected(MenuItem item) {
+            if (item.getItemId() == android.R.id.home) {
+                onBackPressed();
+                return true;
+            }
+            return super.onOptionsItemSelected(item);
+        }
     }
 
     public static class TestListActivity extends AbstractTestListActivity
@@ -302,6 +342,25 @@
         public void updatePassButton() {
             getPassButton().setEnabled(mAdapter.allTestsPassed());
         }
+
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            ActionBar actBar = getActionBar();
+            if (actBar != null) {
+                actBar.setDisplayHomeAsUpEnabled(true);
+            }
+        }
+
+        @Override
+        public boolean onOptionsItemSelected(MenuItem item) {
+            if (item.getItemId() == android.R.id.home) {
+                onBackPressed();
+                return true;
+            }
+            return super.onOptionsItemSelected(item);
+        }
     }
 
     protected static <T extends android.app.Activity & PassFailActivity>
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java
index 6e48bcc..fb18b06 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java
@@ -19,6 +19,9 @@
  * Enum containing metadata for mainline modules.
  */
 public enum MainlineModule {
+
+    // Added in Q
+
     // Security
     MEDIA_SOFTWARE_CODEC("com.google.android.media.swcodec",
             true, ModuleType.APEX,
@@ -50,10 +53,6 @@
             "9A:4B:85:34:44:86:EC:F5:1F:F8:05:EB:9D:23:17:97:79:BE:B7:EC:81:91:93:5A:CA:67:F0"
                     + ":F4:09:02:52:97"),
     // Consistency
-    TZDATA2("com.google.android.tzdata2",
-            true, ModuleType.APEX,
-            "48:F3:A2:98:76:1B:6D:46:75:7C:EE:62:43:66:6A:25:B9:15:B9:42:18:A6:C2:82:72:99:BE"
-                    + ":DA:C9:92:AB:E7"),
     NETWORK_STACK("com.google.android.networkstack",
             true, ModuleType.APK,
             "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
@@ -70,6 +69,61 @@
             true, ModuleType.APK,
             "BF:62:23:1E:28:F0:85:42:75:5C:F3:3C:9D:D8:3C:5D:1D:0F:A3:20:64:50:EF:BC:4C:3F:F3"
                     + ":D5:FD:A0:33:0F"),
+
+    // Added in R
+
+    ADBD("com.google.android.adbd",
+            true, ModuleType.APEX,
+            "87:3D:4E:43:58:25:1A:25:1A:2D:9C:18:E1:55:09:45:21:88:A8:1E:FE:9A:83:9D:43:0D:E8"
+                    + ":D8:7E:C2:49:4C"),
+    NEURAL_NETWORKS("com.google.android.neuralnetworks",
+            true, ModuleType.APEX,
+            "6F:AB:D5:72:9A:90:02:6B:74:E4:87:79:8F:DF:10:BB:E3:6C:9E:6C:B7:A6:59:04:3C:D8:15"
+                    + ":61:6C:9E:60:50"),
+    CELL_BROADCAST("com.google.android.cellbroadcast",
+            true, ModuleType.APEX,
+            "A8:2C:84:7A:A3:9D:DA:19:A5:6C:9E:D3:56:50:1A:76:4F:BD:5D:C9:60:98:66:16:E3:1D:48"
+                    + ":EE:27:08:19:70"),
+    EXT_SERVICES("com.google.android.extservices",
+            true, ModuleType.APEX,
+            "10:89:F2:7C:85:6A:83:D4:02:6B:6A:49:97:15:4C:A1:70:9A:F6:93:27:C8:EF:9A:2D:1D:56"
+                    + ":AB:69:DE:07:0B"),
+    IPSEC("com.google.android.ipsec",
+            true, ModuleType.APEX,
+            "64:3D:3E:A5:B7:BF:22:E5:94:42:29:77:7C:4B:FF:C6:C8:44:14:64:4D:E0:4B:E4:90:37:57"
+                    + ":DE:83:CF:04:8B"),
+    MEDIA_PROVIDER("com.google.android.mediaprovider",
+            true, ModuleType.APEX,
+            "1A:61:93:09:6D:DC:81:58:72:45:EF:2C:07:33:73:6E:8E:FF:9D:E9:0E:51:27:4B:F8:23:AC"
+                    + ":F0:F7:49:00:A0"),
+    PERMISSION_CONTROLLER_APEX("com.google.android.permission",
+            true, ModuleType.APEX,
+            "69:AC:92:BF:BA:D5:85:4C:61:8E:AB:AE:85:7F:AB:0B:1A:65:19:44:E9:19:EA:3C:86:DB:D4"
+                    + ":07:04:1E:22:C1"),
+    SDK_EXTENSIONS("com.google.android.sdkext",
+            true, ModuleType.APEX,
+            "99:90:29:2B:22:11:D2:78:17:BF:5B:10:98:84:8F:68:44:53:37:16:2B:47:FF:D1:A0:8E:10"
+                    + ":CE:65:B1:CC:73"),
+    STATSD("com.google.android.os.statsd",
+            true, ModuleType.APEX,
+            "DA:FE:D6:20:A7:0C:98:05:A9:A2:22:04:55:6B:0E:94:E8:E3:4D:ED:F4:16:EC:58:92:C6:48"
+                    + ":86:53:39:B4:7B"),
+    TELEMETRY_TVP("com.google.mainline.telemetry",
+            true, ModuleType.APK,
+            "9D:AC:CC:AE:4F:49:5A:E6:DB:C5:8A:0E:C2:33:C6:E5:2D:31:14:33:AC:57:3C:4D:A1:C7:39"
+                    + ":DF:64:03:51:5D"),
+    TETHERING("com.google.android.tethering",
+            true, ModuleType.APEX,
+            "E5:3F:52:F4:14:15:0C:05:BA:E0:E4:CE:E2:07:3D:D0:0F:E6:44:66:1D:5F:9A:0F:BE:49:4A"
+                    + ":DC:07:F0:59:93"),
+    TZDATA2("com.google.android.tzdata2",
+            true, ModuleType.APEX,
+            "48:F3:A2:98:76:1B:6D:46:75:7C:EE:62:43:66:6A:25:B9:15:B9:42:18:A6:C2:82:72:99:BE"
+                    + ":DA:C9:92:AB:E7"),
+    WIFI("com.google.android.wifi",
+            false, ModuleType.APEX,
+            "B7:A3:DB:7A:86:6D:18:51:3F:97:6C:63:20:BC:0F:E6:E4:01:BA:2F:26:96:B1:C3:94:2A:F0"
+                    + ":FE:29:31:98:B1"),
     ;
 
     public final String packageName;
diff --git a/hostsidetests/adb/src/android/adb/cts/AdbHostTest.java b/hostsidetests/adb/src/android/adb/cts/AdbHostTest.java
index bea7506..d5301d4 100644
--- a/hostsidetests/adb/src/android/adb/cts/AdbHostTest.java
+++ b/hostsidetests/adb/src/android/adb/cts/AdbHostTest.java
@@ -64,6 +64,10 @@
             return;
         }
 
+        if (getDevice().isAdbTcp()) { // adb over WiFi, no point checking it
+            return;
+        }
+
         ProcessBuilder pb = new ProcessBuilder(check_ms_os_desc.getAbsolutePath());
         pb.environment().put("ANDROID_SERIAL", serial);
         pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
diff --git a/hostsidetests/angle/Android.bp b/hostsidetests/angle/Android.bp
index 3125610..dac193f 100644
--- a/hostsidetests/angle/Android.bp
+++ b/hostsidetests/angle/Android.bp
@@ -22,7 +22,6 @@
         "cts",
         "vts10",
         "general-tests",
-        "mts"
     ],
     libs: [
         "cts-tradefed",
diff --git a/hostsidetests/angle/app/common/Android.bp b/hostsidetests/angle/app/common/Android.bp
index 508ce2d..fe33a37 100644
--- a/hostsidetests/angle/app/common/Android.bp
+++ b/hostsidetests/angle/app/common/Android.bp
@@ -20,6 +20,5 @@
     test_suites: [
         "gts",
         "ats",
-        "mts"
     ],
 }
diff --git a/hostsidetests/angle/app/driverTest/Android.bp b/hostsidetests/angle/app/driverTest/Android.bp
index 1bfc779..9b2adb2 100644
--- a/hostsidetests/angle/app/driverTest/Android.bp
+++ b/hostsidetests/angle/app/driverTest/Android.bp
@@ -22,7 +22,6 @@
     test_suites: [
         "cts",
         "vts10",
-        "mts"
     ],
     compile_multilib: "both",
     static_libs: [
diff --git a/hostsidetests/angle/app/driverTestSecondary/Android.bp b/hostsidetests/angle/app/driverTestSecondary/Android.bp
index 22f3c2f..fad514e 100644
--- a/hostsidetests/angle/app/driverTestSecondary/Android.bp
+++ b/hostsidetests/angle/app/driverTestSecondary/Android.bp
@@ -24,7 +24,6 @@
     test_suites: [
         "cts",
         "vts10",
-        "mts"
     ],
     compile_multilib: "both",
     static_libs: [
diff --git a/hostsidetests/apex/src/android/apex/cts/ApexTest.java b/hostsidetests/apex/src/android/apex/cts/ApexTest.java
index 081da9b..c2ca8bc 100644
--- a/hostsidetests/apex/src/android/apex/cts/ApexTest.java
+++ b/hostsidetests/apex/src/android/apex/cts/ApexTest.java
@@ -41,7 +41,9 @@
       || systemProduct.equals("aosp_arm_ab") // _ab for Legacy GSI
       || systemProduct.equals("aosp_arm64_ab")
       || systemProduct.equals("aosp_x86_ab")
-      || systemProduct.equals("aosp_x86_64_ab");
+      || systemProduct.equals("aosp_x86_64_ab")
+      || systemProduct.equals("aosp_tv_arm")
+      || systemProduct.equals("aosp_tv_arm64");
   }
 
   /**
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
index b8bb01f..d986e58 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
@@ -55,6 +55,8 @@
     private static final String MODE_NONE = "none";
 
     private static final String FEATURE_DEVICE_ADMIN = "feature:android.software.device_admin";
+    private static final String FEATURE_SECURE_LOCK_SCREEN =
+            "feature:android.software.secure_lock_screen";
     private static final String FEATURE_AUTOMOTIVE = "feature:android.hardware.type.automotive";
 
     private static final long SHUTDOWN_TIME_MS = 30 * 1000;
@@ -213,7 +215,8 @@
     }
 
     private boolean isSupportedDevice() throws Exception {
-        return getDevice().hasFeature(FEATURE_DEVICE_ADMIN);
+        return getDevice().hasFeature(FEATURE_DEVICE_ADMIN)
+                && getDevice().hasFeature(FEATURE_SECURE_LOCK_SCREEN);
     }
 
     private boolean isAutomotiveDevice() throws Exception {
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/DocumentsTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/DocumentsTest.java
index 1c83284..fc63925 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/DocumentsTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/DocumentsTest.java
@@ -18,6 +18,8 @@
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 
+import com.android.tradefed.device.DeviceNotAvailableException;
+
 import com.google.common.collect.ImmutableSet;
 
 /**
@@ -124,7 +126,7 @@
     }
 
     public void testRestrictStorageAccessFrameworkEnabled_blockFromTree() throws Exception {
-        if (isAtLeastR()) {
+        if (isAtLeastR() && isSupportedHardware()) {
             runDeviceCompatTest(CLIENT_PKG, ".DocumentsClientTest",
                 "testRestrictStorageAccessFrameworkEnabled_blockFromTree",
                 /* enabledChanges */ ImmutableSet.of(RESTRICT_STORAGE_ACCESS_FRAMEWORK),
@@ -133,7 +135,7 @@
     }
 
     public void testRestrictStorageAccessFrameworkDisabled_notBlockFromTree() throws Exception {
-        if (isAtLeastR()) {
+        if (isAtLeastR() && isSupportedHardware()) {
             runDeviceCompatTest(CLIENT_PKG, ".DocumentsClientTest",
                 "testRestrictStorageAccessFrameworkDisabled_notBlockFromTree",
                 /* enabledChanges */ ImmutableSet.of(),
@@ -153,4 +155,17 @@
             return false;
         }
     }
+
+    private boolean isSupportedHardware() {
+        try {
+            if (getDevice().hasFeature("feature:android.hardware.type.television")
+                    || getDevice().hasFeature("feature:android.hardware.type.watch")
+                    || getDevice().hasFeature("feature:android.hardware.type.automotive")) {
+                return false;
+            }
+        } catch (DeviceNotAvailableException e) {
+            return true;
+        }
+        return true;
+    }
 }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/LocationPolicyTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/LocationPolicyTest.java
new file mode 100644
index 0000000..e2ff6c6
--- /dev/null
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/LocationPolicyTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.appsecurity.cts;
+
+
+import android.platform.test.annotations.SecurityTest;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/** Tests to verify app location access */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class LocationPolicyTest extends BaseAppSecurityTest {
+
+    private static final String TEST_PKG = "android.appsecurity.cts.locationpolicy";
+    private static final String TEST_APK = "CtsLocationPolicyApp.apk";
+
+    @Before
+    public void setUp() throws Exception {
+        getDevice().uninstallPackage(TEST_PKG);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        getDevice().uninstallPackage(TEST_PKG);
+    }
+
+    @Test
+    @SecurityTest
+    public void testLocationPolicyPermissions() throws Exception {
+        new InstallMultiple(true).addFile(TEST_APK).run();
+        Utils.runDeviceTests(
+            getDevice(), TEST_PKG, ".LocationPolicyTest", "testLocationPolicyPermissions");
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
index 7db3682..8fdf859 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
@@ -103,7 +103,7 @@
      * Verify we can write to our own package dirs.
      */
     public void testAllPackageDirsWritable() throws Exception {
-        final long testValue = 12345000;
+        final long testValue = 1234500000000L;
         final List<File> paths = getAllPackageSpecificPaths(getContext());
         for (File path : paths) {
             assertNotNull("Valid media must be inserted during CTS", path);
diff --git a/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp
new file mode 100644
index 0000000..b7174d2
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp
@@ -0,0 +1,36 @@
+// Copyright (C) 2020 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.
+
+android_test {
+    name: "CtsLocationPolicyApp",
+    defaults: ["cts_defaults"],
+    libs: [
+        "android.test.runner.stubs",
+        "android.test.base.stubs",
+    ],
+    static_libs: [
+        "androidx.test.rules",
+        "telephony-common",
+    ],
+    srcs: ["src/**/*.java"],
+    platform_apis: true,
+    test_suites: [
+        "cts",
+        "vts10",
+        "sts",
+        "general-tests",
+    ],
+    min_sdk_version: "27",
+    target_sdk_version: "28",
+}
diff --git a/hostsidetests/appsecurity/test-apps/LocationPolicyApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/AndroidManifest.xml
new file mode 100644
index 0000000..ed9d1fc
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+  package="android.appsecurity.cts.locationpolicy">
+
+    <application>
+      <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.appsecurity.cts.locationpolicy"
+                     android:label="Test to check location policy access for bad sdk."/>
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/LocationPolicyApp/src/android/appsecurity/cts/locationpolicy/LocationPolicyTest.java b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/src/android/appsecurity/cts/locationpolicy/LocationPolicyTest.java
new file mode 100644
index 0000000..74ce0c5
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/src/android/appsecurity/cts/locationpolicy/LocationPolicyTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.appsecurity.cts.locationpolicy;
+
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.platform.test.annotations.SecurityTest;
+import android.telephony.TelephonyManager;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class LocationPolicyTest {
+
+    private final Context mContext = InstrumentationRegistry.getInstrumentation().getContext();
+
+    @Test
+    @SecurityTest
+    public void testLocationPolicyPermissions() throws Exception {
+        assertNotNull(mContext);
+        PackageManager pm = mContext.getPackageManager();
+        assertNotNull(pm);
+        assertNotEquals(
+            PackageManager.PERMISSION_GRANTED,
+            pm.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION,
+            mContext.getPackageName()));
+        assertNotEquals(
+            PackageManager.PERMISSION_GRANTED,
+            pm.checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
+            mContext.getPackageName()));
+        TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
+        try {
+            tele.getCellLocation();
+        fail(
+            "ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION Permissions not granted. Should have"
+              + " received a security exception when invoking getCellLocation().");
+        } catch (SecurityException ignore) {
+          // That's what we want!
+        }
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java b/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java
index e44d70d..f507d40 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java
@@ -45,6 +45,7 @@
 import android.os.storage.StorageManager;
 import android.provider.Settings;
 import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObjectNotFoundException;
 import android.support.test.uiautomator.UiScrollable;
 import android.support.test.uiautomator.UiSelector;
 import android.test.InstrumentationTestCase;
@@ -102,7 +103,11 @@
 
         if (!isTV(getContext())) {
             UiScrollable uiScrollable = new UiScrollable(new UiSelector().scrollable(true));
-            uiScrollable.scrollTextIntoView("internal storage");
+            try {
+                uiScrollable.scrollTextIntoView("internal storage");
+            } catch (UiObjectNotFoundException e) {
+                // Scrolling can fail if the UI is not scrollable
+            }
             device.findObject(new UiSelector().textContains("internal storage")).click();
             device.waitForIdle();
         }
diff --git a/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java b/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java
index 3e7c1da..2f4164f 100644
--- a/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java
@@ -23,6 +23,8 @@
 import com.android.compatibility.common.util.CommonTestUtils;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
+import com.android.tradefed.log.LogUtil.CLog;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -40,6 +42,12 @@
 
     private Optional<Integer> mProfileUserId = Optional.empty();
 
+    /**
+     * User ID for the system user.
+     * The value is from the UserHandle class.
+     */
+    protected static final int USER_SYSTEM = 0;
+
     /** Create the profile and start it. */
     @Before
     @Override
@@ -79,11 +87,21 @@
 
         assertTrue(mBackupUtils.isBackupActivatedForUser(profileUserId));
 
-        assertTrue(getDevice().removeUser(profileUserId));
+        removeUser(profileUserId);
         mProfileUserId = Optional.empty();
 
         CommonTestUtils.waitUntil("wait for backup to be deactivated for removed user",
                 BACKUP_DEACTIVATION_TIMEOUT_SECONDS,
                 () -> !mBackupUtils.isBackupActivatedForUser(profileUserId));
     }
+
+    private void removeUser(int userId) throws Exception  {
+        if (getDevice().listUsers().contains(userId) && userId != USER_SYSTEM) {
+            // Don't log output, as tests sometimes set no debug user restriction, which
+            // causes this to fail, we should still continue and remove the user.
+            CLog.d("Stopping and removing user " + userId);
+            getDevice().stopUser(userId, true, true);
+            assertTrue("Couldn't remove user", getDevice().removeUser(userId));
+        }
+    }
 }
diff --git a/hostsidetests/bootstats/Android.bp b/hostsidetests/bootstats/Android.bp
index fa86bcf..3681c59 100644
--- a/hostsidetests/bootstats/Android.bp
+++ b/hostsidetests/bootstats/Android.bp
@@ -17,6 +17,7 @@
     defaults: ["cts_defaults"],
     // Only compile source java files in this apk.
     srcs: ["src/**/*.java"],
+    static_libs: ["framework-protos"],
     libs: [
         "cts-tradefed",
         "tradefed",
diff --git a/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java b/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java
index 47789f1..9bcf2a1 100644
--- a/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java
+++ b/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java
@@ -18,11 +18,13 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.os.AtomsProto.Atom;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.IDeviceTest;
 
+import org.junit.Assert;
 import org.junit.Assume;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -53,6 +55,11 @@
                 + " in Android 8.0. Current API Level " + apiLevel,
                 apiLevel < 26 /* Build.VERSION_CODES.O */);
 
+        if (apiLevel <= 29 /* Build.VERSION_CODES.Q */) {
+            testBootStatsForApiLevel29AndBelow();
+            return;
+        }
+
         // Clear buffer to make it easier to find new logs
         getDevice().executeShellCommand("logcat --buffer=events --clear");
 
@@ -109,6 +116,69 @@
         return value;
     }
 
+    /** Need to keep the old version of test for api 27, 28, 29 as new version 
+        of tests can be used on devices with old Android versions */
+    private void testBootStatsForApiLevel29AndBelow() throws Exception {
+        long startTime = System.currentTimeMillis();
+        // Clear buffer to make it easier to find new logs
+        getDevice().executeShellCommand("logcat --buffer=events --clear");
+
+        // reboot device
+        getDevice().rebootUntilOnline();
+        waitForBootCompleted();
+        int upperBoundSeconds = (int) ((System.currentTimeMillis() - startTime) / 1000);
+
+        // wait for logs to post
+        Thread.sleep(10000);
+
+        // find logs and parse them
+        // ex: sysui_multi_action: [757,804,799,ota_boot_complete,801,85,802,1]
+        // ex: 757,804,799,counter_name,801,bucket_value,802,increment_value
+        final String bucketTag = Integer.toString(MetricsEvent.RESERVED_FOR_LOGBUILDER_BUCKET);
+        final String counterNameTag = Integer.toString(MetricsEvent.RESERVED_FOR_LOGBUILDER_NAME);
+        final String counterNamePattern = counterNameTag + ",boot_complete,";
+        final String multiActionPattern = "sysui_multi_action: [";
+
+        final String log = getDevice().executeShellCommand("logcat --buffer=events -d");
+
+        int counterNameIndex = log.indexOf(counterNamePattern);
+        Assert.assertTrue("did not find boot logs", counterNameIndex != -1);
+
+        int multiLogStart = log.lastIndexOf(multiActionPattern, counterNameIndex);
+        multiLogStart += multiActionPattern.length();
+        int multiLogEnd = log.indexOf("]", multiLogStart);
+        String[] multiLogDataStrings = log.substring(multiLogStart, multiLogEnd).split(",");
+
+        boolean foundBucket = false;
+        int bootTime = 0;
+        for (int i = 0; i < multiLogDataStrings.length; i += 2) {
+            if (bucketTag.equals(multiLogDataStrings[i])) {
+                foundBucket = true;
+                Assert.assertTrue("histogram data was truncated",
+                        (i + 1) < multiLogDataStrings.length);
+                bootTime = Integer.valueOf(multiLogDataStrings[i + 1]);
+            }
+        }
+        Assert.assertTrue("log line did not contain a tag " + bucketTag, foundBucket);
+        Assert.assertTrue("reported boot time must be less than observed boot time",
+                bootTime < upperBoundSeconds);
+        Assert.assertTrue("reported boot time must be non-zero", bootTime > 0);
+    }
+
+    private boolean isBootCompleted() throws Exception {
+        return "1".equals(getDevice().executeShellCommand("getprop sys.boot_completed").trim());
+    }
+
+    private void waitForBootCompleted() throws Exception {
+        for (int i = 0; i < 45; i++) {
+            if (isBootCompleted()) {
+                return;
+            }
+            Thread.sleep(1000);
+        }
+        throw new AssertionError("System failed to become ready!");
+    }
+
     @Override
     public void setDevice(ITestDevice device) {
         mDevice = device;
diff --git a/hostsidetests/content/src/android/content/cts/ContextCrossProfileHostTest.java b/hostsidetests/content/src/android/content/cts/ContextCrossProfileHostTest.java
index f02e901..0e473f2 100644
--- a/hostsidetests/content/src/android/content/cts/ContextCrossProfileHostTest.java
+++ b/hostsidetests/content/src/android/content/cts/ContextCrossProfileHostTest.java
@@ -30,6 +30,7 @@
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
 import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.IBuildReceiver;
 
@@ -73,7 +74,10 @@
         assumeTrue(mSupportsMultiUser);
 
         mParentUserId = getDevice().getCurrentUser();
-        assertEquals(USER_SYSTEM, mParentUserId);
+        // Automotive uses non-system user as current user always
+        if (!getDevice().hasFeature("feature:android.hardware.type.automotive")) {
+            assertEquals(USER_SYSTEM, mParentUserId);
+        }
 
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
         mApkFile = buildHelper.getTestFile(TEST_WITH_PERMISSION_APK);
@@ -99,6 +103,7 @@
     @Test
     public void testBindServiceAsUser_differentUser_bindsServiceToCorrectUser()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -126,6 +131,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_samePackage_withAcrossUsersPermission_bindsService()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -153,6 +159,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_differentPackage_withAcrossUsersPermission_bindsService()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -180,6 +187,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_samePackage_withAcrossProfilesPermission_bindsService()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -207,6 +215,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_differentPackage_withAcrossProfilesPermission_throwsException()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -234,6 +243,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_samePackage_withAcrossProfilesAppOp_bindsService()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -261,6 +271,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_differentPackage_withAcrossProfilesAppOp_throwsException()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -375,6 +386,7 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_withNoPermissions_throwsException()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -402,9 +414,8 @@
     @Test
     public void testBindServiceAsUser_sameProfileGroup_reportsMetric()
             throws Exception {
-        if (!isStatsdEnabled(getDevice())) {
-            return;
-        }
+        assumeTrue(isStatsdEnabled(getDevice()));
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */ true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -444,9 +455,7 @@
     @Test
     public void testBindServiceAsUser_differentProfileGroup_doesNotReportMetric()
             throws Exception {
-        if (!isStatsdEnabled(getDevice())) {
-            return;
-        }
+        assumeTrue(isStatsdEnabled(getDevice()));
         int userInDifferentProfileGroup = createUser();
         getDevice().startUser(userInDifferentProfileGroup, /* waitFlag= */ true);
         mTestArgs.put("testUser", Integer.toString(userInDifferentProfileGroup));
@@ -483,9 +492,8 @@
     @Test
     public void testBindServiceAsUser_sameUser_doesNotReportMetric()
             throws Exception {
-        if (!isStatsdEnabled(getDevice())) {
-            return;
-        }
+        assumeTrue(isStatsdEnabled(getDevice()));
+
         mTestArgs.put("testUser", Integer.toString(mParentUserId));
 
         assertMetricsNotLogged(getDevice(), () -> {
@@ -506,6 +514,7 @@
     @Test
     public void testCreateContextAsUser_sameProfileGroup_withInteractAcrossProfilesPermission_throwsException()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -533,6 +542,7 @@
     @Test
     public void testCreateContextAsUser_sameProfileGroup_withInteractAcrossUsersPermission_createsContext()
             throws Exception {
+        assumeTrue(supportsManagedUsers());
         int userInSameProfileGroup = createProfile(mParentUserId);
         getDevice().startUser(userInSameProfileGroup, /* waitFlag= */true);
         mTestArgs.put("testUser", Integer.toString(userInSameProfileGroup));
@@ -556,4 +566,12 @@
                 /* timeout= */60L,
                 TimeUnit.SECONDS);
     }
+
+    boolean supportsManagedUsers() {
+        try {
+            return getDevice().hasFeature("feature:android.software.managed_users");
+        } catch (DeviceNotAvailableException e) {
+            return false;
+        }
+    }
 }
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp
new file mode 100644
index 0000000..a33eec5
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp
@@ -0,0 +1,35 @@
+// Copyright (C) 2020 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.
+
+android_test_helper_app {
+    name: "CtsModifyQuietModeEnabledApp",
+    defaults: ["cts_defaults"],
+    srcs: ["src/**/*.java"],
+    libs: ["junit"],
+    static_libs: [
+        "androidx.legacy_legacy-support-v4",
+        "ctstestrunner-axt",
+        "compatibility-device-util-axt",
+        "androidx.test.rules",
+        "truth-prebuilt",
+        "ub-uiautomator",
+    ],
+    min_sdk_version: "29",
+    // tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/AndroidManifest.xml
new file mode 100644
index 0000000..b371d96
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/AndroidManifest.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+     package="com.android.cts.modifyquietmodeenabledapp">
+
+    <uses-sdk android:minSdkVersion="29"
+         android:targetSdkVersion="29"/>
+
+    <uses-permission android:name="android.permission.MODIFY_QUIET_MODE"/>
+
+    <application android:crossProfile="true">
+        <receiver android:name=".ModifyQuietModeEnabledAppReceiver"
+             android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MANAGED_PROFILE_UNAVAILABLE"/>
+                <action android:name="android.intent.action.MANAGED_PROFILE_AVAILABLE"/>
+                <action android:name="android.intent.action.MANAGED_PROFILE_ADDED"/>
+                <action android:name="android.intent.action.MANAGED_PROFILE_REMOVED"/>
+            </intent-filter>
+        </receiver>
+    </application>
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+         android:targetPackage="com.android.cts.modifyquietmodeenabledapp"
+         android:label="Launcher Apps CTS Tests"/>
+</manifest>
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/OWNERS b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/OWNERS
new file mode 100644
index 0000000..9647f11
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/OWNERS
@@ -0,0 +1,4 @@
+# Bug component: 168445
+alexkershaw@google.com
+kholoudm@google.com
+pbdr@google.com
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/src/com/android/cts/modifyquietmodeenabledapp/ModifyQuietModeEnabledAppReceiver.java b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/src/com/android/cts/modifyquietmodeenabledapp/ModifyQuietModeEnabledAppReceiver.java
new file mode 100644
index 0000000..88e0f12
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/src/com/android/cts/modifyquietmodeenabledapp/ModifyQuietModeEnabledAppReceiver.java
@@ -0,0 +1,15 @@
+package com.android.cts.modifyquietmodeenabledapp;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Slog;
+
+public class ModifyQuietModeEnabledAppReceiver extends BroadcastReceiver {
+    private static final String TAG = "ModifyQuietModeEnabledAppReceiver";
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Slog.w(TAG, String.format("onReceive(%s)", intent.getAction()));
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
index f59803b..ed420f1 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
@@ -16,7 +16,6 @@
 package com.android.cts.deviceandprofileowner;
 
 import android.app.admin.DevicePolicyManager;
-import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 import android.util.Log;
 
 /**
@@ -34,35 +33,32 @@
         super.setUp();
     }
 
-    public void testSetScreenCaptureDisabled_false() throws Exception {
+    public void testSetScreenCaptureDisabled_false() {
         mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, false);
         assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
         assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
     }
 
-    public void testSetScreenCaptureDisabled_true() throws Exception {
+    public void testSetScreenCaptureDisabled_true() {
         mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, true);
         assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
         assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
     }
 
-    public void testSetScreenCaptureDisabledOnParent() throws Exception {
+    public void testSetScreenCaptureDisabledOnParent_false() {
         DevicePolicyManager parentDevicePolicyManager =
                 mDevicePolicyManager.getParentProfileInstance(ADMIN_RECEIVER_COMPONENT);
-        boolean initial = parentDevicePolicyManager.getScreenCaptureDisabled(
-                ADMIN_RECEIVER_COMPONENT);
-
-        parentDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, true);
-        assertTrue(parentDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
-        assertTrue(parentDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
-        testScreenCaptureImpossible();
-
         parentDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, false);
         assertFalse(parentDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
         assertFalse(parentDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
-        testScreenCapturePossible();
+    }
 
-        parentDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, initial);
+    public void testSetScreenCaptureDisabledOnParent_true() {
+        DevicePolicyManager parentDevicePolicyManager =
+                mDevicePolicyManager.getParentProfileInstance(ADMIN_RECEIVER_COMPONENT);
+        parentDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, true);
+        assertTrue(parentDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
+        assertTrue(parentDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
     }
 
     public void testScreenCaptureImpossible() throws Exception {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index d828b86..72e8293 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -1223,6 +1223,9 @@
             // Reboot while in kiosk mode and then unlock the device
             rebootAndWaitUntilReady();
 
+            // Wait for the LockTask starting
+            waitForBroadcastIdle();
+
             // Try to open settings via adb
             executeShellCommand("am start -a android.settings.SETTINGS");
 
@@ -2219,13 +2222,9 @@
                 ? "testScreenCaptureImpossible"
                 : "testScreenCapturePossible";
 
-        if (userId == mPrimaryUserId) {
-            // If testing for user-0, also make sure the existing screen can't be captured.
-            executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
-        }
-
         startSimpleActivityAsUser(userId);
         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
+        forceStopPackageForUser(TEST_APP_PKG, userId);
     }
 
     protected void setScreenCaptureDisabled_assist(int userId, boolean disabled) throws Exception {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileContactsTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileContactsTest.java
index 2ed1e30..5492cf2 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileContactsTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileContactsTest.java
@@ -150,6 +150,9 @@
                     "settings put --user " + mProfileUserId
                     + " secure managed_profile_contact_remote_search 1");
 
+            // Wait for updating cache
+            waitForBroadcastIdle();
+
             // Add test account
             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
                     "testAddTestAccount", mParentUserId);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java
index f575fc7..875803c 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java
@@ -49,6 +49,8 @@
     private static final String ACTION_WIPE_DATA =
             "com.android.cts.deviceandprofileowner.WIPE_DATA";
 
+    private static final String TEST_APP_APK = "CtsSimpleApp.apk";
+    private static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp";
     private static final String DUMMY_IME_APK = "DummyIme.apk";
     private static final String DUMMY_IME_PKG = "com.android.cts.dummyime";
     private static final String DUMMY_IME_COMPONENT = DUMMY_IME_PKG + "/.DummyIme";
@@ -554,8 +556,41 @@
         if (!mHasFeature) {
             return;
         }
+        installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
+        setPoAsUser(mPrimaryUserId);
+
+        try {
+            setScreenCaptureDisabled(true);
+        } finally {
+            setScreenCaptureDisabled(false);
+        }
+    }
+
+    private void takeScreenCaptureAsUser(int userId, String testMethodName) throws Exception {
+        installAppAsUser(TEST_APP_APK, /* grantPermissions */ true, /* dontKillApp */ true, userId);
+        startActivityAsUser(userId, TEST_APP_PKG, TEST_APP_PKG + ".SimpleActivity");
         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".ScreenCaptureDisabledTest",
-                "testSetScreenCaptureDisabledOnParent", mUserId);
+                testMethodName, userId);
+        forceStopPackageForUser(TEST_APP_PKG, userId);
+    }
+
+    private void setScreenCaptureDisabled(boolean disabled) throws Exception {
+        String testMethodName = disabled
+                ? "testSetScreenCaptureDisabledOnParent_true"
+                : "testSetScreenCaptureDisabledOnParent_false";
+        runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".ScreenCaptureDisabledTest",
+                testMethodName, mUserId);
+
+        testMethodName = disabled
+                ? "testScreenCaptureImpossible"
+                : "testScreenCapturePossible";
+
+        // Test personal profile
+        takeScreenCaptureAsUser(mPrimaryUserId, testMethodName);
+
+        // Test managed profile. This should not be disabled when screen capture is disabled on
+        // the parent by the profile owner of an organization-owned device.
+        takeScreenCaptureAsUser(mUserId, "testScreenCapturePossible");
     }
 
     private void assertHasNoUser(int userId) throws DeviceNotAvailableException {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java
index 47fcf7a..f13cd86 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java
@@ -28,6 +28,7 @@
     private static final String ENABLED_TEST_APK = "CtsCrossProfileEnabledApp.apk";
     private static final String USER_ENABLED_TEST_APK = "CtsCrossProfileUserEnabledApp.apk";
     private static final String ENABLED_NO_PERMS_TEST_APK = "CtsCrossProfileEnabledNoPermsApp.apk";
+    private static final String QUIET_MODE_ENABLED_TEST_APK = "CtsQuietModeEnabledApp.apk";
     private static final String NOT_ENABLED_TEST_APK = "CtsCrossProfileNotEnabledApp.apk";
     private static final String ENABLED_TEST_PACKAGE = "com.android.cts.crossprofileenabledapp";
     private static final String USER_ENABLED_TEST_PACKAGE =
@@ -36,6 +37,8 @@
             "com.android.cts.crossprofileenablednopermsapp";
     private static final String NOT_ENABLED_TEST_PACKAGE =
             "com.android.cts.crossprofilenotenabledapp";
+    private static final String QUIET_MODE_ENABLED_TEST_PACKAGE =
+            "com.android.cts.quietmodeenabledapp";
 
     private int mProfileId;
     private String mOriginalLauncher;
@@ -194,6 +197,8 @@
         assertThat(result).doesNotContain(
                 buildReceivedBroadcastRegex(actionName,
                         "CrossProfileNotEnabledAppReceiver"));
+        assertThat(result).contains(
+                buildReceivedBroadcastRegex(actionName, "ModifyQuietModeEnabledAppReceiver"));
     }
 
     private String buildReceivedBroadcastRegex(String actionName, String className) {
@@ -231,6 +236,7 @@
         getDevice().uninstallPackage(USER_ENABLED_TEST_PACKAGE);
         getDevice().uninstallPackage(ENABLED_NO_PERMS_TEST_PACKAGE);
         getDevice().uninstallPackage(NOT_ENABLED_TEST_PACKAGE);
+        getDevice().uninstallPackage(QUIET_MODE_ENABLED_TEST_PACKAGE);
     }
 
     private void installCrossProfileApps()
@@ -239,6 +245,7 @@
         installCrossProfileApp(USER_ENABLED_TEST_APK, /* grantPermissions= */ true);
         installCrossProfileApp(NOT_ENABLED_TEST_APK, /* grantPermissions= */ true);
         installCrossProfileApp(ENABLED_NO_PERMS_TEST_APK, /* grantPermissions= */  false);
+        installCrossProfileApp(QUIET_MODE_ENABLED_TEST_APK, /* grantPermissions= */  true);
     }
 
     private void enableCrossProfileAppsOp() throws DeviceNotAvailableException {
diff --git a/hostsidetests/incident/src/com/android/server/cts/IncidentdTest.java b/hostsidetests/incident/src/com/android/server/cts/IncidentdTest.java
index 460181d..f7dcec1 100644
--- a/hostsidetests/incident/src/com/android/server/cts/IncidentdTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/IncidentdTest.java
@@ -72,8 +72,6 @@
 
         AlarmManagerIncidentTest.verifyAlarmManagerServiceDumpProto(dump.getAlarm(), filterLevel);
 
-        MemInfoIncidentTest.verifyMemInfoDumpProto(dump.getMeminfo(), filterLevel);
-
         // GraphicsStats is expected to be all AUTOMATIC.
 
         WindowManagerIncidentTest.verifyWindowManagerServiceDumpProto(dump.getWindow(), filterLevel);
diff --git a/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java b/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java
deleted file mode 100644
index 2747972..0000000
--- a/hostsidetests/incident/src/com/android/server/cts/MemInfoIncidentTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts;
-
-import com.android.server.am.MemInfoDumpProto;
-import com.android.server.am.MemInfoDumpProto.AppData;
-import com.android.server.am.MemInfoDumpProto.MemItem;
-import com.android.server.am.MemInfoDumpProto.ProcessMemory;
-
-/** Test to check that ActivityManager properly outputs meminfo data. */
-public class MemInfoIncidentTest extends ProtoDumpTestCase {
-
-    public void testMemInfoDump() throws Exception {
-        final MemInfoDumpProto dump =
-                getDump(MemInfoDumpProto.parser(), "dumpsys -t 30000 meminfo -a --proto");
-
-        verifyMemInfoDumpProto(dump, PRIVACY_NONE);
-    }
-
-    static void verifyMemInfoDumpProto(MemInfoDumpProto dump, final int filterLevel) throws Exception {
-        assertTrue(dump.getUptimeDurationMs() >= 0);
-        assertTrue(dump.getElapsedRealtimeMs() >= 0);
-
-        for (ProcessMemory pm : dump.getNativeProcessesList()) {
-            testProcessMemory(pm);
-        }
-
-        for (AppData ad : dump.getAppProcessesList()) {
-            testAppData(ad);
-        }
-
-        for (MemItem mi : dump.getTotalPssByProcessList()) {
-            testMemItem(mi);
-        }
-        for (MemItem mi : dump.getTotalPssByOomAdjustmentList()) {
-            testMemItem(mi);
-        }
-        for (MemItem mi : dump.getTotalPssByCategoryList()) {
-            testMemItem(mi);
-        }
-
-        assertTrue(0 <= dump.getTotalRamKb());
-        assertTrue(0 <= dump.getCachedPssKb());
-        assertTrue(0 <= dump.getCachedKernelKb());
-        assertTrue(0 <= dump.getFreeKb());
-        assertTrue(0 <= dump.getUsedPssKb());
-        assertTrue(0 <= dump.getUsedKernelKb());
-
-        // Ideally lost RAM would not be negative, but there's an issue where it's sometimes
-        // calculated to be negative.
-        // TODO: re-enable check once the underlying bug has been fixed.
-        // assertTrue(0 <= dump.getLostRamKb());
-
-        assertTrue(0 <= dump.getTotalZramKb());
-        assertTrue(0 <= dump.getZramPhysicalUsedInSwapKb());
-        assertTrue(0 <= dump.getTotalZramSwapKb());
-
-        assertTrue(0 <= dump.getKsmSharingKb());
-        assertTrue(0 <= dump.getKsmSharedKb());
-        assertTrue(0 <= dump.getKsmUnsharedKb());
-        assertTrue(0 <= dump.getKsmVolatileKb());
-
-        assertTrue("Tuning_mb (" + dump.getTuningMb() + ") is not positive", 0 < dump.getTuningMb());
-        assertTrue(0 < dump.getTuningLargeMb());
-
-        assertTrue(0 <= dump.getOomKb());
-
-        assertTrue(0 < dump.getRestoreLimitKb());
-    }
-
-    private static void testProcessMemory(ProcessMemory pm) throws Exception {
-        assertNotNull(pm);
-
-        assertTrue(0 < pm.getPid());
-        // On most Linux machines, the max pid value is 32768 (=2^15), but, it can be set to any
-        // value up to 4194304 (=2^22) if necessary.
-        assertTrue(4194304 >= pm.getPid());
-
-        testHeapInfo(pm.getNativeHeap());
-        testHeapInfo(pm.getDalvikHeap());
-
-        for (ProcessMemory.MemoryInfo mi : pm.getOtherHeapsList()) {
-            testMemoryInfo(mi);
-        }
-        testMemoryInfo(pm.getUnknownHeap());
-        testHeapInfo(pm.getTotalHeap());
-
-        for (ProcessMemory.MemoryInfo mi : pm.getDalvikDetailsList()) {
-            testMemoryInfo(mi);
-        }
-
-        ProcessMemory.AppSummary as = pm.getAppSummary();
-        assertTrue(0 <= as.getJavaHeapPssKb());
-        assertTrue(0 <= as.getNativeHeapPssKb());
-        assertTrue(0 <= as.getCodePssKb());
-        assertTrue(0 <= as.getStackPssKb());
-        assertTrue(0 <= as.getGraphicsPssKb());
-        assertTrue(0 <= as.getPrivateOtherPssKb());
-        assertTrue(0 <= as.getSystemPssKb());
-        assertTrue(0 <= as.getTotalSwapPss());
-        assertTrue(0 <= as.getTotalSwapKb());
-    }
-
-    private static void testMemoryInfo(ProcessMemory.MemoryInfo mi) throws Exception {
-        assertNotNull(mi);
-
-        assertTrue(0 <= mi.getTotalPssKb());
-        assertTrue(0 <= mi.getCleanPssKb());
-        assertTrue(0 <= mi.getSharedDirtyKb());
-        assertTrue(0 <= mi.getPrivateDirtyKb());
-        assertTrue(0 <= mi.getSharedCleanKb());
-        assertTrue(0 <= mi.getPrivateCleanKb());
-        assertTrue(0 <= mi.getDirtySwapKb());
-        assertTrue(0 <= mi.getDirtySwapPssKb());
-    }
-
-    private static void testHeapInfo(ProcessMemory.HeapInfo hi) throws Exception {
-        assertNotNull(hi);
-
-        testMemoryInfo(hi.getMemInfo());
-        assertTrue(0 <= hi.getHeapSizeKb());
-        assertTrue(0 <= hi.getHeapAllocKb());
-        assertTrue(0 <= hi.getHeapFreeKb());
-    }
-
-    private static void testAppData(AppData ad) throws Exception {
-        assertNotNull(ad);
-
-        testProcessMemory(ad.getProcessMemory());
-
-        AppData.ObjectStats os = ad.getObjects();
-        assertTrue(0 <= os.getViewInstanceCount());
-        assertTrue(0 <= os.getViewRootInstanceCount());
-        assertTrue(0 <= os.getAppContextInstanceCount());
-        assertTrue(0 <= os.getActivityInstanceCount());
-        assertTrue(0 <= os.getGlobalAssetCount());
-        assertTrue(0 <= os.getGlobalAssetManagerCount());
-        assertTrue(0 <= os.getLocalBinderObjectCount());
-        assertTrue(0 <= os.getProxyBinderObjectCount());
-        assertTrue(0 <= os.getParcelMemoryKb());
-        assertTrue(0 <= os.getParcelCount());
-        assertTrue(0 <= os.getBinderObjectDeathCount());
-        assertTrue(0 <= os.getOpenSslSocketCount());
-        assertTrue(0 <= os.getWebviewInstanceCount());
-
-        AppData.SqlStats ss = ad.getSql();
-        assertTrue(0 <= ss.getMemoryUsedKb());
-        assertTrue(0 <= ss.getPagecacheOverflowKb());
-        assertTrue(0 <= ss.getMallocSizeKb());
-        for (AppData.SqlStats.Database d : ss.getDatabasesList()) {
-            assertTrue(0 <= d.getPageSize());
-            assertTrue(0 <= d.getDbSize());
-            assertTrue(0 <= d.getLookasideB());
-        }
-    }
-
-    private static void testMemItem(MemItem mi) throws Exception {
-        assertNotNull(mi);
-
-        assertTrue(0 <= mi.getPssKb());
-        assertTrue(0 <= mi.getSwapPssKb());
-
-        for (MemItem smi : mi.getSubItemsList()) {
-            testMemItem(smi);
-        }
-    }
-}
diff --git a/hostsidetests/scopedstorage/Android.bp b/hostsidetests/scopedstorage/Android.bp
index 3e5096b..1a1a7f9 100644
--- a/hostsidetests/scopedstorage/Android.bp
+++ b/hostsidetests/scopedstorage/Android.bp
@@ -15,28 +15,28 @@
 android_test_helper_app {
     name: "CtsScopedStorageTestAppA",
     manifest: "ScopedStorageTestHelper/TestAppA.xml",
-    static_libs: ["androidx.test.rules", "cts-scopedstorage-lib"],
+    static_libs: ["cts-scopedstorage-lib"],
     sdk_version: "test_current",
     srcs: ["ScopedStorageTestHelper/src/**/*.java"],
 }
 android_test_helper_app {
     name: "CtsScopedStorageTestAppB",
     manifest: "ScopedStorageTestHelper/TestAppB.xml",
-    static_libs: ["androidx.test.rules", "cts-scopedstorage-lib"],
+    static_libs: ["cts-scopedstorage-lib"],
     sdk_version: "test_current",
     srcs: ["ScopedStorageTestHelper/src/**/*.java"],
 }
 android_test_helper_app {
     name: "CtsScopedStorageTestAppC",
     manifest: "ScopedStorageTestHelper/TestAppC.xml",
-    static_libs: ["androidx.test.rules", "cts-scopedstorage-lib"],
+    static_libs: ["cts-scopedstorage-lib"],
     sdk_version: "test_current",
     srcs: ["ScopedStorageTestHelper/src/**/*.java"],
 }
 android_test_helper_app {
     name: "CtsScopedStorageTestAppCLegacy",
     manifest: "ScopedStorageTestHelper/TestAppCLegacy.xml",
-    static_libs: ["androidx.test.rules", "cts-scopedstorage-lib"],
+    static_libs: ["cts-scopedstorage-lib"],
     sdk_version: "test_current",
     target_sdk_version: "28",
     srcs: ["ScopedStorageTestHelper/src/**/*.java"],
@@ -46,9 +46,9 @@
     name: "ScopedStorageTest",
     manifest: "AndroidManifest.xml",
     srcs: ["src/**/*.java"],
-    static_libs: ["androidx.test.rules", "truth-prebuilt", "cts-scopedstorage-lib"],
+    static_libs: ["truth-prebuilt", "cts-scopedstorage-lib"],
     compile_multilib: "both",
-    test_suites: ["general-tests", "mts"],
+    test_suites: ["general-tests", "mts", "cts"],
     sdk_version: "test_current",
     java_resources: [
         ":CtsScopedStorageTestAppA",
@@ -61,9 +61,9 @@
     name: "LegacyStorageTest",
     manifest: "legacy/AndroidManifest.xml",
     srcs: ["legacy/src/**/*.java"],
-    static_libs: ["androidx.test.rules", "truth-prebuilt",  "cts-scopedstorage-lib"],
+    static_libs: ["truth-prebuilt", "cts-scopedstorage-lib"],
     compile_multilib: "both",
-    test_suites: ["general-tests", "mts"],
+    test_suites: ["general-tests", "mts", "cts"],
     sdk_version: "test_current",
     target_sdk_version: "29",
     java_resources: [
@@ -74,17 +74,15 @@
 java_test_host {
     name: "CtsScopedStorageHostTest",
     srcs: ["host/src/**/*.java"],
-    libs: ["tradefed"],
-    static_libs: ["testng"],
-    test_suites: ["general-tests", "mts"],
+    libs: ["tradefed", "testng"],
+    test_suites: ["general-tests", "mts", "cts"],
     test_config: "AndroidTest.xml",
 }
 
 java_test_host {
     name: "CtsScopedStoragePublicVolumeHostTest",
     srcs: ["host/src/**/*.java"],
-    libs: ["tradefed"],
-    static_libs: ["testng"],
+    libs: ["tradefed", "testng"],
     test_suites: ["general-tests", "mts"],
     test_config: "PublicVolumeTest.xml",
 }
diff --git a/hostsidetests/scopedstorage/AndroidTest.xml b/hostsidetests/scopedstorage/AndroidTest.xml
index 64599d8..43208ac 100644
--- a/hostsidetests/scopedstorage/AndroidTest.xml
+++ b/hostsidetests/scopedstorage/AndroidTest.xml
@@ -15,6 +15,10 @@
 -->
 <configuration description="External storage host test for legacy and scoped storage">
     <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_secondary_user" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="ScopedStorageTest.apk" />
@@ -23,6 +27,7 @@
     <test class="com.android.tradefed.testtype.HostTest" >
         <option name="class" value="android.scopedstorage.cts.host.LegacyStorageHostTest" />
         <option name="class" value="android.scopedstorage.cts.host.ScopedStorageHostTest" />
+        <option name="class" value="android.scopedstorage.cts.host.ScopedStorageInstantAppHostTest" />
     </test>
 
     <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
diff --git a/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java b/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java
index 2054907..8dfe7b7 100644
--- a/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java
+++ b/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java
@@ -18,6 +18,7 @@
 import static android.scopedstorage.cts.lib.RedactionTestHelper.EXIF_METADATA_QUERY;
 import static android.scopedstorage.cts.lib.RedactionTestHelper.getExifMetadata;
 import static android.scopedstorage.cts.lib.TestUtils.CAN_READ_WRITE_QUERY;
+import static android.scopedstorage.cts.lib.TestUtils.CREATE_IMAGE_ENTRY_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.CREATE_FILE_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.DELETE_FILE_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.INTENT_EXCEPTION;
@@ -26,11 +27,15 @@
 import static android.scopedstorage.cts.lib.TestUtils.OPEN_FILE_FOR_WRITE_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.QUERY_TYPE;
 import static android.scopedstorage.cts.lib.TestUtils.READDIR_QUERY;
+import static android.scopedstorage.cts.lib.TestUtils.SETATTR_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.canOpen;
+import static android.scopedstorage.cts.lib.TestUtils.getImageContentUri;
 
 import android.app.Activity;
 import android.content.Intent;
+import android.content.ContentValues;
 import android.os.Bundle;
+import android.provider.MediaStore;
 
 import androidx.annotation.Nullable;
 
@@ -73,11 +78,15 @@
                 case DELETE_FILE_QUERY:
                 case OPEN_FILE_FOR_READ_QUERY:
                 case OPEN_FILE_FOR_WRITE_QUERY:
+                case SETATTR_QUERY:
                     returnIntent = accessFile(queryType);
                     break;
                 case EXIF_METADATA_QUERY:
                     returnIntent = sendMetadata(queryType);
                     break;
+                case CREATE_IMAGE_ENTRY_QUERY:
+                    returnIntent = createImageEntry(queryType);
+                    break;
                 case "null":
                 default:
                     throw new IllegalStateException(
@@ -125,6 +134,28 @@
         }
     }
 
+    private Intent createImageEntry(String queryType) throws Exception {
+        if (getIntent().hasExtra(INTENT_EXTRA_PATH)) {
+            final String path = getIntent().getStringExtra(INTENT_EXTRA_PATH);
+            final String relativePath = path.substring(0, path.lastIndexOf('/'));
+            final String name = path.substring(path.lastIndexOf('/') + 1);
+
+            ContentValues values = new ContentValues();
+            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
+            values.put(MediaStore.Images.Media.RELATIVE_PATH, relativePath);
+            values.put(MediaStore.Images.Media.DISPLAY_NAME, name);
+
+            getContentResolver().insert(getImageContentUri(), values);
+
+            final Intent intent = new Intent(queryType);
+            intent.putExtra(queryType, true);
+            return intent;
+        } else {
+            throw new IllegalStateException(
+                    CREATE_IMAGE_ENTRY_QUERY + ": File path not set from launcher app");
+        }
+    }
+
     private Intent accessFile(String queryType) throws IOException {
         if (getIntent().hasExtra(INTENT_EXTRA_PATH)) {
             final String filePath = getIntent().getStringExtra(INTENT_EXTRA_PATH);
@@ -141,6 +172,9 @@
                 returnStatus = canOpen(file, false /* forWrite */);
             } else if (queryType.equals(OPEN_FILE_FOR_WRITE_QUERY)) {
                 returnStatus = canOpen(file, true /* forWrite */);
+            } else if (queryType.equals(SETATTR_QUERY)) {
+                int newTimeMillis = 12345000;
+                returnStatus = file.setLastModified(newTimeMillis);
             }
             final Intent intent = new Intent(queryType);
             intent.putExtra(queryType, returnStatus);
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
index 4ca2e12..8729f9b 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
@@ -20,6 +20,8 @@
 
 import static org.junit.Assert.assertTrue;
 
+import android.platform.test.annotations.AppModeFull;
+
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
@@ -32,6 +34,7 @@
  * Runs the legacy file path access tests.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
+@AppModeFull
 public class LegacyStorageHostTest extends BaseHostJUnit4Test {
     private boolean isExternalStorageSetup = false;
 
@@ -178,7 +181,22 @@
     }
 
     @Test
+    public void testCreateDoesntUpsert() throws Exception {
+        runDeviceTest("testCreateDoesntUpsert");
+    }
+
+    @Test
     public void testCaseInsensitivity() throws Exception {
         runDeviceTest("testAndroidDataObbCannotBeDeleted");
     }
+
+    @Test
+    public void testLegacyAppUpdatingOwnershipOfExistingEntry() throws Exception {
+        runDeviceTest("testLegacyAppUpdatingOwnershipOfExistingEntry");
+    }
+
+    @Test
+    public void testInsertWithUnsupportedMimeType() throws Exception {
+        runDeviceTest("testInsertWithUnsupportedMimeType");
+    }
 }
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java
index 88be97c..08349a1 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java
@@ -18,8 +18,12 @@
 
 import static org.junit.Assert.assertTrue;
 
+import android.platform.test.annotations.AppModeFull;
+
+import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;
 
 import org.junit.After;
 import org.junit.Before;
@@ -30,6 +34,7 @@
  * Runs the ScopedStorageTest tests.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
+@AppModeFull
 public class ScopedStorageHostTest extends BaseHostJUnit4Test {
     private boolean mIsExternalStorageSetup = false;
 
@@ -43,6 +48,19 @@
 
     }
 
+    /**
+     * Runs the given phase of ScopedStorageTest by calling into the device with {@code
+     * --no-isolated-storage} flag.
+     * Throws an exception if the test phase fails.
+     */
+    void runDeviceTestWithDisabledIsolatedStorage(String phase) throws Exception {
+        runDeviceTests(new DeviceTestRunOptions("android.scopedstorage.cts")
+            .setDevice(getDevice())
+            .setTestClassName("android.scopedstorage.cts.ScopedStorageTest")
+            .setTestMethodName(phase)
+            .setDisableIsolatedStorage(true));
+    }
+
     String executeShellCommand(String cmd) throws Exception {
         return getDevice().executeShellCommand(cmd);
     }
@@ -108,6 +126,11 @@
     }
 
     @Test
+    public void testDeleteAlreadyUnlinkedFile() throws Exception {
+        runDeviceTest("testDeleteAlreadyUnlinkedFile");
+
+    }
+    @Test
     public void testOpendirRestrictions() throws Exception {
         runDeviceTest("testOpendirRestrictions");
     }
@@ -352,6 +375,21 @@
     }
 
     @Test
+    public void testOpenOtherPendingFilesFromFuse() throws Exception {
+        grantPermissions("android.permission.READ_EXTERNAL_STORAGE");
+        try {
+            runDeviceTest("testOpenOtherPendingFilesFromFuse");
+        } finally {
+            revokePermissions("android.permission.READ_EXTERNAL_STORAGE");
+        }
+    }
+
+    @Test
+    public void testCantSetAttrOtherAppsFile() throws Exception {
+        runDeviceTest("testCantSetAttrOtherAppsFile");
+    }
+
+    @Test
     public void testAccess_file() throws Exception {
         grantPermissions("android.permission.READ_EXTERNAL_STORAGE");
         try {
@@ -383,6 +421,61 @@
         }
     }
 
+    @Test
+    public void testWallpaperApisNoPermission() throws Exception {
+        runDeviceTest("testWallpaperApisNoPermission");
+    }
+
+    @Test
+    public void testWallpaperApisReadExternalStorage() throws Exception {
+        grantPermissions("android.permission.READ_EXTERNAL_STORAGE");
+        try {
+            runDeviceTest("testWallpaperApisReadExternalStorage");
+        } finally {
+            revokePermissions("android.permission.READ_EXTERNAL_STORAGE");
+        }
+    }
+
+    @Test
+    public void testWallpaperApisManageExternalStorageAppOp() throws Exception {
+        runDeviceTest("testWallpaperApisManageExternalStorageAppOp");
+    }
+
+    @Test
+    public void testWallpaperApisManageExternalStoragePrivileged() throws Exception {
+        runDeviceTest("testWallpaperApisManageExternalStoragePrivileged");
+    }
+
+    @Test
+    public void testNoIsolatedStorageInstrumentationFlag() throws Exception {
+        runDeviceTestWithDisabledIsolatedStorage("testNoIsolatedStorageCanCreateFilesAnywhere");
+        runDeviceTestWithDisabledIsolatedStorage(
+                "testNoIsolatedStorageCantReadWriteOtherAppExternalDir");
+        runDeviceTestWithDisabledIsolatedStorage("testNoIsolatedStorageStorageReaddir");
+        runDeviceTestWithDisabledIsolatedStorage("testNoIsolatedStorageQueryOtherAppsFile");
+
+        // Check that appop is revoked after instrumentation is over.
+        runDeviceTest("testCreateFileInAppExternalDir");
+        runDeviceTest("testCreateFileInOtherAppExternalDir");
+        runDeviceTest("testReadWriteFilesInOtherAppExternalDir");
+    }
+
+    @Test
+    public void testRenameFromShell() throws Exception {
+        final ITestDevice device = getDevice();
+        final boolean isAdbRoot = device.isAdbRoot() ? true : false;
+        try {
+            if (isAdbRoot) {
+                device.disableAdbRoot();
+            }
+            runDeviceTest("testRenameFromShell");
+        } finally {
+            if (isAdbRoot) {
+                device.enableAdbRoot();
+            }
+        }
+    }
+
     private void grantPermissions(String... perms) throws Exception {
         for (String perm : perms) {
             executeShellCommand("pm grant android.scopedstorage.cts " + perm);
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java
new file mode 100644
index 0000000..c97b41f
--- /dev/null
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.scopedstorage.cts.host;
+
+import static org.junit.Assert.assertTrue;
+
+import android.platform.test.annotations.AppModeInstant;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Runs the ScopedStorageTest tests for an instant app.
+ */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class ScopedStorageInstantAppHostTest extends BaseHostJUnit4Test {
+    /**
+     * Runs the given phase of Test by calling into the device.
+     * Throws an exception if the test phase fails.
+     */
+    protected void runDeviceTest(String phase) throws Exception {
+        assertTrue(runDeviceTests("android.scopedstorage.cts",
+                "android.scopedstorage.cts.ScopedStorageTest", phase));
+    }
+
+    @Test
+    @AppModeInstant
+    public void testInstantAppsCantAccessExternalStorage() throws Exception {
+        runDeviceTest("testInstantAppsCantAccessExternalStorage");
+    }
+}
diff --git a/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java b/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
index 251f65a..4596cab 100644
--- a/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
+++ b/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
@@ -26,17 +26,23 @@
 import static android.scopedstorage.cts.lib.TestUtils.assertDirectoryContains;
 import static android.scopedstorage.cts.lib.TestUtils.assertFileContent;
 import static android.scopedstorage.cts.lib.TestUtils.createFileAs;
+import static android.scopedstorage.cts.lib.TestUtils.createImageEntryAs;
 import static android.scopedstorage.cts.lib.TestUtils.deleteFileAsNoThrow;
+import static android.scopedstorage.cts.lib.TestUtils.deleteWithMediaProviderNoThrow;
 import static android.scopedstorage.cts.lib.TestUtils.executeShellCommand;
 import static android.scopedstorage.cts.lib.TestUtils.getContentResolver;
 import static android.scopedstorage.cts.lib.TestUtils.getFileOwnerPackageFromDatabase;
 import static android.scopedstorage.cts.lib.TestUtils.getFileRowIdFromDatabase;
+import static android.scopedstorage.cts.lib.TestUtils.getImageContentUri;
 import static android.scopedstorage.cts.lib.TestUtils.installApp;
 import static android.scopedstorage.cts.lib.TestUtils.listAs;
+import static android.scopedstorage.cts.lib.TestUtils.openFileAs;
+import static android.scopedstorage.cts.lib.TestUtils.openWithMediaProvider;
 import static android.scopedstorage.cts.lib.TestUtils.pollForExternalStorageState;
 import static android.scopedstorage.cts.lib.TestUtils.pollForPermission;
 import static android.scopedstorage.cts.lib.TestUtils.setupDefaultDirectories;
 import static android.scopedstorage.cts.lib.TestUtils.uninstallApp;
+import static android.scopedstorage.cts.lib.TestUtils.uninstallAppNoThrow;
 
 import static com.google.common.truth.Truth.assertThat;
 
@@ -51,11 +57,15 @@
 import android.content.ContentValues;
 import android.database.Cursor;
 import android.net.Uri;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.ParcelFileDescriptor;
 import android.provider.MediaStore;
 import android.scopedstorage.cts.lib.TestUtils;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.OsConstants;
+import android.text.TextUtils;
 import android.util.Log;
 
 import androidx.test.InstrumentationRegistry;
@@ -74,6 +84,7 @@
 import java.io.FileDescriptor;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
 
@@ -92,9 +103,16 @@
     private static final String TAG = "LegacyFileAccessTest";
     static final String THIS_PACKAGE_NAME = InstrumentationRegistry.getContext().getPackageName();
 
-    static final String IMAGE_FILE_NAME = "LegacyStorageTest_file.jpg";
-    static final String VIDEO_FILE_NAME = "LegacyStorageTest_file.mp4";
-    static final String NONMEDIA_FILE_NAME = "LegacyStorageTest_file.pdf";
+    /**
+     * To help avoid flaky tests, give ourselves a unique nonce to be used for
+     * all filesystem paths, so that we don't risk conflicting with previous
+     * test runs.
+     */
+    static final String NONCE = String.valueOf(System.nanoTime());
+
+    static final String IMAGE_FILE_NAME = "LegacyStorageTest_file_" + NONCE + ".jpg";
+    static final String VIDEO_FILE_NAME = "LegacyStorageTest_file_" + NONCE + ".mp4";
+    static final String NONMEDIA_FILE_NAME = "LegacyStorageTest_file_" + NONCE + ".pdf";
 
     private static final TestApp TEST_APP_A = new TestApp("TestAppA",
             "android.scopedstorage.cts.testapp.A", 1, false, "CtsScopedStorageTestAppA.apk");
@@ -115,6 +133,7 @@
     @After
     public void teardown() throws Exception {
         executeShellCommand("rm " + getShellFile());
+        MediaStore.scanFile(getContentResolver(), getShellFile());
     }
 
     /**
@@ -203,6 +222,7 @@
 
         try {
             executeShellCommand("touch " + existingFile);
+            MediaStore.scanFile(getContentResolver(), existingFile);
             Os.open(existingFile.getPath(), OsConstants.O_RDONLY, /*mode*/ 0);
             fail("Opening file for read expected to fail: " + existingFile);
         } catch (ErrnoException expected) {
@@ -255,6 +275,7 @@
         FileDescriptor fd = null;
         try {
             executeShellCommand("touch " + existingFile);
+            MediaStore.scanFile(getContentResolver(), existingFile);
             fd = Os.open(existingFile.getPath(), OsConstants.O_RDONLY, /*mode*/ 0);
         } finally {
             if (fd != null) {
@@ -296,6 +317,7 @@
         final File shellFile = getShellFile();
 
         executeShellCommand("touch " + getShellFile());
+        MediaStore.scanFile(getContentResolver(), getShellFile());
         // can list a non-media file created by other package.
         assertThat(Arrays.asList(shellFile.getParentFile().list()))
                 .contains(shellFile.getName());
@@ -363,6 +385,7 @@
                         "LegacyFileAccessTest2");
         try {
             executeShellCommand("touch " + shellFile1);
+            MediaStore.scanFile(getContentResolver(), shellFile1);
             // app can't rename shell file.
             assertCantRenameFile(shellFile1, shellFile2);
             // app can't move shell file to its media directory.
@@ -397,6 +420,7 @@
                         "LegacyFileAccessTest2");
         try {
             executeShellCommand("touch " + shellFile1);
+            MediaStore.scanFile(getContentResolver(), shellFile1);
             // app can't rename shell file.
             assertCantRenameFile(shellFile1, shellFile2);
             // app can't move shell file to its media directory.
@@ -617,6 +641,35 @@
         }
     }
 
+    /**
+     * Test that legacy apps creating files for existing db row doesn't upsert and set IS_PENDING
+     */
+    @Test
+    public void testCreateDoesntUpsert() throws Exception {
+        pollForPermission(Manifest.permission.READ_EXTERNAL_STORAGE, /*granted*/ true);
+        pollForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, /*granted*/ true);
+
+        final File file = new File(TestUtils.getDcimDir(), IMAGE_FILE_NAME);
+        Uri uri = null;
+        try {
+            uri = TestUtils.insertFileUsingDataColumn(file);
+            assertNotNull(uri);
+
+            assertTrue(file.createNewFile());
+
+            try (Cursor c = TestUtils.queryFile(file,
+                    new String[] {MediaStore.MediaColumns.IS_PENDING})) {
+                // This file will not have IS_PENDING=1 because create didn't set IS_PENDING.
+                assertTrue(c.moveToFirst());
+                assertEquals(c.getInt(0), 0);
+            }
+        } finally {
+            file.delete();
+            // If create file fails, we should delete the inserted db row.
+            deleteWithMediaProviderNoThrow(uri);
+        }
+    }
+
     @Test
     public void testAndroidDataObbCannotBeDeleted() throws Exception {
         File canDeleteDir = new File("/sdcard/canDelete");
@@ -636,6 +689,81 @@
         assertThat(canDeleteDir.delete()).isTrue();
     }
 
+    @Test
+    public void testLegacyAppUpdatingOwnershipOfExistingEntry() throws Exception {
+        pollForPermission(Manifest.permission.READ_EXTERNAL_STORAGE, /*granted*/ true);
+        pollForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, /*granted*/ true);
+
+        final File fullPath = new File(TestUtils.getDcimDir(),
+                "OwnershipChange_" + IMAGE_FILE_NAME);
+        final String relativePath = "DCIM/OwnershipChange_" + IMAGE_FILE_NAME;
+        try {
+            installApp(TEST_APP_A, false);
+            createImageEntryAs(TEST_APP_A, relativePath);
+            assertThat(fullPath.createNewFile()).isTrue();
+
+            // We have transferred ownership away from TEST_APP_A so reads / writes
+            // should no longer work.
+            assertThat(openFileAs(TEST_APP_A, fullPath, false /* for write */)).isFalse();
+            assertThat(openFileAs(TEST_APP_A, fullPath, false /* for read */)).isFalse();
+        } finally {
+            deleteFileAsNoThrow(TEST_APP_A, fullPath.getAbsolutePath());
+            uninstallAppNoThrow(TEST_APP_A);
+            fullPath.delete();
+        }
+    }
+
+    /**
+     * b/156717256,b/156336269: Test that MediaProvider doesn't throw error on usage of unsupported
+     * or empty/null MIME type.
+     */
+    @Test
+    public void testInsertWithUnsupportedMimeType() throws Exception {
+        pollForPermission(Manifest.permission.READ_EXTERNAL_STORAGE, /*granted*/ true);
+        pollForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, /*granted*/ true);
+
+        final String IMAGE_FILE_DISPLAY_NAME = "LegacyStorageTest_file_" + NONCE;
+        final File imageFile = new File(TestUtils.getDcimDir(), IMAGE_FILE_DISPLAY_NAME + ".jpg");
+
+        for (String mimeType : new String[] {
+            "image/*", "", null, "foo/bar"
+        }) {
+            Uri uri = null;
+            try {
+                ContentValues values = new ContentValues();
+                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
+                if (TextUtils.isEmpty(mimeType)) {
+                    values.put(MediaStore.MediaColumns.DISPLAY_NAME, imageFile.getName());
+                } else {
+                    values.put(MediaStore.MediaColumns.DISPLAY_NAME, IMAGE_FILE_DISPLAY_NAME);
+                }
+                values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
+
+                uri = getContentResolver().insert(getImageContentUri(), values, Bundle.EMPTY);
+                assertNotNull(uri);
+
+                try (final OutputStream fos = getContentResolver().openOutputStream(uri, "rw")) {
+                    fos.write(BYTES_DATA1);
+                }
+
+                // Closing the file should trigger a scan, we still scan again to ensure MIME type
+                // is extracted from file extension
+                assertNotNull(MediaStore.scanFile(getContentResolver(), imageFile));
+
+                final String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME,
+                        MediaStore.MediaColumns.MIME_TYPE};
+                try (Cursor c = getContentResolver().query(uri, projection, null, null, null)) {
+                    assertTrue(c.moveToFirst());
+                    assertEquals(c.getCount(), 1);
+                    assertEquals(c.getString(0), imageFile.getName());
+                    assertTrue("image/jpeg".equalsIgnoreCase(c.getString(1)));
+                }
+            } finally {
+                deleteWithMediaProviderNoThrow(uri);
+            }
+        }
+    }
+
     private static void assertCanCreateFile(File file) throws IOException {
         if (file.exists()) {
             file.delete();
diff --git a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp
index 3a5ba59..be2ae44 100644
--- a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp
+++ b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp
@@ -15,6 +15,6 @@
 java_library {
     name: "cts-scopedstorage-lib",
     srcs: ["src/**/*.java"],
-    static_libs: ["androidx.test.rules", "cts-install-lib"],
+    static_libs: ["androidx.test.rules", "cts-install-lib", "platform-test-annotations",],
     sdk_version: "test_current"
 }
diff --git a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
index 22e6fb4..34fbe79 100644
--- a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
+++ b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
@@ -65,6 +65,7 @@
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.InterruptedIOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -84,13 +85,17 @@
     public static final String INTENT_EXTRA_PATH = "android.scopedstorage.cts.path";
     public static final String INTENT_EXCEPTION = "android.scopedstorage.cts.exception";
     public static final String CREATE_FILE_QUERY = "android.scopedstorage.cts.createfile";
+    public static final String CREATE_IMAGE_ENTRY_QUERY =
+            "android.scopedstorage.cts.createimageentry";
     public static final String DELETE_FILE_QUERY = "android.scopedstorage.cts.deletefile";
-    public static final String OPEN_FILE_FOR_READ_QUERY = "android.scopedstorage.cts.openfile_read";
+    public static final String OPEN_FILE_FOR_READ_QUERY =
+            "android.scopedstorage.cts.openfile_read";
     public static final String OPEN_FILE_FOR_WRITE_QUERY =
             "android.scopedstorage.cts.openfile_write";
     public static final String CAN_READ_WRITE_QUERY =
             "android.scopedstorage.cts.can_read_and_write";
     public static final String READDIR_QUERY = "android.scopedstorage.cts.readdir";
+    public static final String SETATTR_QUERY = "android.scopedstorage.cts.setattr";
 
     public static final String STR_DATA1 = "Just some random text";
     public static final String STR_DATA2 = "More arbitrary stuff";
@@ -102,7 +107,7 @@
     private static File sExternalStorageDirectory = Environment.getExternalStorageDirectory();
     private static String sStorageVolumeName = MediaStore.VOLUME_EXTERNAL;
 
-    private static final long POLLING_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(10);
+    private static final long POLLING_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(20);
     private static final long POLLING_SLEEP_MILLIS = 100;
 
     /**
@@ -165,7 +170,21 @@
     /**
      * Executes a shell command.
      */
-    public static String executeShellCommand(String cmd) throws Exception {
+    public static String executeShellCommand(String command) throws IOException {
+        int attempt = 0;
+        while (attempt++ < 5) {
+            try {
+                return executeShellCommandInternal(command);
+            } catch (InterruptedIOException e) {
+                // Hmm, we had trouble executing the shell command; the best we
+                // can do is try again a few more times
+                Log.v(TAG, "Trouble executing " + command + "; trying again", e);
+            }
+        }
+        throw new IOException("Failed to execute " + command);
+    }
+
+    private static String executeShellCommandInternal(String cmd) throws IOException {
         UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
         try (FileInputStream output = new FileInputStream(
                      uiAutomation.executeShellCommand(cmd).getFileDescriptor())) {
@@ -210,6 +229,17 @@
     }
 
     /**
+     * Makes the given {@code testApp} create a mediastore DB entry under
+     * {@code MediaStore.Media.Images}.
+     *
+     * The {@code path} argument is treated as a relative path and a name separated
+     * by an {@code '/'}.
+     */
+    public static boolean createImageEntryAs(TestApp testApp, String path) throws Exception {
+        return getResultFromTestApp(testApp, path, CREATE_IMAGE_ENTRY_QUERY);
+    }
+
+    /**
      * Makes the given {@code testApp} delete a file.
      *
      * <p>This method drops shell permission identity.
@@ -254,6 +284,16 @@
     }
 
     /**
+     * Makes the given {@code testApp} setattr for given file path.
+     *
+     * <p>This method drops shell permission identity.
+     */
+    public static boolean setAttrAs(TestApp testApp, String path)
+            throws Exception {
+        return getResultFromTestApp(testApp, path, SETATTR_QUERY);
+    }
+
+    /**
      * Installs a {@link TestApp} without storage permissions.
      */
     public static void installApp(TestApp testApp) throws Exception {
@@ -332,6 +372,13 @@
     }
 
     /**
+     * Returns the content URI for images based on the current storage volume.
+     */
+    public static Uri getImageContentUri() {
+        return MediaStore.Images.Media.getContentUri(sStorageVolumeName);
+    }
+
+    /**
      * Renames the given file using {@link ContentResolver} and {@link MediaStore} and APIs.
      * This method uses the data column, and not all apps can use it.
      * @see MediaStore.MediaColumns#DATA
@@ -406,7 +453,7 @@
     @NonNull
     public static Cursor queryVideoFile(File file, String... projection) {
         return queryFile(MediaStore.Video.Media.getContentUri(sStorageVolumeName), file,
-                projection);
+                /*includePending*/ true, projection);
     }
 
     /**
@@ -416,7 +463,7 @@
     @NonNull
     public static Cursor queryImageFile(File file, String... projection) {
         return queryFile(MediaStore.Images.Media.getContentUri(sStorageVolumeName), file,
-                projection);
+                /*includePending*/ true, projection);
     }
 
     /**
@@ -884,7 +931,11 @@
         intent.putExtra(INTENT_EXTRA_PATH, dirPath);
         intent.addCategory(Intent.CATEGORY_LAUNCHER);
         getContext().startActivity(intent);
-        latch.await();
+        if (!latch.await(POLLING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
+            final String errorMessage = "Timed out while waiting to receive " + actionName
+                    + " intent from " + packageName;
+            throw new TimeoutException(errorMessage);
+        }
         getContext().unregisterReceiver(broadcastReceiver);
     }
 
@@ -991,22 +1042,38 @@
         }
     }
 
+    /**
+     * Queries {@link ContentResolver} for a file IS_PENDING=0 and returns a {@link Cursor} with the
+     * given columns.
+     */
     @NonNull
-    public static Cursor queryFile(@NonNull File file, String... projection) {
-        return queryFile(
-                MediaStore.Files.getContentUri(sStorageVolumeName), file, projection);
+    public static Cursor queryFileExcludingPending(@NonNull File file, String... projection) {
+        return queryFile(MediaStore.Files.getContentUri(sStorageVolumeName), file,
+                /*includePending*/ false, projection);
     }
 
     @NonNull
-    private static Cursor queryFile(@NonNull Uri uri, @NonNull File file, String... projection) {
+    public static Cursor queryFile(@NonNull File file, String... projection) {
+        return queryFile(MediaStore.Files.getContentUri(sStorageVolumeName), file,
+                /*includePending*/ true, projection);
+    }
+
+    @NonNull
+    private static Cursor queryFile(@NonNull Uri uri, @NonNull File file, boolean includePending,
+            String... projection) {
         Bundle queryArgs = new Bundle();
         queryArgs.putString(ContentResolver.QUERY_ARG_SQL_SELECTION,
                 MediaStore.MediaColumns.DATA + " = ?");
         queryArgs.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS,
                 new String[] { file.getAbsolutePath() });
-        queryArgs.putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_INCLUDE);
         queryArgs.putInt(MediaStore.QUERY_ARG_MATCH_TRASHED, MediaStore.MATCH_INCLUDE);
 
+        if (includePending) {
+            queryArgs.putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_INCLUDE);
+        } else {
+            queryArgs.putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_EXCLUDE);
+        }
+
         final Cursor c = getContentResolver().query(uri, projection, queryArgs, null);
         assertThat(c).isNotNull();
         return c;
diff --git a/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java b/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
index 1842d1c..eb60460 100644
--- a/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
+++ b/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
@@ -27,6 +27,7 @@
 import static android.scopedstorage.cts.lib.TestUtils.BYTES_DATA2;
 import static android.scopedstorage.cts.lib.TestUtils.STR_DATA1;
 import static android.scopedstorage.cts.lib.TestUtils.STR_DATA2;
+import static android.scopedstorage.cts.lib.TestUtils.adoptShellPermissionIdentity;
 import static android.scopedstorage.cts.lib.TestUtils.allowAppOpsToUid;
 import static android.scopedstorage.cts.lib.TestUtils.assertCanRenameDirectory;
 import static android.scopedstorage.cts.lib.TestUtils.assertCanRenameFile;
@@ -44,6 +45,7 @@
 import static android.scopedstorage.cts.lib.TestUtils.deleteWithMediaProvider;
 import static android.scopedstorage.cts.lib.TestUtils.deleteWithMediaProviderNoThrow;
 import static android.scopedstorage.cts.lib.TestUtils.denyAppOpsToUid;
+import static android.scopedstorage.cts.lib.TestUtils.dropShellPermissionIdentity;
 import static android.scopedstorage.cts.lib.TestUtils.executeShellCommand;
 import static android.scopedstorage.cts.lib.TestUtils.getAlarmsDir;
 import static android.scopedstorage.cts.lib.TestUtils.getAndroidDataDir;
@@ -78,10 +80,12 @@
 import static android.scopedstorage.cts.lib.TestUtils.pollForExternalStorageState;
 import static android.scopedstorage.cts.lib.TestUtils.pollForPermission;
 import static android.scopedstorage.cts.lib.TestUtils.queryFile;
+import static android.scopedstorage.cts.lib.TestUtils.queryFileExcludingPending;
 import static android.scopedstorage.cts.lib.TestUtils.queryImageFile;
 import static android.scopedstorage.cts.lib.TestUtils.queryVideoFile;
 import static android.scopedstorage.cts.lib.TestUtils.readExifMetadataFromTestApp;
 import static android.scopedstorage.cts.lib.TestUtils.revokePermission;
+import static android.scopedstorage.cts.lib.TestUtils.setAttrAs;
 import static android.scopedstorage.cts.lib.TestUtils.setupDefaultDirectories;
 import static android.scopedstorage.cts.lib.TestUtils.uninstallApp;
 import static android.scopedstorage.cts.lib.TestUtils.uninstallAppNoThrow;
@@ -99,6 +103,7 @@
 import static androidx.test.InstrumentationRegistry.getContext;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertTrue;
@@ -110,6 +115,7 @@
 
 import android.Manifest;
 import android.app.AppOpsManager;
+import android.app.WallpaperManager;
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.database.Cursor;
@@ -119,6 +125,7 @@
 import android.os.FileUtils;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
+import android.platform.test.annotations.AppModeInstant;
 import android.provider.MediaStore;
 import android.system.ErrnoException;
 import android.system.Os;
@@ -158,14 +165,21 @@
     static final String TAG = "ScopedStorageTest";
     static final String THIS_PACKAGE_NAME = getContext().getPackageName();
 
-    static final String TEST_DIRECTORY_NAME = "ScopedStorageTestDirectory";
+    /**
+     * To help avoid flaky tests, give ourselves a unique nonce to be used for
+     * all filesystem paths, so that we don't risk conflicting with previous
+     * test runs.
+     */
+    static final String NONCE = String.valueOf(System.nanoTime());
 
-    static final String AUDIO_FILE_NAME = "ScopedStorageTest_file.mp3";
-    static final String PLAYLIST_FILE_NAME = "ScopedStorageTest_file.m3u";
-    static final String SUBTITLE_FILE_NAME = "ScopedStorageTest_file.srt";
-    static final String VIDEO_FILE_NAME = "ScopedStorageTest_file.mp4";
-    static final String IMAGE_FILE_NAME = "ScopedStorageTest_file.jpg";
-    static final String NONMEDIA_FILE_NAME = "ScopedStorageTest_file.pdf";
+    static final String TEST_DIRECTORY_NAME = "ScopedStorageTestDirectory" + NONCE;
+
+    static final String AUDIO_FILE_NAME = "ScopedStorageTest_file_" + NONCE + ".mp3";
+    static final String PLAYLIST_FILE_NAME = "ScopedStorageTest_file_" + NONCE + ".m3u";
+    static final String SUBTITLE_FILE_NAME = "ScopedStorageTest_file_" + NONCE + ".srt";
+    static final String VIDEO_FILE_NAME = "ScopedStorageTest_file_" + NONCE + ".mp4";
+    static final String IMAGE_FILE_NAME = "ScopedStorageTest_file_" + NONCE + ".jpg";
+    static final String NONMEDIA_FILE_NAME = "ScopedStorageTest_file_" + NONCE + ".pdf";
 
     static final String FILE_CREATION_ERROR_MESSAGE = "No such file or directory";
 
@@ -187,8 +201,10 @@
         // skips all test cases if FUSE is not active.
         assumeTrue(getBoolean("persist.sys.fuse", false));
 
-        pollForExternalStorageState();
-        getExternalFilesDir().mkdirs();
+        if (!getContext().getPackageManager().isInstantApp()) {
+            pollForExternalStorageState();
+            getExternalFilesDir().mkdirs();
+        }
     }
 
     /**
@@ -499,6 +515,29 @@
     }
 
     /**
+     * Test that deleting uri corresponding to a file which was already deleted via filePath
+     * doesn't result in a security exception.
+     */
+    @Test
+    public void testDeleteAlreadyUnlinkedFile() throws Exception {
+        final File nonMediaFile = new File(getDownloadDir(), NONMEDIA_FILE_NAME);
+        try {
+            assertTrue(nonMediaFile.createNewFile());
+            final Uri uri = MediaStore.scanFile(getContentResolver(), nonMediaFile);
+            assertNotNull(uri);
+
+            // Delete the file via filePath
+            assertTrue(nonMediaFile.delete());
+
+            // If we delete nonMediaFile with ContentResolver#delete, it shouldn't result in a
+            // security exception.
+            assertThat(getContentResolver().delete(uri, Bundle.EMPTY)).isEqualTo(0);
+        } finally {
+            nonMediaFile.delete();
+        }
+    }
+
+    /**
      * This test relies on the fact that {@link File#list} uses opendir internally, and that it
      * returns {@code null} if opendir fails.
      */
@@ -675,10 +714,8 @@
             // TEST_APP_A should not see other app's external files directory.
             installAppWithStoragePermissions(TEST_APP_A);
 
-            // TODO(b/157650550): we don't have consistent behaviour on both primary and public
-            //  volumes
-//            assertThrows(IOException.class,
-//                    () -> listAs(TEST_APP_A, getAndroidDataDir().getPath()));
+            assertThrows(IOException.class,
+                    () -> listAs(TEST_APP_A, getAndroidDataDir().getPath()));
             assertThrows(IOException.class,
                     () -> listAs(TEST_APP_A, getExternalFilesDir().getPath()));
         } finally {
@@ -744,6 +781,8 @@
         } finally {
             executeShellCommand("rm " + pdfFile.getAbsolutePath());
             executeShellCommand("rm " + videoFile.getAbsolutePath());
+            MediaStore.scanFile(getContentResolver(), pdfFile);
+            MediaStore.scanFile(getContentResolver(), videoFile);
             uninstallAppNoThrow(TEST_APP_A);
         }
     }
@@ -1350,6 +1389,7 @@
             videoFile.delete();
             topLevelVideoFile.delete();
             executeShellCommand("rm  " + musicFile.getAbsolutePath());
+            MediaStore.scanFile(getContentResolver(), musicFile);
             denyAppOpsToUid(Process.myUid(), SYSTEM_GALERY_APPOPS);
         }
     }
@@ -1628,8 +1668,7 @@
                     THIS_PACKAGE_NAME, TEST_APP_A.getPackageName()));
             final File otherAppExternalDataFile = new File(otherAppExternalDataDir,
                     NONMEDIA_FILE_NAME);
-            assertThat(createFileAs(TEST_APP_A, otherAppExternalDataFile.getAbsolutePath()))
-                    .isTrue();
+            assertCreateFilesAs(TEST_APP_A, otherAppExternalDataFile);
 
             // File Manager app gets global access with MANAGE_EXTERNAL_STORAGE permission, however,
             // file manager app doesn't have access to other app's external files directory
@@ -1649,6 +1688,41 @@
     }
 
     /**
+     * Tests that an instant app can't access external storage.
+     */
+    @Test
+    @AppModeInstant
+    public void testInstantAppsCantAccessExternalStorage() throws Exception {
+        assumeTrue("This test requires that the test runs as an Instant app",
+                getContext().getPackageManager().isInstantApp());
+        assertThat(getContext().getPackageManager().isInstantApp()).isTrue();
+
+        // Can't read ExternalStorageDir
+        assertThat(getExternalStorageDir().list()).isNull();
+
+        // Can't create a top-level direcotry
+        final File topLevelDir = new File(getExternalStorageDir(), TEST_DIRECTORY_NAME);
+        assertThat(topLevelDir.mkdir()).isFalse();
+
+        // Can't create file under root dir
+        final File newTxtFile = new File(getExternalStorageDir(), NONMEDIA_FILE_NAME);
+        assertThrows(IOException.class,
+                () -> { newTxtFile.createNewFile(); });
+
+        // Can't create music file under /MUSIC
+        final File newMusicFile = new File(getMusicDir(), AUDIO_FILE_NAME);
+        assertThrows(IOException.class,
+                () -> { newMusicFile.createNewFile(); });
+
+        // getExternalFilesDir() is not null
+        assertThat(getExternalFilesDir()).isNotNull();
+
+        // Can't read/write app specific dir
+        assertThat(getExternalFilesDir().list()).isNull();
+        assertThat(getExternalFilesDir().exists()).isFalse();
+    }
+
+    /**
      * Test that apps can create and delete hidden file.
      */
     @Test
@@ -2026,11 +2100,13 @@
             // Use shell to create root file because TEST_APP_A is in
             // scoped storage.
             executeShellCommand("touch " + shellPdfAtRoot.getAbsolutePath());
+            MediaStore.scanFile(getContentResolver(), shellPdfAtRoot);
             assertFileAccess_existsOnly(shellPdfAtRoot);
         } finally {
             deleteFileAsNoThrow(TEST_APP_A, otherAppPdf.getAbsolutePath());
             deleteFileAsNoThrow(TEST_APP_A, otherAppImage.getAbsolutePath());
             executeShellCommand("rm " + shellPdfAtRoot.getAbsolutePath());
+            MediaStore.scanFile(getContentResolver(), shellPdfAtRoot);
             myAppPdf.delete();
             uninstallApp(TEST_APP_A);
         }
@@ -2154,6 +2230,7 @@
             installApp(TEST_APP_A);
             assertCreateFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
             executeShellCommand("touch " + otherTopLevelFile);
+            MediaStore.scanFile(getContentResolver(), otherTopLevelFile);
 
             allowAppOpsToUid(Process.myUid(), OPSTR_MANAGE_EXTERNAL_STORAGE);
 
@@ -2169,6 +2246,7 @@
         } finally {
             denyAppOpsToUid(Process.myUid(), OPSTR_MANAGE_EXTERNAL_STORAGE);
             executeShellCommand("rm " + otherTopLevelFile);
+            MediaStore.scanFile(getContentResolver(), otherTopLevelFile);
             deleteFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
             uninstallApp(TEST_APP_A);
         }
@@ -2273,6 +2351,7 @@
             assertThat(dirInDcim.exists() || dirInDcim.mkdir()).isTrue();
 
             executeShellCommand("touch " + otherAppPdfFile1);
+            MediaStore.scanFile(getContentResolver(), otherAppPdfFile1);
 
             installAppWithStoragePermissions(TEST_APP_A);
             allowAppOpsToUid(Process.myUid(), SYSTEM_GALERY_APPOPS);
@@ -2291,6 +2370,8 @@
         } finally {
             executeShellCommand("rm " + otherAppPdfFile1);
             executeShellCommand("rm " + otherAppPdfFile2);
+            MediaStore.scanFile(getContentResolver(), otherAppPdfFile1);
+            MediaStore.scanFile(getContentResolver(), otherAppPdfFile2);
             otherAppImageFile1.delete();
             otherAppImageFile2.delete();
             otherAppVideoFile1.delete();
@@ -2407,6 +2488,50 @@
         }
     }
 
+    @Test
+    public void testWallpaperApisNoPermission() throws Exception {
+        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getContext());
+        assertThrows(SecurityException.class, () -> wallpaperManager.getFastDrawable());
+        assertThrows(SecurityException.class, () -> wallpaperManager.peekFastDrawable());
+        assertThrows(SecurityException.class,
+                () -> wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM));
+    }
+
+    @Test
+    public void testWallpaperApisReadExternalStorage() throws Exception {
+        pollForPermission(Manifest.permission.READ_EXTERNAL_STORAGE, /*granted*/ true);
+        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getContext());
+        wallpaperManager.getFastDrawable();
+        wallpaperManager.peekFastDrawable();
+        wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
+    }
+
+    @Test
+    public void testWallpaperApisManageExternalStorageAppOp() throws Exception {
+        try {
+            allowAppOpsToUid(Process.myUid(), OPSTR_MANAGE_EXTERNAL_STORAGE);
+            WallpaperManager wallpaperManager = WallpaperManager.getInstance(getContext());
+            wallpaperManager.getFastDrawable();
+            wallpaperManager.peekFastDrawable();
+            wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
+        } finally {
+            denyAppOpsToUid(Process.myUid(), OPSTR_MANAGE_EXTERNAL_STORAGE);
+        }
+    }
+
+    @Test
+    public void testWallpaperApisManageExternalStoragePrivileged() throws Exception {
+        adoptShellPermissionIdentity(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
+        try {
+            WallpaperManager wallpaperManager = WallpaperManager.getInstance(getContext());
+            wallpaperManager.getFastDrawable();
+            wallpaperManager.peekFastDrawable();
+            wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
+        } finally {
+            dropShellPermissionIdentity();
+        }
+    }
+
     /**
      * Verifies that files created by {@code otherApp} in shared locations {@code imageDir}
      * and {@code documentDir} follow the scoped storage rules. Requires the running app to hold
@@ -2439,6 +2564,7 @@
     @Test
     public void testPendingFromFuse() throws Exception {
         final File pendingFile = new File(getDcimDir(), IMAGE_FILE_NAME);
+        final File otherPendingFile = new File(getDcimDir(), VIDEO_FILE_NAME);
         try {
             assertTrue(pendingFile.createNewFile());
             // Newly created file should have IS_PENDING set
@@ -2447,6 +2573,13 @@
                 assertThat(c.getInt(0)).isEqualTo(1);
             }
 
+            // If we query with MATCH_EXCLUDE, we should still see this pendingFile
+            try (Cursor c = queryFileExcludingPending(pendingFile, MediaColumns.IS_PENDING)) {
+                assertThat(c.getCount()).isEqualTo(1);
+                assertTrue(c.moveToFirst());
+                assertThat(c.getInt(0)).isEqualTo(1);
+            }
+
             assertNotNull(MediaStore.scanFile(getContentResolver(), pendingFile));
 
             // IS_PENDING should be unset after the scan
@@ -2454,8 +2587,196 @@
                 assertTrue(c.moveToFirst());
                 assertThat(c.getInt(0)).isEqualTo(0);
             }
+
+            installAppWithStoragePermissions(TEST_APP_A);
+            assertCreateFilesAs(TEST_APP_A, otherPendingFile);
+            // We can't query other apps pending file from FUSE with MATCH_EXCLUDE
+            try (Cursor c = queryFileExcludingPending(otherPendingFile, MediaColumns.IS_PENDING)) {
+                assertThat(c.getCount()).isEqualTo(0);
+            }
         } finally {
             pendingFile.delete();
+            deleteFileAsNoThrow(TEST_APP_A, otherPendingFile.getAbsolutePath());
+            uninstallAppNoThrow(TEST_APP_A);
+        }
+    }
+
+    @Test
+    public void testOpenOtherPendingFilesFromFuse() throws Exception {
+        final File otherPendingFile = new File(getDcimDir(), IMAGE_FILE_NAME);
+        try {
+            installApp(TEST_APP_A);
+            assertCreateFilesAs(TEST_APP_A, otherPendingFile);
+
+            // We can read other app's pending file from FUSE via filePath
+            assertCanQueryAndOpenFile(otherPendingFile, "r");
+
+            // We can also read other app's pending file via MediaStore API
+            assertNotNull(openWithMediaProvider(otherPendingFile, "r"));
+        } finally {
+            deleteFileAsNoThrow(TEST_APP_A, otherPendingFile.getAbsolutePath());
+            uninstallAppNoThrow(TEST_APP_A);
+        }
+    }
+
+    /**
+     * Test that apps can't set attributes on another app's files.
+     */
+    @Test
+    public void testCantSetAttrOtherAppsFile() throws Exception {
+        // This path's permission is checked in MediaProvider (directory/external media dir)
+        final File externalMediaPath = new File(getExternalMediaDir(), VIDEO_FILE_NAME);
+
+        try {
+            // Create the files
+            if (!externalMediaPath.exists()) {
+                assertThat(externalMediaPath.createNewFile()).isTrue();
+            }
+
+            // Install TEST_APP_A with READ_EXTERNAL_STORAGE permission.
+            installAppWithStoragePermissions(TEST_APP_A);
+
+            // TEST_APP_A should not be able to setattr to other app's files.
+            assertWithMessage(
+                "setattr on directory/external media path [%s]", externalMediaPath.getPath())
+                .that(setAttrAs(TEST_APP_A, externalMediaPath.getPath()))
+                .isFalse();
+        } finally {
+            externalMediaPath.delete();
+            uninstallAppNoThrow(TEST_APP_A);
+        }
+    }
+
+    @Test
+    public void testNoIsolatedStorageCanCreateFilesAnywhere() throws Exception {
+        final File topLevelPdf = new File(getExternalStorageDir(), NONMEDIA_FILE_NAME);
+        final File musicFileInMovies = new File(getMoviesDir(), AUDIO_FILE_NAME);
+        final File imageFileInDcim = new File(getDcimDir(), IMAGE_FILE_NAME);
+        // Nothing special about this, anyone can create an image file in DCIM
+        assertCanCreateFile(imageFileInDcim);
+        // This is where we see the special powers of MANAGE_EXTERNAL_STORAGE, because it can
+        // create a top level file
+        assertCanCreateFile(topLevelPdf);
+        // It can even create a music file in Pictures
+        assertCanCreateFile(musicFileInMovies);
+    }
+
+    @Test
+    public void testNoIsolatedStorageCantReadWriteOtherAppExternalDir() throws Exception {
+        try {
+            // Install TEST_APP_A with READ_EXTERNAL_STORAGE permission.
+            installAppWithStoragePermissions(TEST_APP_A);
+
+            // Let app A create a file in its data dir
+            final File otherAppExternalDataDir = new File(getExternalFilesDir().getPath().replace(
+                    THIS_PACKAGE_NAME, TEST_APP_A.getPackageName()));
+            final File otherAppExternalDataFile = new File(otherAppExternalDataDir,
+                    NONMEDIA_FILE_NAME);
+            assertCreateFilesAs(TEST_APP_A, otherAppExternalDataFile);
+
+            // File Manager app gets global access with MANAGE_EXTERNAL_STORAGE permission, however,
+            // file manager app doesn't have access to other app's external files directory
+            assertThat(canOpen(otherAppExternalDataFile, /* forWrite */ false)).isFalse();
+            assertThat(canOpen(otherAppExternalDataFile, /* forWrite */ true)).isFalse();
+            assertThat(otherAppExternalDataFile.delete()).isFalse();
+
+            assertThat(deleteFileAs(TEST_APP_A, otherAppExternalDataFile.getPath())).isTrue();
+
+            assertThrows(IOException.class,
+                    () -> { otherAppExternalDataFile.createNewFile(); });
+
+        } finally {
+            uninstallApp(TEST_APP_A); // Uninstalling deletes external app dirs
+        }
+    }
+
+    @Test
+    public void testNoIsolatedStorageStorageReaddir() throws Exception {
+        final File otherAppPdf = new File(getDownloadDir(), "other" + NONMEDIA_FILE_NAME);
+        final File otherAppImg = new File(getDcimDir(), "other" + IMAGE_FILE_NAME);
+        final File otherAppMusic = new File(getMusicDir(), "other" + AUDIO_FILE_NAME);
+        final File otherTopLevelFile = new File(getExternalStorageDir(),
+                "other" + NONMEDIA_FILE_NAME);
+        try {
+            installApp(TEST_APP_A);
+            assertCreateFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
+            executeShellCommand("touch " + otherTopLevelFile);
+
+            // We can list other apps' files
+            assertDirectoryContains(otherAppPdf.getParentFile(), otherAppPdf);
+            assertDirectoryContains(otherAppImg.getParentFile(), otherAppImg);
+            assertDirectoryContains(otherAppMusic.getParentFile(), otherAppMusic);
+            // We can list top level files
+            assertDirectoryContains(getExternalStorageDir(), otherTopLevelFile);
+
+            // We can also list all top level directories
+            assertDirectoryContains(getExternalStorageDir(), getDefaultTopLevelDirs());
+        } finally {
+            executeShellCommand("rm " + otherTopLevelFile);
+            deleteFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
+            uninstallApp(TEST_APP_A);
+        }
+    }
+
+    @Test
+    public void testNoIsolatedStorageQueryOtherAppsFile() throws Exception {
+        final File otherAppPdf = new File(getDownloadDir(), "other" + NONMEDIA_FILE_NAME);
+        final File otherAppImg = new File(getDcimDir(), "other" + IMAGE_FILE_NAME);
+        final File otherAppMusic = new File(getMusicDir(), "other" + AUDIO_FILE_NAME);
+        final File otherHiddenFile = new File(getPicturesDir(), ".otherHiddenFile.jpg");
+        try {
+            installApp(TEST_APP_A);
+            // Apps can't query other app's pending file, hence create file and publish it.
+            assertCreatePublishedFilesAs(
+                    TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf, otherHiddenFile);
+
+            assertCanQueryAndOpenFile(otherAppPdf, "rw");
+            assertCanQueryAndOpenFile(otherAppImg, "rw");
+            assertCanQueryAndOpenFile(otherAppMusic, "rw");
+            assertCanQueryAndOpenFile(otherHiddenFile, "rw");
+        } finally {
+            deleteFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf, otherHiddenFile);
+            uninstallApp(TEST_APP_A);
+        }
+    }
+
+    @Test
+    public void testRenameFromShell() throws Exception {
+        final File imageFile = new File(getPicturesDir(), IMAGE_FILE_NAME);
+        final File dir = new File(getMoviesDir(), TEST_DIRECTORY_NAME);
+        final File renamedDir = new File(getMusicDir(), TEST_DIRECTORY_NAME);
+        final File renamedImageFile = new File(dir, IMAGE_FILE_NAME);
+        final File imageFileInRenamedDir = new File(renamedDir, IMAGE_FILE_NAME);
+        try {
+            assertTrue(imageFile.createNewFile());
+            assertThat(getFileRowIdFromDatabase(imageFile)).isNotEqualTo(-1);
+            if (!dir.exists()) {
+                assertThat(dir.mkdir()).isTrue();
+            }
+
+            final String renameFileCommand = String.format("mv %s %s",
+                    imageFile.getAbsolutePath(), renamedImageFile.getAbsolutePath());
+            executeShellCommand(renameFileCommand);
+            assertFalse(imageFile.exists());
+            assertThat(getFileRowIdFromDatabase(imageFile)).isEqualTo(-1);
+            assertTrue(renamedImageFile.exists());
+            assertThat(getFileRowIdFromDatabase(renamedImageFile)).isNotEqualTo(-1);
+
+            final String renameDirectoryCommand = String.format("mv %s %s",
+                    dir.getAbsolutePath(), renamedDir.getAbsolutePath());
+            executeShellCommand(renameDirectoryCommand);
+            assertFalse(dir.exists());
+            assertFalse(renamedImageFile.exists());
+            assertThat(getFileRowIdFromDatabase(renamedImageFile)).isEqualTo(-1);
+            assertTrue(renamedDir.exists());
+            assertTrue(imageFileInRenamedDir.exists());
+            assertThat(getFileRowIdFromDatabase(imageFileInRenamedDir)).isNotEqualTo(-1);
+        } finally {
+            imageFile.delete();
+            renamedImageFile.delete();
+            imageFileInRenamedDir.delete();
+            dir.delete();
+            renamedDir.delete();
         }
     }
 
diff --git a/hostsidetests/securitybulletin/Android.bp b/hostsidetests/securitybulletin/Android.bp
index 6a574c9..f17395e 100644
--- a/hostsidetests/securitybulletin/Android.bp
+++ b/hostsidetests/securitybulletin/Android.bp
@@ -53,4 +53,8 @@
         "vts10",
         "sts",
     ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
 }
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/Android.bp b/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
index 3f4087f..c20e845 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
@@ -13,15 +13,22 @@
 // limitations under the License.
 
 filegroup {
-    name: "cts_securitybulletin_memutils",
+    name: "cts_hostsidetests_securitybulletin_memutils",
     srcs: [
         "memutils.c",
     ],
 }
 
 filegroup {
-    name: "cts_securitybulletin_omxutils",
+    name: "cts_hostsidetests_securitybulletin_omxutils",
     srcs: [
         "omxUtils.cpp",
     ],
 }
+
+filegroup {
+    name: "cts_hostsidetests_securitybulletin_memutils_track",
+    srcs: [
+        "memutils_track.c",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/memutils.c b/hostsidetests/securitybulletin/securityPatch/includes/memutils.c
index 650d2f6..65e1e90 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/memutils.c
+++ b/hostsidetests/securitybulletin/securityPatch/includes/memutils.c
@@ -61,6 +61,7 @@
     if (NULL == real_memalign) {
         return;
     }
+#ifndef DISABLE_MALLOC_OVERLOADING
     real_calloc = dlsym(RTLD_NEXT, "calloc");
     if (NULL == real_calloc) {
         return;
@@ -73,6 +74,7 @@
     if (NULL == real_realloc) {
         return;
     }
+#endif /* DISABLE_MALLOC_OVERLOADING */
     real_free = dlsym(RTLD_NEXT, "free");
     if (NULL == real_free) {
         return;
@@ -99,14 +101,6 @@
     size_t num_pages;
     size_t page_size = getpagesize();
 
-    /* User specified alignment is not respected and is overridden by
-     * "new_alignment". This is required to catch OOB read when read offset is
-     * less than user specified alignment. "new_alignment" is derived based on
-     * size_t, and helps to avoid bus errors due to non-aligned memory.
-     * "new_alignment", whenever used, is checked to ensure sizeof(size_t)
-     * has returned proper value                                            */
-    size_t new_alignment = sizeof(size_t);
-
     if (s_mem_map_index == MAX_ENTRIES) {
         return real_memalign(alignment, size);
     }
@@ -115,13 +109,16 @@
         return real_memalign(alignment, size);
     }
 
-    if ((0 == page_size) || (0 == alignment) || (0 == size)
-            || (0 == new_alignment)) {
+    if ((0 == page_size) || (0 == alignment) || (0 == size)) {
         return real_memalign(alignment, size);
     }
 #ifdef CHECK_OVERFLOW
-    if (0 != (size % new_alignment)) {
-        aligned_size = size + (new_alignment - (size % new_alignment));
+    /* User specified alignment is not respected and is overridden by
+     * MINIMUM_ALIGNMENT. This is required to catch OOB read when read offset
+     * is less than user specified alignment. "MINIMUM_ALIGNMENT" helps to
+     * avoid bus errors due to non-aligned memory.                         */
+    if (0 != (size % MINIMUM_ALIGNMENT)) {
+        aligned_size = size + (MINIMUM_ALIGNMENT - (size % MINIMUM_ALIGNMENT));
     }
 #endif
 
@@ -134,11 +131,7 @@
     total_size = (num_pages * page_size);
     start_ptr = (char *) real_memalign(page_size, total_size);
 #ifdef CHECK_OVERFLOW
-#ifdef FORCE_UNALIGN
-    mem_ptr = (char *) start_ptr + ((num_pages - 1) * page_size) - size;
-#else
     mem_ptr = (char *) start_ptr + ((num_pages - 1) * page_size) - aligned_size;
-#endif /* FORCE_UNALIGN */
     DISABLE_MEM_ACCESS((start_ptr + ((num_pages - 1) * page_size)), page_size);
 #endif /* CHECK_OVERFLOW */
 #ifdef CHECK_UNDERFLOW
@@ -154,6 +147,7 @@
     return mem_ptr;
 }
 
+#ifndef DISABLE_MALLOC_OVERLOADING
 void *malloc(size_t size) {
     if (s_memutils_initialized == 0) {
         memutils_init();
@@ -163,7 +157,7 @@
         return real_malloc(size);
     }
 #endif /* ENABLE_SELECTIVE_OVERLOADING */
-    return memalign(sizeof(size_t), size);
+    return memalign(MINIMUM_ALIGNMENT, size);
 }
 
 void *calloc(size_t nitems, size_t size) {
@@ -210,6 +204,7 @@
     }
     return real_realloc(ptr, size);
 }
+#endif /* DISABLE_MALLOC_OVERLOADING */
 
 void free(void *ptr) {
     if (s_memutils_initialized == 0) {
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/memutils.h b/hostsidetests/securitybulletin/securityPatch/includes/memutils.h
index 10ee31e..4d3791e 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/memutils.h
+++ b/hostsidetests/securitybulletin/securityPatch/includes/memutils.h
@@ -19,6 +19,7 @@
 #endif /* __cplusplus */
 #define MAX_ENTRIES        (1024 * 1024)
 #define INITIAL_VAL        (0xBE)
+#define MINIMUM_ALIGNMENT  (16)
 
 #define DISABLE_MEM_ACCESS(mem, size)\
     mprotect((char *) mem, size, PROT_NONE);
@@ -43,9 +44,11 @@
 } map_struct_t;
 
 static void* (*real_memalign)(size_t, size_t) = NULL;
+#ifndef DISABLE_MALLOC_OVERLOADING
 static void* (*real_calloc)(size_t, size_t) = NULL;
 static void* (*real_malloc)(size_t) = NULL;
 static void* (*real_realloc)(void *ptr, size_t size) = NULL;
+#endif /* DISABLE_MALLOC_OVERLOADING */
 static void (*real_free)(void *) = NULL;
 static int s_memutils_initialized = 0;
 static int s_mem_map_index = 0;
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
new file mode 100644
index 0000000..80e125f
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
@@ -0,0 +1,205 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#define _GNU_SOURCE
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/mman.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <dlfcn.h>
+#include <string.h>
+#include <unistd.h>
+#include "common.h"
+#include "memutils_track.h"
+
+void memutils_init(void) {
+    real_memalign = dlsym(RTLD_NEXT, "memalign");
+    if (!real_memalign) {
+        return;
+    }
+    real_malloc = dlsym(RTLD_NEXT, "malloc");
+    if (!real_malloc) {
+        return;
+    }
+    real_free = dlsym(RTLD_NEXT, "free");
+    if (!real_free) {
+        return;
+    }
+
+#ifdef CHECK_MEMORY_LEAK
+    real_calloc = dlsym(RTLD_NEXT, "calloc");
+    if (!real_calloc) {
+        return;
+    }
+    atexit(exit_vulnerable_if_memory_leak_detected);
+#endif /* CHECK_MEMORY_LEAK */
+
+    s_memutils_initialized = true;
+}
+
+void *memalign(size_t alignment, size_t size) {
+    if (!s_memutils_initialized) {
+        memutils_init();
+    }
+    void* mem_ptr = real_memalign(alignment, size);
+
+#ifdef CHECK_UNINITIALIZED_MEMORY
+    if(mem_ptr) {
+        memset(mem_ptr, INITIAL_VAL, size);
+    }
+#endif /* CHECK_UNINITIALIZED_MEMORY */
+
+#ifdef ENABLE_SELECTIVE_OVERLOADING
+    if ((enable_selective_overload & ENABLE_MEMALIGN_CHECK) != ENABLE_MEMALIGN_CHECK) {
+        return mem_ptr;
+    }
+#endif /* ENABLE_SELECTIVE_OVERLOADING */
+
+    if (!is_tracking_required(size)) {
+        return mem_ptr;
+    }
+    if (s_allocation_index >= MAX_ENTRIES) {
+        return mem_ptr;
+    }
+    s_allocation_list[s_allocation_index].mem_ptr = mem_ptr;
+    s_allocation_list[s_allocation_index].mem_size = size;
+    ++s_allocation_index;
+    return mem_ptr;
+}
+
+void *malloc(size_t size) {
+    if (!s_memutils_initialized) {
+        memutils_init();
+    }
+    void* mem_ptr = real_malloc(size);
+
+#ifdef CHECK_UNINITIALIZED_MEMORY
+    if(mem_ptr) {
+        memset(mem_ptr, INITIAL_VAL, size);
+    }
+#endif /* CHECK_UNINITIALIZED_MEMORY */
+
+#ifdef ENABLE_SELECTIVE_OVERLOADING
+    if ((enable_selective_overload & ENABLE_MALLOC_CHECK) != ENABLE_MALLOC_CHECK) {
+        return mem_ptr;
+    }
+#endif /* ENABLE_SELECTIVE_OVERLOADING */
+
+    if (!is_tracking_required(size)) {
+        return mem_ptr;
+    }
+    if (s_allocation_index >= MAX_ENTRIES) {
+        return mem_ptr;
+    }
+    s_allocation_list[s_allocation_index].mem_ptr = mem_ptr;
+    s_allocation_list[s_allocation_index].mem_size = size;
+    ++s_allocation_index;
+    return mem_ptr;
+}
+
+void free(void *ptr) {
+    if (!s_memutils_initialized) {
+        memutils_init();
+    }
+    if (ptr) {
+        for (int i = 0; i < s_allocation_index; ++i) {
+            if (ptr == s_allocation_list[i].mem_ptr) {
+                real_free(ptr);
+                memset(&s_allocation_list[i], 0,
+                       sizeof(allocated_memory_struct));
+                return;
+            }
+        }
+    }
+    return real_free(ptr);
+}
+
+#ifdef CHECK_MEMORY_LEAK
+void *calloc(size_t nitems, size_t size) {
+    if (!s_memutils_initialized) {
+        memutils_init();
+    }
+    void* mem_ptr = real_calloc(nitems, size);
+
+#ifdef ENABLE_SELECTIVE_OVERLOADING
+    if ((enable_selective_overload & ENABLE_CALLOC_CHECK) != ENABLE_CALLOC_CHECK) {
+        return mem_ptr;
+    }
+#endif /* ENABLE_SELECTIVE_OVERLOADING */
+
+    if (!is_tracking_required((nitems *size))) {
+        return mem_ptr;
+    }
+    if (s_allocation_index >= MAX_ENTRIES) {
+        return mem_ptr;
+    }
+    s_allocation_list[s_allocation_index].mem_ptr = mem_ptr;
+    s_allocation_list[s_allocation_index].mem_size = nitems * size;
+    ++s_allocation_index;
+    return mem_ptr;
+}
+
+void exit_vulnerable_if_memory_leak_detected(void) {
+    bool memory_leak_detected = false;
+    for (int i = 0; i < s_allocation_index; ++i) {
+        if (s_allocation_list[i].mem_ptr) {
+            real_free(s_allocation_list[i].mem_ptr);
+            memset(&s_allocation_list[i], 0,
+                    sizeof(allocated_memory_struct));
+            memory_leak_detected = true;
+        }
+    }
+    if(memory_leak_detected) {
+        exit(EXIT_VULNERABLE);
+    }
+    return;
+}
+#endif /* CHECK_MEMORY_LEAK */
+
+#ifdef CHECK_UNINITIALIZED_MEMORY
+bool is_memory_uninitialized() {
+    for (int i = 0; i < s_allocation_index; ++i) {
+        char *mem_ptr = s_allocation_list[i].mem_ptr;
+        size_t mem_size = s_allocation_list[i].mem_size;
+        if (mem_ptr) {
+
+#ifdef CHECK_FOUR_BYTES
+            if(mem_size > (2 * sizeof(uint32_t))) {
+                char *mem_ptr_start = (char *)s_allocation_list[i].mem_ptr;
+                char *mem_ptr_end = (char *)s_allocation_list[i].mem_ptr + mem_size - 1;
+                for (size_t j = 0; j < sizeof(uint32_t); ++j) {
+                    if (*mem_ptr_start++ == INITIAL_VAL) {
+                        return true;
+                    }
+                    if (*mem_ptr_end-- == INITIAL_VAL) {
+                        return true;
+                    }
+                }
+                continue;
+            }
+#endif /* CHECK_FOUR_BYTES */
+
+            for (size_t j = 0; j < mem_size; ++j) {
+                if (*mem_ptr++ == INITIAL_VAL) {
+                    return true;
+                }
+            }
+        }
+    }
+    return false;
+}
+
+#endif /* CHECK_UNINITIALIZED_MEMORY */
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.h b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.h
new file mode 100644
index 0000000..dff76e2
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.h
@@ -0,0 +1,59 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#define MAX_ENTRIES               (32 * 1024)
+#define INITIAL_VAL               0xBE
+
+#define ENABLE_NONE               0x00
+#define ENABLE_MEMALIGN_CHECK     0x01
+#define ENABLE_MALLOC_CHECK       0x02
+#define ENABLE_CALLOC_CHECK       0x04
+#define ENABLE_ALL                ENABLE_MEMALIGN_CHECK | ENABLE_MALLOC_CHECK |\
+    ENABLE_CALLOC_CHECK
+
+typedef struct {
+    void *mem_ptr;
+    size_t mem_size;
+} allocated_memory_struct;
+
+static bool s_memutils_initialized = false;
+static int s_allocation_index = 0;
+static allocated_memory_struct s_allocation_list[MAX_ENTRIES] = { { 0, 0 } };
+
+extern bool is_tracking_required(size_t size);
+static void* (*real_memalign)(size_t, size_t) = NULL;
+static void* (*real_malloc)(size_t) = NULL;
+static void (*real_free)(void *) = NULL;
+
+#ifdef ENABLE_SELECTIVE_OVERLOADING
+extern char enable_selective_overload;
+#endif /* ENABLE_SELECTIVE_OVERLOADING */
+
+#ifdef CHECK_MEMORY_LEAK
+static void* (*real_calloc)(size_t, size_t) = NULL;
+void exit_vulnerable_if_memory_leak_detected(void);
+#endif
+
+#ifdef CHECK_UNINITIALIZED_MEMORY
+extern bool is_memory_uninitialized();
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/omxUtils.h b/hostsidetests/securitybulletin/securityPatch/includes/omxUtils.h
index 8986c32..aeea4a0 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/omxUtils.h
+++ b/hostsidetests/securitybulletin/securityPatch/includes/omxUtils.h
@@ -34,7 +34,7 @@
 #include <android/IOMXBufferSource.h>
 #include <media/omx/1.0/WOmx.h>
 #include <binder/MemoryDealer.h>
-#include "HardwareAPI.h"
+#include "media/hardware/HardwareAPI.h"
 #include "OMX_Component.h"
 #include <binder/ProcessState.h>
 #include <media/stagefright/foundation/ALooper.h>
diff --git a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
index a7922db..93064e6 100644
--- a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
@@ -331,6 +331,15 @@
     }
 
     @Test
+    public void testStageAnotherSessionImmediatelyAfterAbandonMultiPackage() throws Exception {
+        assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+        int sessionId = stageMultipleApks(TestApp.Apex2, TestApp.A1, TestApp.B1)
+                .assertSuccessful().getSessionId();
+        abandonSession(sessionId);
+        stageSingleApk(TestApp.Apex2).assertSuccessful();
+    }
+
+    @Test
     public void testNoSessionUpdatedBroadcastSentForStagedSessionAbandon() throws Exception {
         assertThat(getInstalledVersion(TestApp.A)).isEqualTo(-1);
         assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(1);
diff --git a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
index 3345f62..427dbcc 100644
--- a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
@@ -138,6 +138,12 @@
     }
 
     @Test
+    public void testStageAnotherSessionImmediatelyAfterAbandonMultiPackage() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+        runPhase("testStageAnotherSessionImmediatelyAfterAbandonMultiPackage");
+    }
+
+    @Test
     public void testNoSessionUpdatedBroadcastSentForStagedSessionAbandon() throws Exception {
         assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
         runPhase("testNoSessionUpdatedBroadcastSentForStagedSessionAbandon");
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
index 9311656..144e28e 100644
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
+++ b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
@@ -200,6 +200,7 @@
         // Op 96 was deprecated/removed
         APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, 97);
         APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_MANAGED_BY_INSTALLER, 98);
+        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NO_ISOLATED_STORAGE, 99);
     }
 
     @Test
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java b/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
index 4c0e4e6..7ad2d17 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
@@ -76,6 +76,7 @@
             Thread.sleep(10);
         }
         doAppBreadcrumbReportedStart(/* irrelevant val */ 6); // Event, after TTL_TIME_SEC secs.
+        Thread.sleep(WAIT_TIME_SHORT);
         report = getStatsdStatsReport();
         LogUtil.CLog.d("got following statsdstats report: " + report.toString());
         foundActiveConfig = false;
diff --git a/hostsidetests/systemui/src/android/host/systemui/TvMicrophoneCaptureIndicatorTest.java b/hostsidetests/systemui/src/android/host/systemui/TvMicrophoneCaptureIndicatorTest.java
index c42faa2..674226c 100644
--- a/hostsidetests/systemui/src/android/host/systemui/TvMicrophoneCaptureIndicatorTest.java
+++ b/hostsidetests/systemui/src/android/host/systemui/TvMicrophoneCaptureIndicatorTest.java
@@ -37,12 +37,14 @@
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
 import org.junit.After;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.List;
 
+@Ignore
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class TvMicrophoneCaptureIndicatorTest extends BaseHostJUnit4Test {
     private static final String SHELL_AM_START_FG_SERVICE =
diff --git a/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java b/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
index 4a3570b..ad1fae9 100644
--- a/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
+++ b/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
@@ -62,10 +62,16 @@
 import org.junit.runner.RunWith;
 
 import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Random;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
@@ -81,12 +87,16 @@
 
     private static final long TIMEOUT_BIND_SERVICE_SEC = 2;
 
+    private static final long TIMEOUT_WAIT_FOR_IDLE_MS = 2_000;
+
     // TODO: Make it a @TestApi or move the test using this to a different location.
     // Copy of DeviceConfig.NAMESPACE_BLOBSTORE constant
     private static final String NAMESPACE_BLOBSTORE = "blobstore";
     private static final String KEY_SESSION_EXPIRY_TIMEOUT_MS = "session_expiry_timeout_ms";
     private static final String KEY_LEASE_ACQUISITION_WAIT_DURATION_MS =
             "lease_acquisition_wait_time_ms";
+    private static final String KEY_DELETE_ON_LAST_LEASE_DELAY_MS =
+            "delete_on_last_lease_delay_ms";
     private static final String KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR =
             "total_bytes_per_app_limit_floor";
     public static final String KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION =
@@ -202,9 +212,15 @@
                 blobData.readFromSessionAndVerifyBytes(session,
                         101 /* offset */, 1001 /* length */);
 
-                blobData.writeToSession(session, 202 /* offset */, 2002 /* length */);
+                blobData.writeToSession(session, 202 /* offset */, 2002 /* length */,
+                        blobData.getFileSize());
                 blobData.readFromSessionAndVerifyBytes(session,
                         202 /* offset */, 2002 /* length */);
+
+                final CompletableFuture<Integer> callback = new CompletableFuture<>();
+                session.commit(mContext.getMainExecutor(), callback::complete);
+                assertThat(callback.get(TIMEOUT_COMMIT_CALLBACK_SEC, TimeUnit.SECONDS))
+                        .isEqualTo(0);
             }
         } finally {
             blobData.delete();
@@ -592,6 +608,228 @@
     }
 
     @Test
+    public void testSessionCommit_incompleteData() throws Exception {
+        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        blobData.prepare();
+        try {
+            final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
+            assertThat(sessionId).isGreaterThan(0L);
+
+            try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
+                blobData.writeToSession(session, 0, blobData.getFileSize() - 2);
+
+                final CompletableFuture<Integer> callback = new CompletableFuture<>();
+                session.commit(mContext.getMainExecutor(), callback::complete);
+                assertThat(callback.get(TIMEOUT_COMMIT_CALLBACK_SEC, TimeUnit.SECONDS))
+                        .isEqualTo(1);
+            }
+        } finally {
+            blobData.delete();
+        }
+    }
+
+    @Test
+    public void testSessionCommit_incorrectData() throws Exception {
+        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        blobData.prepare();
+        try {
+            final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
+            assertThat(sessionId).isGreaterThan(0L);
+
+            try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
+                blobData.writeToSession(session, 0, blobData.getFileSize());
+                try (OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(
+                        session.openWrite(0, blobData.getFileSize()))) {
+                    out.write("wrong_data".getBytes(StandardCharsets.UTF_8));
+                }
+
+                final CompletableFuture<Integer> callback = new CompletableFuture<>();
+                session.commit(mContext.getMainExecutor(), callback::complete);
+                assertThat(callback.get(TIMEOUT_COMMIT_CALLBACK_SEC, TimeUnit.SECONDS))
+                        .isEqualTo(1);
+            }
+        } finally {
+            blobData.delete();
+        }
+    }
+
+    @Test
+    public void testRecommitBlob() throws Exception {
+        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        blobData.prepare();
+
+        try {
+            commitBlob(blobData);
+            // Verify that blob can be accessed after committing.
+            try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
+                assertThat(pfd).isNotNull();
+                blobData.verifyBlob(pfd);
+            }
+
+            commitBlob(blobData);
+            // Verify that blob can be accessed after re-committing.
+            try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
+                assertThat(pfd).isNotNull();
+                blobData.verifyBlob(pfd);
+            }
+        } finally {
+            blobData.delete();
+        }
+    }
+
+    @Test
+    public void testRecommitBlob_fromMultiplePackages() throws Exception {
+        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        blobData.prepare();
+        final TestServiceConnection connection = bindToHelperService(HELPER_PKG);
+        try {
+            commitBlob(blobData);
+            // Verify that blob can be accessed after committing.
+            try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
+                assertThat(pfd).isNotNull();
+                blobData.verifyBlob(pfd);
+            }
+
+            commitBlobFromPkg(blobData, connection);
+            // Verify that blob can be accessed after re-committing.
+            try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
+                assertThat(pfd).isNotNull();
+                blobData.verifyBlob(pfd);
+            }
+            assertPkgCanAccess(blobData, connection);
+        } finally {
+            blobData.delete();
+            connection.unbind();
+        }
+    }
+
+    @Test
+    public void testSessionCommit_largeBlob() throws Exception {
+        final long fileSizeBytes = Math.min(mBlobStoreManager.getRemainingLeaseQuotaBytes(),
+                150 * 1024L * 1024L);
+        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+                .setFileSize(fileSizeBytes)
+                .build();
+        blobData.prepare();
+        final long commitTimeoutSec = TIMEOUT_COMMIT_CALLBACK_SEC * 2;
+        try {
+            final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
+            assertThat(sessionId).isGreaterThan(0L);
+            try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
+                blobData.writeToSession(session);
+
+                final CompletableFuture<Integer> callback = new CompletableFuture<>();
+                session.commit(mContext.getMainExecutor(), callback::complete);
+                assertThat(callback.get(commitTimeoutSec, TimeUnit.SECONDS))
+                        .isEqualTo(0);
+            }
+
+            // Verify that blob can be accessed after committing.
+            try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
+                assertThat(pfd).isNotNull();
+                blobData.verifyBlob(pfd);
+            }
+        } finally {
+            blobData.delete();
+        }
+    }
+
+    @Test
+    public void testCommitSession_multipleWrites() throws Exception {
+        final int numThreads = 2;
+        final Random random = new Random(0);
+        final ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
+        final CompletableFuture<Throwable>[] completableFutures = new CompletableFuture[numThreads];
+        for (int i = 0; i < numThreads; ++i) {
+            completableFutures[i] = CompletableFuture.supplyAsync(() -> {
+                final int minSizeMb = 30;
+                final long fileSizeBytes = (minSizeMb + random.nextInt(minSizeMb)) * 1024L * 1024L;
+                final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+                        .setFileSize(fileSizeBytes)
+                        .build();
+                try {
+                    blobData.prepare();
+                    commitAndVerifyBlob(blobData);
+                } catch (Throwable t) {
+                    return t;
+                } finally {
+                    blobData.delete();
+                }
+                return null;
+            }, executorService);
+        }
+        final ArrayList<Throwable> invalidResults = new ArrayList<>();
+        for (int i = 0; i < numThreads; ++i) {
+             final Throwable result = completableFutures[i].get();
+             if (result != null) {
+                 invalidResults.add(result);
+             }
+        }
+        assertThat(invalidResults).isEmpty();
+    }
+
+    @Test
+    public void testCommitSession_multipleReadWrites() throws Exception {
+        final int numThreads = 2;
+        final Random random = new Random(0);
+        final ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
+        final CompletableFuture<Throwable>[] completableFutures = new CompletableFuture[numThreads];
+        for (int i = 0; i < numThreads; ++i) {
+            completableFutures[i] = CompletableFuture.supplyAsync(() -> {
+                final int minSizeMb = 30;
+                final long fileSizeBytes = (minSizeMb + random.nextInt(minSizeMb)) * 1024L * 1024L;
+                final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+                        .setFileSize(fileSizeBytes)
+                        .build();
+                try {
+                    blobData.prepare();
+                    final long sessionId = mBlobStoreManager.createSession(
+                            blobData.getBlobHandle());
+                    assertThat(sessionId).isGreaterThan(0L);
+                    try (BlobStoreManager.Session session = mBlobStoreManager.openSession(
+                            sessionId)) {
+                        final long partialFileSizeBytes = minSizeMb * 1024L * 1024L;
+                        blobData.writeToSession(session, 0L, partialFileSizeBytes,
+                                blobData.getFileSize());
+                        blobData.readFromSessionAndVerifyBytes(session, 0L,
+                                (int) partialFileSizeBytes);
+                        blobData.writeToSession(session, partialFileSizeBytes,
+                                blobData.getFileSize() - partialFileSizeBytes,
+                                blobData.getFileSize());
+                        blobData.readFromSessionAndVerifyBytes(session, partialFileSizeBytes,
+                                (int) (blobData.getFileSize() - partialFileSizeBytes));
+
+                        final CompletableFuture<Integer> callback = new CompletableFuture<>();
+                        session.commit(mContext.getMainExecutor(), callback::complete);
+                        assertThat(callback.get(TIMEOUT_COMMIT_CALLBACK_SEC, TimeUnit.SECONDS))
+                                .isEqualTo(0);
+                    }
+
+                    // Verify that blob can be accessed after committing.
+                    try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(
+                            blobData.getBlobHandle())) {
+                        assertThat(pfd).isNotNull();
+                        blobData.verifyBlob(pfd);
+                    }
+                } catch (Throwable t) {
+                    return t;
+                } finally {
+                    blobData.delete();
+                }
+                return null;
+            }, executorService);
+        }
+        final ArrayList<Throwable> invalidResults = new ArrayList<>();
+        for (int i = 0; i < numThreads; ++i) {
+            final Throwable result = completableFutures[i].get();
+            if (result != null) {
+                invalidResults.add(result);
+            }
+        }
+        assertThat(invalidResults).isEmpty();
+    }
+
+    @Test
     public void testOpenBlob() throws Exception {
         final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
         blobData.prepare();
@@ -602,7 +840,7 @@
             try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
                 blobData.writeToSession(session);
 
-                // Verify that trying to access the blob before commit throws
+                // Verify that trying to accessed the blob before commit throws
                 assertThrows(SecurityException.class,
                         () -> mBlobStoreManager.openBlob(blobData.getBlobHandle()));
 
@@ -612,7 +850,7 @@
                         .isEqualTo(0);
             }
 
-            // Verify that blob can be access after committing.
+            // Verify that blob can be accessed after committing.
             try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
                 assertThat(pfd).isNotNull();
 
@@ -697,7 +935,7 @@
     }
 
     @Test
-    public void testAcquireRelease_deleteImmediately() throws Exception {
+    public void testAcquireRelease_deleteAfterDelay() throws Exception {
         final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
         blobData.prepare();
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(1);
@@ -714,6 +952,10 @@
                 releaseLease(mContext, blobData.getBlobHandle());
                 assertNoLeasedBlobs(mBlobStoreManager);
 
+                SystemClock.sleep(waitDurationMs);
+                SystemUtil.runWithShellPermissionIdentity(() ->
+                        mBlobStoreManager.waitForIdle(TIMEOUT_WAIT_FOR_IDLE_MS));
+
                 assertThrows(SecurityException.class, () -> mBlobStoreManager.acquireLease(
                         blobData.getBlobHandle(), R.string.test_desc,
                         blobData.getExpiryTimeMillis()));
@@ -721,7 +963,8 @@
             } finally {
                 blobData.delete();
             }
-        }, Pair.create(KEY_LEASE_ACQUISITION_WAIT_DURATION_MS, String.valueOf(waitDurationMs)));
+        }, Pair.create(KEY_LEASE_ACQUISITION_WAIT_DURATION_MS, String.valueOf(waitDurationMs)),
+                Pair.create(KEY_DELETE_ON_LAST_LEASE_DELAY_MS, String.valueOf(waitDurationMs)));
     }
 
     @Test
@@ -763,7 +1006,7 @@
         final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
         assertThat(sessionId).isGreaterThan(0L);
         try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
-            blobData.writeToSession(session, 0, partialFileSize);
+            blobData.writeToSession(session, 0, partialFileSize, partialFileSize);
         }
 
         StorageStats afterStatsForPkg = storageStatsManager
@@ -780,7 +1023,8 @@
         // Complete writing data.
         final long totalFileSize = blobData.getFileSize();
         try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
-            blobData.writeToSession(session, partialFileSize, totalFileSize - partialFileSize);
+            blobData.writeToSession(session, partialFileSize, totalFileSize - partialFileSize,
+                    totalFileSize);
         }
 
         afterStatsForPkg = storageStatsManager
@@ -796,7 +1040,8 @@
 
         // Commit the session.
         try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
-            blobData.writeToSession(session, partialFileSize, session.getSize() - partialFileSize);
+            blobData.writeToSession(session, partialFileSize,
+                    session.getSize() - partialFileSize, blobData.getFileSize());
             final CompletableFuture<Integer> callback = new CompletableFuture<>();
             session.commit(mContext.getMainExecutor(), callback::complete);
             assertThat(callback.get(TIMEOUT_COMMIT_CALLBACK_SEC, TimeUnit.SECONDS))
@@ -1054,7 +1299,7 @@
         assertThat(sessionId).isGreaterThan(0L);
 
         try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
-            blobData.writeToSession(session, 0, partialFileSize);
+            blobData.writeToSession(session, 0, partialFileSize, blobData.getFileSize());
         }
 
         SystemClock.sleep(waitDurationMs);
@@ -1064,7 +1309,7 @@
 
         try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
             blobData.writeToSession(session, partialFileSize,
-                    blobData.getFileSize() - partialFileSize);
+                    blobData.getFileSize() - partialFileSize, blobData.getFileSize());
             final CompletableFuture<Integer> callback = new CompletableFuture<>();
             session.commit(mContext.getMainExecutor(), callback::complete);
             assertThat(callback.get(TIMEOUT_COMMIT_CALLBACK_SEC, TimeUnit.SECONDS))
@@ -1100,7 +1345,7 @@
             assertThat(sessionId).isGreaterThan(0L);
 
             try (BlobStoreManager.Session session = mBlobStoreManager.openSession(sessionId)) {
-                blobData.writeToSession(session, 0, 100);
+                blobData.writeToSession(session, 0, 100, blobData.getFileSize());
             }
 
             SystemClock.sleep(waitDurationMs);
@@ -1146,6 +1391,16 @@
         }
     }
 
+    private void commitAndVerifyBlob(DummyBlobData blobData) throws Exception {
+        commitBlob(blobData);
+
+        // Verify that blob can be accessed after committing.
+        try (ParcelFileDescriptor pfd = mBlobStoreManager.openBlob(blobData.getBlobHandle())) {
+            assertThat(pfd).isNotNull();
+            blobData.verifyBlob(pfd);
+        }
+    }
+
     private long commitBlob(DummyBlobData blobData) throws Exception {
         return commitBlob(blobData, null);
     }
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java
index 3551205..e75d109 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java
@@ -168,7 +168,8 @@
     private boolean isCarModeSupported() {
         // TVs don't support car mode.
         return !getContext().getPackageManager().hasSystemFeature(
-                PackageManager.FEATURE_LEANBACK_ONLY);
+                PackageManager.FEATURE_LEANBACK_ONLY)
+                && !getContext().getSystemService(UiModeManager.class).isUiModeLocked();
     }
 
     /**
@@ -305,7 +306,6 @@
         if (!isCarModeSupported()) {
             return;
         }
-
         runIdleJobStartsOnlyWhenIdle();
 
         setCarMode(true);
@@ -314,6 +314,9 @@
     }
 
     public void testIdleJobStartsOnlyWhenIdle_screenEndsIdle() throws Exception {
+        if (!isCarModeSupported()) {
+            return;
+        }
         runIdleJobStartsOnlyWhenIdle();
 
         toggleScreenOn(true);
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
index c065b1e..e013454 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
@@ -24,6 +24,7 @@
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import android.app.AppOpsManager;
@@ -102,6 +103,7 @@
     private boolean mInitialAirplaneModeState;
     private String mInitialJobSchedulerConstants;
     private String mInitialDisplayTimeout;
+    private boolean mAutomotiveDevice;
 
     private TestAppInterface mTestAppInterface;
 
@@ -162,6 +164,15 @@
         mInitialDisplayTimeout =
                 Settings.System.getString(mContext.getContentResolver(), SCREEN_OFF_TIMEOUT);
         Settings.System.putString(mContext.getContentResolver(), SCREEN_OFF_TIMEOUT, "300000");
+
+        // In automotive device, always-on screen and endless battery charging are assumed.
+        mAutomotiveDevice =
+                mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
+        if (mAutomotiveDevice) {
+            setScreenState(true);
+            // TODO(b/159176758): make sure that initial power supply is on.
+            BatteryUtils.runDumpsysBatterySetPluggedIn(true);
+        }
     }
 
     @Test
@@ -281,6 +292,7 @@
     @Test
     public void testJobsInRestrictedBucket_ParoleSession() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
 
         // Disable coalescing
         Settings.Global.putString(mContext.getContentResolver(),
@@ -304,6 +316,7 @@
     @Test
     public void testJobsInRestrictedBucket_NoRequiredNetwork() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
 
         // Disable coalescing and the parole session
         Settings.Global.putString(mContext.getContentResolver(),
@@ -339,6 +352,7 @@
     @Test
     public void testJobsInRestrictedBucket_WithRequiredNetwork() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         assumeTrue(mHasWifi);
         ensureSavedWifiNetwork(mWifiManager);
 
@@ -386,6 +400,7 @@
     @Test
     public void testJobsInNeverApp() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
 
         BatteryUtils.runDumpsysBatteryUnplug();
         setTestPackageStandbyBucket(Bucket.NEVER);
@@ -396,6 +411,8 @@
 
     @Test
     public void testUidActiveBypassesStandby() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
+
         BatteryUtils.runDumpsysBatteryUnplug();
         setTestPackageStandbyBucket(Bucket.NEVER);
         tempWhitelistTestApp(6_000);
@@ -407,6 +424,7 @@
 
     @Test
     public void testBatterySaverOff() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         BatteryUtils.runDumpsysBatteryUnplug();
@@ -418,6 +436,7 @@
 
     @Test
     public void testBatterySaverOn() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         BatteryUtils.runDumpsysBatteryUnplug();
@@ -429,6 +448,7 @@
 
     @Test
     public void testUidActiveBypassesBatterySaverOn() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         BatteryUtils.runDumpsysBatteryUnplug();
@@ -441,6 +461,7 @@
 
     @Test
     public void testBatterySaverOnThenUidActive() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         // Enable battery saver, and schedule a job. It shouldn't run.
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextActionTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextActionTest.java
index b2fc2c5..566ccac 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextActionTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextActionTest.java
@@ -259,7 +259,7 @@
 
         ReplacementSpan replacementSpanFromA11y = findSingleSpanInViewWithText(R.string.a_b,
                 ReplacementSpan.class);
-        
+
         assertEquals(contentDescription, replacementSpanFromA11y.getContentDescription());
     }
 
@@ -480,8 +480,8 @@
         final int expectedHeightInPx = textView.getLayoutParams().height;
         final float expectedTextSize = textView.getTextSize();
         final float newTextSize = 20f;
-        final float expectedNewTextSize = (int) (0.5f + TypedValue.applyDimension(
-                TypedValue.COMPLEX_UNIT_SP, newTextSize, displayMetrics));
+        final float expectedNewTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
+                newTextSize, displayMetrics);
         makeTextViewVisibleAndSetText(textView, stringToSet);
 
         final AccessibilityNodeInfo info = sUiAutomation.getRootInActiveWindow()
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
index b37358f..252fbcb 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
@@ -150,11 +150,13 @@
     }
 
     private final AccessibilityEventFilter mDividerPresentFilter = (event) ->
-            (event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED)
+            (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
+                    || event.getEventType() == TYPE_WINDOWS_CHANGED)
                     && isDividerWindowPresent();
 
     private final AccessibilityEventFilter mDividerAbsentFilter = (event) ->
-            (event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED)
+            (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
+                    || event.getEventType() == TYPE_WINDOWS_CHANGED)
                     && !isDividerWindowPresent();
 
     @MediumTest
@@ -700,11 +702,14 @@
     }
 
     private boolean isDividerWindowPresent() {
-        List<AccessibilityWindowInfo> windows = sUiAutomation.getWindows();
+        final List<AccessibilityWindowInfo> windows = sUiAutomation.getWindows();
         final int windowCount = windows.size();
         for (int i = 0; i < windowCount; i++) {
-            AccessibilityWindowInfo window = windows.get(i);
-            if (window.getType() == AccessibilityWindowInfo.TYPE_SPLIT_SCREEN_DIVIDER) {
+            final AccessibilityWindowInfo window = windows.get(i);
+            final AccessibilityNodeInfo rootNode = window.getRoot();
+            if (window.getType() == AccessibilityWindowInfo.TYPE_SPLIT_SCREEN_DIVIDER &&
+                    rootNode != null &&
+                    rootNode.isVisibleToUser()) {
                 return true;
             }
         }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
index 8393012..c64eaa3 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
@@ -51,6 +51,7 @@
 import android.graphics.PointF;
 import android.platform.test.annotations.AppModeFull;
 import android.provider.Settings;
+import android.view.ViewConfiguration;
 import android.widget.TextView;
 
 import androidx.test.InstrumentationRegistry;
@@ -105,7 +106,6 @@
     @Before
     public void setUp() throws Exception {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
-
         PackageManager pm = mInstrumentation.getContext().getPackageManager();
         mHasTouchscreen = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
                 || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH);
@@ -179,7 +179,11 @@
 
     @Test
     public void testPanning() {
-        if (!mHasTouchscreen) return;
+        //The minimum movement to transit to panningState.
+        final float minSwipeDistance = ViewConfiguration.get(
+                mInstrumentation.getContext()).getScaledTouchSlop();
+        final boolean screenBigEnough = mPan > minSwipeDistance;
+        if (!mHasTouchscreen || !screenBigEnough) return;
         assertFalse(isZoomed());
 
         setZoomByTripleTapping(true);
@@ -190,7 +194,8 @@
                 swipe(mTapLocation2, add(mTapLocation2, -mPan, 0)));
 
         waitOn(mZoomLock,
-                () -> (mCurrentZoomCenter.x - oldCenter.x >= mPan / mCurrentScale * 0.9));
+                () -> (mCurrentZoomCenter.x - oldCenter.x
+                        >= (mPan - minSwipeDistance) / mCurrentScale * 0.9));
 
         setZoomByTripleTapping(false);
     }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
index 655b1fe..56d5240 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
@@ -17,20 +17,14 @@
 package android.accessibilityservice.cts;
 
 import static android.accessibilityservice.cts.utils.AsyncUtils.await;
-import static android.accessibilityservice.cts.utils.GestureUtils.IS_ACTION_DOWN;
-import static android.accessibilityservice.cts.utils.GestureUtils.IS_ACTION_UP;
 import static android.accessibilityservice.cts.utils.GestureUtils.add;
-import static android.accessibilityservice.cts.utils.GestureUtils.ceil;
 import static android.accessibilityservice.cts.utils.GestureUtils.click;
-import static android.accessibilityservice.cts.utils.GestureUtils.diff;
 import static android.accessibilityservice.cts.utils.GestureUtils.dispatchGesture;
 import static android.accessibilityservice.cts.utils.GestureUtils.doubleTap;
 import static android.accessibilityservice.cts.utils.GestureUtils.doubleTapAndHold;
-import static android.accessibilityservice.cts.utils.GestureUtils.isRawAtPoint;
 import static android.accessibilityservice.cts.utils.GestureUtils.multiTap;
 import static android.accessibilityservice.cts.utils.GestureUtils.secondFingerMultiTap;
 import static android.accessibilityservice.cts.utils.GestureUtils.swipe;
-import static android.accessibilityservice.cts.utils.GestureUtils.times;
 import static android.view.MotionEvent.ACTION_DOWN;
 import static android.view.MotionEvent.ACTION_HOVER_ENTER;
 import static android.view.MotionEvent.ACTION_HOVER_EXIT;
@@ -49,9 +43,6 @@
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_LONG_CLICKED;
 
-import static org.hamcrest.CoreMatchers.both;
-import static org.hamcrest.MatcherAssert.assertThat;
-
 import android.accessibility.cts.common.AccessibilityDumpOnFailureRule;
 import android.accessibility.cts.common.InstrumentedAccessibilityServiceTestRule;
 import android.accessibilityservice.GestureDescription;
@@ -71,7 +62,6 @@
 import android.platform.test.annotations.AppModeFull;
 import android.util.DisplayMetrics;
 import android.view.Display;
-import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewConfiguration;
 import android.view.WindowManager;
@@ -87,8 +77,6 @@
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 
-import java.util.List;
-
 /**
  * A set of tests for testing touch exploration. Each test dispatches a gesture and checks for the
  * appropriate hover and/or touch events followed by the appropriate accessibility events. Some
@@ -99,12 +87,12 @@
 public class TouchExplorerTest {
     // Constants
     private static final float GESTURE_LENGTH_INCHES = 1.0f;
-    private static final int SWIPE_TIME_MILLIS = 400;
     private TouchExplorationStubAccessibilityService mService;
     private Instrumentation mInstrumentation;
     private UiAutomation mUiAutomation;
     private boolean mHasTouchscreen;
     private boolean mScreenBigEnough;
+    private long mSwipeTimeMillis;
     private EventCapturingHoverListener mHoverListener = new EventCapturingHoverListener(false);
     private EventCapturingTouchListener mTouchListener = new EventCapturingTouchListener(false);
     private EventCapturingClickListener mClickListener = new EventCapturingClickListener();
@@ -164,6 +152,7 @@
                     mCenter = new Point(viewLocation[0] + midX, viewLocation[1] + midY);
                     mTapLocation = new PointF(mCenter);
                     mSwipeDistance = (viewLocation[0] + mView.getWidth()) / 4;
+                    mSwipeTimeMillis = (long) mSwipeDistance * 4;
                     mView.setOnClickListener(mClickListener);
                     mView.setOnLongClickListener(mLongClickListener);
                 });
@@ -174,7 +163,7 @@
     @AppModeFull
     public void testSlowSwipe_initiatesTouchExploration() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
-        dispatch(swipe(mTapLocation, add(mTapLocation, mSwipeDistance, 0), SWIPE_TIME_MILLIS));
+        dispatch(swipe(mTapLocation, add(mTapLocation, mSwipeDistance, 0), mSwipeTimeMillis));
         mHoverListener.assertPropagated(ACTION_HOVER_ENTER, ACTION_HOVER_MOVE, ACTION_HOVER_EXIT);
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
@@ -218,29 +207,9 @@
         final PointF finger2Start = add(dragStart, -twoFingerOffset, 0);
         final PointF finger2End = add(finger2Start, 0, mSwipeDistance);
         dispatch(
-                swipe(finger1Start, finger1End, SWIPE_TIME_MILLIS),
-                swipe(finger2Start, finger2End, SWIPE_TIME_MILLIS));
-        List<MotionEvent> twoFingerPoints = mTouchListener.getRawEvents();
-
-        // Check the drag events performed by a two finger drag. The moving locations would be
-        // adjusted to the middle of two fingers.
-        final int numEvents = twoFingerPoints.size();
-        final int upEventIndex = numEvents - 1;
-        final float stepDuration =
-                (float)
-                        (twoFingerPoints.get(1).getEventTime()
-                                - twoFingerPoints.get(0).getEventTime());
-        final float gestureDuration =
-                (float)
-                        (twoFingerPoints.get(upEventIndex).getEventTime()
-                                - twoFingerPoints.get(0).getEventTime());
-        final float intervalFraction =
-                stepDuration * (mSwipeDistance / gestureDuration) / gestureDuration;
-        PointF downPoint = add(dragStart, ceil(times(intervalFraction, diff(dragEnd, dragStart))));
-        assertThat(twoFingerPoints.get(0), both(IS_ACTION_DOWN).and(isRawAtPoint(downPoint, 1.0f)));
-        assertThat(
-                twoFingerPoints.get(upEventIndex),
-                both(IS_ACTION_UP).and(isRawAtPoint(finger2End, 1.0f)));
+                swipe(finger1Start, finger1End, mSwipeTimeMillis),
+                swipe(finger2Start, finger2End, mSwipeTimeMillis));
+        mTouchListener.assertPropagated(ACTION_DOWN, ACTION_MOVE, ACTION_UP);
     }
 
     /** Test a basic single tap which should initiate touch exploration. */
@@ -311,7 +280,7 @@
      */
     @Test
     @AppModeFull
-    public void testDoubleTapNoAccessibilityFocus_doesNotPerformClick() {
+    public void testDoubleTapNoFocus_doesNotPerformClick() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(doubleTap(mTapLocation));
         mHoverListener.assertNonePropagated();
@@ -349,7 +318,7 @@
      */
     @Test
     @AppModeFull
-    public void testDoubleTapAndHoldNoAccessibilityFocus_doesNotPerformLongClick() {
+    public void testDoubleTapAndHoldNoFocus_doesNotPerformLongClick() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(doubleTap(mTapLocation));
         mHoverListener.assertNonePropagated();
@@ -389,6 +358,63 @@
     }
 
     /**
+     * Test the case where we double tap and no item has accessibility focus, so TouchExplorer sends
+     * touch events to the last touch-explored coordinates to simulate a click.
+     */
+    @Test
+    @AppModeFull
+    public void testDoubleTapNoAccessibilityFocus_sendsTouchEvents() {
+        if (!mHasTouchscreen || !mScreenBigEnough) return;
+        // Do a single tap so there is a valid last touch-explored location.
+        dispatch(click(mTapLocation));
+        mHoverListener.assertPropagated(ACTION_HOVER_ENTER, ACTION_HOVER_EXIT);
+        // We don't really care about these events but we need to make sure all the events we want
+        // to clear have arrived before we clear them.
+        mService.assertPropagated(
+                TYPE_TOUCH_INTERACTION_START,
+                TYPE_TOUCH_EXPLORATION_GESTURE_START,
+                TYPE_TOUCH_EXPLORATION_GESTURE_END,
+                TYPE_TOUCH_INTERACTION_END);
+        mService.clearEvents();
+        dispatch(doubleTap(mTapLocation));
+        mHoverListener.assertNonePropagated();
+        // The click gets delivered as a series of touch events.
+        mTouchListener.assertPropagated(ACTION_DOWN, ACTION_UP);
+        mService.assertPropagated(
+                TYPE_TOUCH_INTERACTION_START, TYPE_TOUCH_INTERACTION_END, TYPE_VIEW_CLICKED);
+        mClickListener.assertClicked(mView);
+    }
+
+    /**
+     * Test the case where we double tap and hold and no item has accessibility focus, so
+     * TouchExplorer sends touch events to the last touch-explored coordinates to simulate a long
+     * click.
+     */
+    @Test
+    @AppModeFull
+    public void testDoubleTapAndHoldNoAccessibilityFocus_sendsTouchEvents() {
+        if (!mHasTouchscreen || !mScreenBigEnough) return;
+        // Do a single tap so there is a valid last touch-explored location.
+        dispatch(click(mTapLocation));
+        mHoverListener.assertPropagated(ACTION_HOVER_ENTER, ACTION_HOVER_EXIT);
+        // We don't really care about these events but we need to make sure all the events we want
+        // to clear have arrived before we clear them.
+        mService.assertPropagated(
+                TYPE_TOUCH_INTERACTION_START,
+                TYPE_TOUCH_EXPLORATION_GESTURE_START,
+                TYPE_TOUCH_EXPLORATION_GESTURE_END,
+                TYPE_TOUCH_INTERACTION_END);
+        mService.clearEvents();
+        dispatch(doubleTapAndHold(mTapLocation));
+        mHoverListener.assertNonePropagated();
+        // The click gets delivered as a series of touch events.
+        mTouchListener.assertPropagated(ACTION_DOWN, ACTION_UP);
+        mService.assertPropagated(
+                TYPE_TOUCH_INTERACTION_START, TYPE_VIEW_LONG_CLICKED, TYPE_TOUCH_INTERACTION_END);
+        mLongClickListener.assertLongClicked(mView);
+    }
+
+    /**
      * Test the case where we want to double tap using a second finger without triggering touch
      * exploration.
      */
@@ -433,9 +459,9 @@
         PointF finger2End = add(mTapLocation, 0, mSwipeDistance);
         PointF finger3Start = add(mTapLocation, mSwipeDistance, 0);
         PointF finger3End = add(mTapLocation, mSwipeDistance, mSwipeDistance);
-        StrokeDescription swipe1 = swipe(finger1Start, finger1End, SWIPE_TIME_MILLIS);
-        StrokeDescription swipe2 = swipe(finger2Start, finger2End, SWIPE_TIME_MILLIS);
-        StrokeDescription swipe3 = swipe(finger3Start, finger3End, SWIPE_TIME_MILLIS);
+        StrokeDescription swipe1 = swipe(finger1Start, finger1End, mSwipeTimeMillis);
+        StrokeDescription swipe2 = swipe(finger2Start, finger2End, mSwipeTimeMillis);
+        StrokeDescription swipe3 = swipe(finger3Start, finger3End, mSwipeTimeMillis);
         dispatch(swipe1, swipe2, swipe3);
         mHoverListener.assertNonePropagated();
         mTouchListener.assertPropagated(
@@ -460,10 +486,10 @@
         // Move two fingers towards eacher slowly.
         PointF finger1Start = add(mTapLocation, -mSwipeDistance, 0);
         PointF finger1End = add(mTapLocation, -10, 0);
-        StrokeDescription swipe1 = swipe(finger1Start, finger1End, SWIPE_TIME_MILLIS);
+        StrokeDescription swipe1 = swipe(finger1Start, finger1End, mSwipeTimeMillis);
         PointF finger2Start = add(mTapLocation, mSwipeDistance, 0);
         PointF finger2End = add(mTapLocation, 10, 0);
-        StrokeDescription swipe2 = swipe(finger2Start, finger2End, SWIPE_TIME_MILLIS);
+        StrokeDescription swipe2 = swipe(finger2Start, finger2End, mSwipeTimeMillis);
         dispatch(swipe1, swipe2);
         mHoverListener.assertNonePropagated();
         mTouchListener.assertPropagated(
diff --git a/tests/app/AppExitTest/AndroidManifest.xml b/tests/app/AppExitTest/AndroidManifest.xml
index 4606ca5..64a1ab8 100644
--- a/tests/app/AppExitTest/AndroidManifest.xml
+++ b/tests/app/AppExitTest/AndroidManifest.xml
@@ -24,6 +24,10 @@
 
     <application android:usesCleartextTraffic="true">
         <uses-library android:name="android.test.runner" />
+        <service android:name="android.app.cts.MemoryConsumerService"
+                android:exported="true"
+                android:isolatedProcess="true">
+        </service>
     </application>
 
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
diff --git a/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java b/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
index bd9e5af..cbded8b 100644
--- a/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
+++ b/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
@@ -30,6 +30,7 @@
 import android.externalservice.common.RunningServiceInfo;
 import android.externalservice.common.ServiceMessages;
 import android.os.AsyncTask;
+import android.os.Binder;
 import android.os.Bundle;
 import android.os.DropBoxManager;
 import android.os.Handler;
@@ -44,12 +45,12 @@
 import android.os.UserManager;
 import android.provider.Settings;
 import android.server.wm.settings.SettingsSession;
-import android.system.Os;
 import android.system.OsConstants;
 import android.test.InstrumentationTestCase;
 import android.text.TextUtils;
 import android.util.DebugUtils;
 import android.util.Log;
+import android.util.Pair;
 
 import com.android.compatibility.common.util.AmMonitor;
 import com.android.compatibility.common.util.ShellIdentityUtils;
@@ -58,9 +59,7 @@
 import com.android.internal.util.MemInfoReader;
 
 import java.io.BufferedInputStream;
-import java.io.FileDescriptor;
 import java.io.IOException;
-import java.nio.DirectByteBuffer;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
@@ -131,6 +130,8 @@
     private UserHandle mOtherUserHandle;
     private DropBoxManager.Entry mAnrEntry;
     private SettingsSession<String> mDataAnrSettings;
+    private SettingsSession<String> mHiddenApiSettings;
+    private int mProcSeqNum;
 
     @Override
     protected void setUp() throws Exception {
@@ -154,6 +155,11 @@
                         Settings.Global.DROPBOX_TAG_PREFIX + "data_app_anr"),
                 Settings.Global::getString, Settings.Global::putString);
         mDataAnrSettings.set("enabled");
+        mHiddenApiSettings = new SettingsSession<>(
+                Settings.Global.getUriFor(
+                        Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
+                Settings.Global::getString, Settings.Global::putString);
+        mHiddenApiSettings.set("*");
     }
 
     private void handleMessagePid(Message msg) {
@@ -217,6 +223,9 @@
         if (mDataAnrSettings != null) {
             mDataAnrSettings.close();
         }
+        if (mHiddenApiSettings != null) {
+            mHiddenApiSettings.close();
+        }
     }
 
     private int createUser(String name, boolean guest) throws Exception {
@@ -391,47 +400,37 @@
                 ApplicationExitInfo.REASON_EXIT_SELF, EXIT_CODE, null, now, now2);
     }
 
-    private List<ApplicationExitInfo> fillUpMemoryAndCheck(ArrayList<Long> addresses)
-            throws Exception {
-        List<ApplicationExitInfo> list = null;
-        // Get the meminfo firstly
-        MemInfoReader reader = new MemInfoReader();
-        reader.readMemInfo();
+    private List<ServiceConnection> fillUpMemoryAndCheck(
+            final MemoryConsumerService.TestFuncInterface testFunc,
+            final List<ApplicationExitInfo> list) throws Exception {
+        final String procNamePrefix = "memconsumer_";
+        final ArrayList<ServiceConnection> memConsumers = new ArrayList<>();
+        Pair<IBinder, ServiceConnection> p = MemoryConsumerService.bindToService(
+                mContext, testFunc, procNamePrefix + mProcSeqNum++);
+        IBinder consumer = p.first;
+        memConsumers.add(p.second);
 
-        long totalMb = (reader.getFreeSizeKb() + reader.getCachedSizeKb()) >> 10;
-        final int pageSize = 4096;
-        final int oneMb = 1024 * 1024;
+        while (list.size() == 0) {
+            // Get the meminfo firstly
+            MemInfoReader reader = new MemInfoReader();
+            reader.readMemInfo();
 
-        // Create an empty fd -1
-        FileDescriptor fd = new FileDescriptor();
-
-        // Okay now start a loop to allocate 1MB each time and check if our process is gone.
-        for (long i = 0; i < totalMb; i++) {
-            long addr = Os.mmap(0, oneMb, OsConstants.PROT_WRITE,
-                    OsConstants.MAP_PRIVATE | OsConstants.MAP_ANONYMOUS, fd, 0);
-            if (addr == 0) {
-                break;
+            long totalMb = (reader.getFreeSizeKb() + reader.getCachedSizeKb()) >> 10;
+            if (!MemoryConsumerService.runOnce(consumer, totalMb) && list.size() == 0) {
+                // Need to create a new consumer (the present one might be running out of space)
+                p = MemoryConsumerService.bindToService(mContext, testFunc,
+                        procNamePrefix + mProcSeqNum++);
+                consumer = p.first;
+                memConsumers.add(p.second);
             }
-            addresses.add(addr);
-
-            // We don't have direct access to Memory.pokeByte() though
-            DirectByteBuffer buf = new DirectByteBuffer(oneMb, addr, fd, null, false);
-
-            // Dirt the buffer
-            for (int j = 0; j < oneMb; j += pageSize) {
-                buf.put(j, (byte) 0xf);
-            }
-
-            // Check if we could get the report
-            list = ShellIdentityUtils.invokeMethodWithShellPermissions(
-                    STUB_PACKAGE_NAME, mStubPackagePid, 1,
-                    mActivityManager::getHistoricalProcessExitReasons,
-                    android.Manifest.permission.DUMP);
-            if (list != null && list.size() == 1) {
+            // make sure we have cached process killed
+            String output = executeShellCmd("dumpsys activity lru");
+            if (output == null && output.indexOf(" cch+") == -1) {
                 break;
             }
         }
-        return list;
+
+        return memConsumers;
     }
 
     public void testLmkdKill() throws Exception {
@@ -444,23 +443,32 @@
         // Start a process and do nothing
         startService(ACTION_FINISH, STUB_SERVICE_NAME, false, false);
 
-        final int oneMb = 1024 * 1024;
-        ArrayList<Long> addresses = new ArrayList<Long>();
-        List<ApplicationExitInfo> list = fillUpMemoryAndCheck(addresses);
+        final ArrayList<IBinder> memConsumers = new ArrayList<>();
+        List<ApplicationExitInfo> list = new ArrayList<>();
+        final MemoryConsumerService.TestFuncInterface testFunc =
+                new MemoryConsumerService.TestFuncInterface(() -> {
+                    final long token = Binder.clearCallingIdentity();
+                    try {
+                        List<ApplicationExitInfo> result =
+                                ShellIdentityUtils.invokeMethodWithShellPermissions(
+                                        STUB_PACKAGE_NAME, mStubPackagePid, 1,
+                                        mActivityManager::getHistoricalProcessExitReasons,
+                                        android.Manifest.permission.DUMP);
+                        if (result != null && result.size() == 1) {
+                            list.add(result.get(0));
+                            return true;
+                        }
+                    } finally {
+                        Binder.restoreCallingIdentity(token);
+                    }
+                    return false;
+                });
 
-        while (list == null || list.size() == 0) {
-            // make sure we have cached process killed
-            String output = executeShellCmd("dumpsys activity lru");
-            if (output == null && output.indexOf(" cch+") == -1) {
-                break;
-            }
-            // try again since the system might have reclaimed some ram
-            list = fillUpMemoryAndCheck(addresses);
-        }
+        List<ServiceConnection> services = fillUpMemoryAndCheck(testFunc, list);
 
-        // Free all the buffers firstly
-        for (int i = addresses.size() - 1; i >= 0; i--) {
-            Os.munmap(addresses.get(i), oneMb);
+        // Unbind all the service connections firstly
+        for (int i = services.size() - 1; i >= 0; i--) {
+            mContext.unbindService(services.get(i));
         }
 
         long now2 = System.currentTimeMillis();
diff --git a/tests/app/AppExitTest/src/android/app/cts/MemoryConsumerService.java b/tests/app/AppExitTest/src/android/app/cts/MemoryConsumerService.java
new file mode 100644
index 0000000..cca0fac
--- /dev/null
+++ b/tests/app/AppExitTest/src/android/app/cts/MemoryConsumerService.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.cts;
+
+import android.app.Service;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.os.AsyncTask;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Parcel;
+import android.os.RemoteException;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+import android.util.Log;
+import android.util.Pair;
+
+import java.io.FileDescriptor;
+import java.nio.DirectByteBuffer;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BooleanSupplier;
+
+public class MemoryConsumerService extends Service {
+    private static final String TAG = MemoryConsumerService.class.getSimpleName();
+
+    private static final int ACTION_RUN_ONCE = IBinder.FIRST_CALL_TRANSACTION;
+    private static final String EXTRA_BUNDLE = "bundle";
+    private static final String EXTRA_TEST_FUNC = "test_func";
+
+    private IBinder mTestFunc;
+
+    private IBinder mBinder = new Binder() {
+        @Override
+        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
+                throws RemoteException {
+            switch (code) {
+                case ACTION_RUN_ONCE:
+                    reply.writeBoolean(fillUpMemoryAndCheck(data.readLong(), mTestFunc));
+                    return true;
+                default:
+                    return false;
+            }
+        }
+    };
+
+    static class TestFuncInterface extends Binder {
+        static final int ACTION_TEST = IBinder.FIRST_CALL_TRANSACTION;
+
+        private final BooleanSupplier mTestFunc;
+
+        TestFuncInterface(final BooleanSupplier testFunc) {
+            mTestFunc = testFunc;
+        }
+
+        @Override
+        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
+                throws RemoteException {
+            switch (code) {
+                case ACTION_TEST:
+                    reply.writeBoolean(mTestFunc.getAsBoolean());
+                    return true;
+                default:
+                    return false;
+            }
+        }
+    }
+
+    private boolean fillUpMemoryAndCheck(final long totalMb, final IBinder testFunc) {
+        final int pageSize = 4096;
+        final int oneMb = 1024 * 1024;
+
+        // Create an empty fd -1
+        FileDescriptor fd = new FileDescriptor();
+
+        // Okay now start a loop to allocate 1MB each time and check if our process is gone.
+        for (long i = 0; i < totalMb; i++) {
+            long addr = 0L;
+            try {
+                addr = Os.mmap(0, oneMb, OsConstants.PROT_WRITE,
+                        OsConstants.MAP_PRIVATE | OsConstants.MAP_ANONYMOUS, fd, 0);
+            } catch (ErrnoException e) {
+                Log.d(TAG, "mmap returns " + e.errno);
+                if (e.errno == OsConstants.ENOMEM) {
+                    // Running out of address space?
+                    return false;
+                }
+            }
+            if (addr == 0) {
+                return false;
+            }
+
+            // We don't have direct access to Memory.pokeByte() though
+            DirectByteBuffer buf = new DirectByteBuffer(oneMb, addr, fd, null, false);
+
+            // Dirt the buffer
+            for (int j = 0; j < oneMb; j += pageSize) {
+                buf.put(j, (byte) 0xf);
+            }
+
+            // Test to see if we could stop
+            Parcel data = Parcel.obtain();
+            Parcel reply = Parcel.obtain();
+            try {
+                testFunc.transact(TestFuncInterface.ACTION_TEST, data, reply, 0);
+                if (reply.readBoolean()) {
+                    break;
+                }
+            } catch (RemoteException e) {
+                // Ignore
+            } finally {
+                data.recycle();
+                reply.recycle();
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        final Bundle bundle = intent.getBundleExtra(EXTRA_BUNDLE);
+        mTestFunc = bundle.getBinder(EXTRA_TEST_FUNC);
+        return mBinder;
+    }
+
+    static Pair<IBinder, ServiceConnection> bindToService(final Context context,
+            final TestFuncInterface testFunc, String instanceName) throws Exception {
+        final Intent intent = new Intent();
+        intent.setClass(context, MemoryConsumerService.class);
+        final Bundle bundle = new Bundle();
+        bundle.putBinder(EXTRA_TEST_FUNC, testFunc);
+        intent.putExtra(EXTRA_BUNDLE, bundle);
+        final String keyIBinder = "ibinder";
+        final Bundle holder = new Bundle();
+        final CountDownLatch latch = new CountDownLatch(1);
+        final ServiceConnection conn = new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                holder.putBinder(keyIBinder, service);
+                latch.countDown();
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+            }
+        };
+        context.bindIsolatedService(intent, Context.BIND_AUTO_CREATE,
+                instanceName, AsyncTask.THREAD_POOL_EXECUTOR, conn);
+        latch.await(10_000, TimeUnit.MILLISECONDS);
+        return new Pair<>(holder.getBinder(keyIBinder), conn);
+    }
+
+    static boolean runOnce(final IBinder binder, final long totalMb) {
+        final Parcel data = Parcel.obtain();
+        final Parcel reply = Parcel.obtain();
+
+        try {
+            data.writeLong(totalMb);
+            binder.transact(ACTION_RUN_ONCE, data, reply, 0);
+            return reply.readBoolean();
+        } catch (RemoteException e) {
+            return false;
+        } finally {
+            data.recycle();
+            reply.recycle();
+        }
+    }
+}
diff --git a/tests/app/src/android/app/cts/ActionBarTest.java b/tests/app/src/android/app/cts/ActionBarTest.java
index ee28c27..f3d2846 100644
--- a/tests/app/src/android/app/cts/ActionBarTest.java
+++ b/tests/app/src/android/app/cts/ActionBarTest.java
@@ -124,6 +124,21 @@
         assertFalse(menuIsVisible[0]);
     }
 
+    @UiThreadTest
+    public void testElevation() {
+        if (mBar == null) {
+            return;
+        }
+        final float oldElevation = mBar.getElevation();
+        try {
+            final float newElevation = 42;
+            mBar.setElevation(newElevation);
+            assertEquals(newElevation, mBar.getElevation());
+        } finally {
+            mBar.setElevation(oldElevation);
+        }
+    }
+
     private Tab createTab(String name) {
         return mBar.newTab().setText("Tab 1").setTabListener(new TestTabListener());
     }
diff --git a/tests/app/src/android/app/cts/UiModeManagerTest.java b/tests/app/src/android/app/cts/UiModeManagerTest.java
index 7174f36..e877350 100644
--- a/tests/app/src/android/app/cts/UiModeManagerTest.java
+++ b/tests/app/src/android/app/cts/UiModeManagerTest.java
@@ -124,6 +124,10 @@
     }
 
     public void testNightModeAutoNotPersistedCarMode() {
+        if (mUiModeManager.isNightModeLocked()) {
+            return;
+        }
+
         // Reset the mode to no if it is set to another value
         setNightMode(UiModeManager.MODE_NIGHT_NO);
         mUiModeManager.enableCarMode(0);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/DatasetFilteringTest.java b/tests/autofillservice/src/android/autofillservice/cts/DatasetFilteringTest.java
index 55253db..6893090 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/DatasetFilteringTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/DatasetFilteringTest.java
@@ -38,9 +38,9 @@
 import com.android.cts.mockime.ImeEventStream;
 import com.android.cts.mockime.MockImeSession;
 
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
 import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.rules.TestRule;
 
 import java.util.regex.Pattern;
 
@@ -53,15 +53,12 @@
         super(inlineUiBot);
     }
 
-    @BeforeClass
-    public static void setMaxDatasets() throws Exception {
-        Helper.setMaxVisibleDatasets(4);
+    @Override
+    protected TestRule getMainTestRule() {
+        return RuleChain.outerRule(new MaxVisibleDatasetsRule(4))
+                        .around(super.getMainTestRule());
     }
 
-    @AfterClass
-    public static void restoreMaxDatasets() throws Exception {
-        Helper.setMaxVisibleDatasets(0);
-    }
 
     private void changeUsername(CharSequence username) {
         mActivity.onUsername((v) -> v.setText(username));
@@ -111,10 +108,7 @@
         // No dataset start with 'aaa'
         final MyAutofillCallback callback = mActivity.registerCallback();
         changeUsername("aaa");
-        // TODO(b/157762527): Fix this for the inline case.
-        if (!isInlineMode()) {
-            callback.assertUiHiddenEvent(mActivity.getUsername());
-        }
+        callback.assertUiHiddenEvent(mActivity.getUsername());
         mUiBot.assertNoDatasets();
 
         // Delete some text to bring back 2 datasets
@@ -179,10 +173,7 @@
         sendKeyEvent("KEYCODE_A");
         sendKeyEvent("KEYCODE_A");
         sendKeyEvent("KEYCODE_A");
-        // TODO(b/157762527): Fix this for the inline case.
-        if (!isInlineMode()) {
-            callback.assertUiHiddenEvent(mActivity.getUsername());
-        }
+        callback.assertUiHiddenEvent(mActivity.getUsername());
         mUiBot.assertNoDatasets();
     }
 
@@ -253,10 +244,7 @@
         final MyAutofillCallback callback = mActivity.registerCallback();
         final ImeCommand cmd5 = mockImeSession.callCommitText("aaa", 1);
         expectCommand(stream, cmd5, MOCK_IME_TIMEOUT_MS);
-        // TODO(b/157762527): Fix this for the inline case.
-        if (!isInlineMode()) {
-            callback.assertUiHiddenEvent(mActivity.getUsername());
-        }
+        callback.assertUiHiddenEvent(mActivity.getUsername());
         mUiBot.assertNoDatasets();
     }
 
@@ -413,10 +401,7 @@
         // No dataset start with 'aaa'
         final MyAutofillCallback callback = mActivity.registerCallback();
         changeUsername("aaa");
-        // TODO(b/157762527): Fix this for the inline case.
-        if (!isInlineMode()) {
-            callback.assertUiHiddenEvent(mActivity.getUsername());
-        }
+        callback.assertUiHiddenEvent(mActivity.getUsername());
         mUiBot.assertNoDatasets();
     }
 
@@ -483,10 +468,7 @@
         // No dataset start with 'aaa'
         final MyAutofillCallback callback = mActivity.registerCallback();
         changeUsername("aaa");
-        // TODO(b/157762527): Fix this for the inline case.
-        if (!isInlineMode()) {
-            callback.assertUiHiddenEvent(mActivity.getUsername());
-        }
+        callback.assertUiHiddenEvent(mActivity.getUsername());
         mUiBot.assertNoDatasets();
     }
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityCommonTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityCommonTestCase.java
index 1ef42c5..1bad60a 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityCommonTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityCommonTestCase.java
@@ -117,6 +117,10 @@
         // Set service.
         enableService();
 
+        final MyAutofillCallback callback = mActivity.registerCallback();
+        final View username = mActivity.getUsername();
+        final View password = mActivity.getPassword();
+
         String[] expectedDatasets = new String[numDatasets];
         final CannedFillResponse.Builder builder = new CannedFillResponse.Builder();
         for (int i = 0; i < numDatasets; i++) {
@@ -136,11 +140,13 @@
         mUiBot.waitForIdle();
 
         mUiBot.assertDatasets(expectedDatasets);
+        callback.assertUiShownEvent(username);
 
         mUiBot.selectDataset(expectedDatasets[selectedDatasetIndex]);
 
         // Check the results.
         mActivity.assertAutoFilled();
+        callback.assertUiHiddenEvent(username);
 
         // Make sure input was sanitized.
         final InstrumentedAutoFillService.FillRequest request = sReplier.getNextFillRequest();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MaxVisibleDatasetsRule.java b/tests/autofillservice/src/android/autofillservice/cts/MaxVisibleDatasetsRule.java
new file mode 100644
index 0000000..8a397d9
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/MaxVisibleDatasetsRule.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.autofillservice.cts;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+/**
+ * Custom JUnit4 rule that improves autofill-related environment by:
+ *
+ * <ol>
+ *   <li>Setting max_visible_datasets before and after test.
+ * </ol>
+ */
+public final class MaxVisibleDatasetsRule implements TestRule {
+
+    private static final String TAG = MaxVisibleDatasetsRule.class.getSimpleName();
+
+    private final int mMaxNumber;
+
+    /**
+     * Creates a MaxVisibleDatasetsRule with given datasets values.
+     *
+     * @param maxNumber The desired max_visible_datasets value for a test,
+     * after the test it will be replaced by the original value
+     */
+    public MaxVisibleDatasetsRule(int maxNumber) {
+        mMaxNumber = maxNumber;
+    }
+
+
+    @Override
+    public Statement apply(Statement base, Description description) {
+        return new Statement() {
+
+            @Override
+            public void evaluate() throws Throwable {
+                final int original = Helper.getMaxVisibleDatasets();
+                Helper.setMaxVisibleDatasets(mMaxNumber);
+                try {
+                    base.evaluate();
+                } finally {
+                    Helper.setMaxVisibleDatasets(original);
+                }
+            }
+        };
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java b/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java
index 22ba3b9..54f391b 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java
@@ -26,6 +26,8 @@
 import android.provider.Settings;
 import android.support.test.uiautomator.UiObject2;
 
+import com.android.compatibility.common.util.FeatureUtil;
+
 import org.junit.After;
 import org.junit.Test;
 
@@ -51,8 +53,12 @@
 
     @After
     public void killSettings() {
-        // Make sure there's no Settings activity left , as it could fail future tests.
-        runShellCommand("am force-stop com.android.settings");
+        // Make sure there's no Settings activity left, as it could fail future tests.
+        if (FeatureUtil.isAutomotive()) {
+            runShellCommand("am force-stop com.android.car.settings");
+        } else {
+            runShellCommand("am force-stop com.android.settings");
+        }
     }
 
     @Test
@@ -65,6 +71,7 @@
         // Asserts services are shown.
         mUiBot.assertShownByText(InstrumentedAutoFillService.sServiceLabel);
         mUiBot.assertShownByText(InstrumentedAutoFillServiceCompatMode.sServiceLabel);
+        mUiBot.scrollToTextObject(NoOpAutofillService.SERVICE_LABEL);
         mUiBot.assertShownByText(NoOpAutofillService.SERVICE_LABEL);
         mUiBot.assertNotShowingForSure(BadAutofillService.SERVICE_LABEL);
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
index f67bd5c..fb878d3 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
@@ -1812,7 +1812,7 @@
 
         // Tapping URLSpan.
         final URLSpan span = mUiBot.findFirstUrlSpanWithText("Here is URLSpan");
-        span.onClick(/* unused= */ null);
+        mActivity.syncRunOnUiThread(() -> span.onClick(/* unused= */ null));
         // Waits for the save UI hided
         mUiBot.waitForIdle();
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
index 8babc6c..88173d3 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
@@ -55,6 +55,9 @@
 import android.support.test.uiautomator.SearchCondition;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject2;
+import android.support.test.uiautomator.UiObjectNotFoundException;
+import android.support.test.uiautomator.UiScrollable;
+import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
 import android.text.Html;
 import android.text.Spanned;
@@ -1246,4 +1249,15 @@
                 .getSpans(0, accessibilityTextWithSpan.length(), URLSpan.class);
         return spans[0];
     }
+
+    public boolean scrollToTextObject(String text) {
+        UiScrollable scroller = new UiScrollable(new UiSelector().scrollable(true));
+        try {
+            // Swipe far away from the edges to avoid triggering navigation gestures
+            scroller.setSwipeDeadZonePercentage(0.25);
+            return scroller.scrollTextIntoView(text);
+        } catch (UiObjectNotFoundException e) {
+            return false;
+        }
+    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineAugmentedLoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineAugmentedLoginActivityTest.java
index 75c1042..d645834 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineAugmentedLoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineAugmentedLoginActivityTest.java
@@ -29,6 +29,7 @@
 
 import android.autofillservice.cts.AutofillActivityTestRule;
 import android.autofillservice.cts.Helper;
+import android.autofillservice.cts.MyAutofillCallback;
 import android.autofillservice.cts.augmented.AugmentedAutofillAutoActivityLaunchTestCase;
 import android.autofillservice.cts.augmented.AugmentedLoginActivity;
 import android.autofillservice.cts.augmented.CannedAugmentedFillResponse;
@@ -175,6 +176,8 @@
     }
 
     private void testBasicLoginAutofill() throws Exception {
+
+        final MyAutofillCallback callback = mActivity.registerCallback();
         // Set expectations
         final EditText username = mActivity.getUsername();
         final EditText password = mActivity.getPassword();
@@ -202,6 +205,7 @@
 
         // Confirm two suggestion
         mUiBot.assertDatasets("dude");
+        callback.assertUiShownEvent(username);
 
         mActivity.expectAutoFill("dude", "sweet");
 
@@ -210,6 +214,8 @@
         mUiBot.waitForIdle();
 
         mActivity.assertAutoFilled();
+        mUiBot.assertNoDatasetsEver();
+        callback.assertUiHiddenEvent(username);
     }
 
     @Test
@@ -315,6 +321,8 @@
         Helper.mockSwitchInputMethod(sContext);
         mUiBot.waitForIdleSync();
 
+        // Set new expectations
+        sReplier.addResponse(NO_RESPONSE);
         sAugmentedReplier.addResponse(new CannedAugmentedFillResponse.Builder()
                 .addInlineSuggestion(new CannedAugmentedFillResponse.Dataset.Builder("Augment Me 2")
                         .setField(usernameId, "dude2", createInlinePresentation("dude2"))
@@ -326,8 +334,7 @@
         // Trigger auto-fill
         mUiBot.selectByRelativeId(ID_USERNAME);
         mUiBot.waitForIdle();
-
-        // Confirm new fill request
+        sReplier.getNextFillRequest();
         sAugmentedReplier.getNextFillRequest();
 
         // Confirm new suggestion
diff --git a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
index 776879d..a3e6256 100644
--- a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
@@ -431,7 +431,7 @@
         int width = size.getWidth();
         int height = size.getHeight();
         /**
-         * Check the input allocation is sane.
+         * Check the input allocation is valid.
          * - Byte size matches what we expect.
          * - The input is not all zeroes.
          */
diff --git a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
index 4a4aa0d..90a7dcd 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
@@ -2361,7 +2361,7 @@
                         result.get(CaptureResult.TONEMAP_PRESET_CURVE));
             }
 
-            // Tonemap curve result availability and basic sanity check for all modes.
+            // Tonemap curve result availability and basic validity check for all modes.
             mCollector.expectValuesInRange("Tonemap curve red values are out of range",
                     CameraTestUtils.toObject(mapRed), /*min*/ZERO, /*max*/ONE);
             mCollector.expectInRange("Tonemap curve red length is out of range",
@@ -2999,8 +2999,9 @@
      */
     private void changeExposure(CaptureRequest.Builder requestBuilder,
             long expTime, int sensitivity) {
-        // Check if the max analog sensitivity is available and no larger than max sensitivity.
-        // The max analog sensitivity is not actually used here. This is only an extra sanity check.
+        // Check if the max analog sensitivity is available and no larger than max sensitivity.  The
+        // max analog sensitivity is not actually used here. This is only an extra correctness
+        // check.
         mStaticInfo.getMaxAnalogSensitivityChecked();
 
         expTime = mStaticInfo.getExposureClampToRange(expTime);
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index 07155ff..7bf1f4c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -2084,7 +2084,7 @@
     }
 
     /**
-     * Sanity check of optical black regions.
+     * Correctness check of optical black regions.
      */
     @Test
     public void testOpticalBlackRegions() {
diff --git a/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java b/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
index 99c6b33..6cfa435 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
@@ -187,7 +187,7 @@
         texture.setDefaultBufferSize(640, 480);
         Surface surface = new Surface(texture);
 
-        // Make sure that the default newInstance is still sane.
+        // Make sure that the default newInstance is still valid.
         ImageWriter defaultWriter = ImageWriter.newInstance(surface, MAX_NUM_IMAGES);
         Image defaultImage = defaultWriter.dequeueInputImage();
         defaultWriter.close();
diff --git a/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java
index 4a88c84..56c2652 100644
--- a/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java
@@ -92,7 +92,6 @@
 
     private static final double FRAME_DURATION_THRESHOLD = 0.03;
     private static final double FOV_THRESHOLD = 0.03;
-    private static final double ASPECT_RATIO_THRESHOLD = 0.03;
     private static final long MAX_TIMESTAMP_DIFFERENCE_THRESHOLD = 10000000; // 10ms
 
     private StateWaiter mSessionWaiter;
@@ -994,51 +993,56 @@
     }
 
     /**
-     * Validate that physical cameras' crop region are compensated based on focal length.
+     * Validate that physical cameras are not cropping too much.
      *
-     * This is to make sure physical processed streams have the same field of view as long as
-     * the physical cameras supports it.
+     * This is to make sure physical processed streams have at least the same field of view as
+     * the logical stream, or the maximum field of view of the physical camera, whichever is
+     * smaller.
+     *
+     * Note that the FOV is calculated in the directio of sensor width.
      */
     private void validatePhysicalCamerasFov(TotalCaptureResult totalCaptureResult,
             List<String> physicalCameraIds) {
         Rect cropRegion = totalCaptureResult.get(CaptureResult.SCALER_CROP_REGION);
         Float focalLength = totalCaptureResult.get(CaptureResult.LENS_FOCAL_LENGTH);
-        float cropAspectRatio = (float)cropRegion.width() / cropRegion.height();
+        Float zoomRatio = totalCaptureResult.get(CaptureResult.CONTROL_ZOOM_RATIO);
+        Rect activeArraySize = mStaticInfo.getActiveArraySizeChecked();
+        SizeF sensorSize = mStaticInfo.getValueFromKeyNonNull(
+                CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);
 
         // Assume subject distance >> focal length, and subject distance >> camera baseline.
-        float fov = cropRegion.width() / (2 * focalLength);
+        double fov = 2 * Math.toDegrees(Math.atan2(sensorSize.getWidth() * cropRegion.width() /
+                (2 * zoomRatio * activeArraySize.width()),  focalLength));
+
         Map<String, CaptureResult> physicalResultsDual =
                     totalCaptureResult.getPhysicalCameraResults();
         for (String physicalId : physicalCameraIds) {
+            StaticMetadata physicalStaticInfo = mAllStaticInfo.get(physicalId);
             CaptureResult physicalResult = physicalResultsDual.get(physicalId);
             Rect physicalCropRegion = physicalResult.get(CaptureResult.SCALER_CROP_REGION);
-            final Float physicalFocalLength = physicalResult.get(CaptureResult.LENS_FOCAL_LENGTH);
+            Float physicalFocalLength = physicalResult.get(CaptureResult.LENS_FOCAL_LENGTH);
+            Float physicalZoomRatio = physicalResult.get(CaptureResult.CONTROL_ZOOM_RATIO);
+            Rect physicalActiveArraySize = physicalStaticInfo.getActiveArraySizeChecked();
+            SizeF physicalSensorSize = mStaticInfo.getValueFromKeyNonNull(
+                    CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);
 
-            StaticMetadata staticInfo = mAllStaticInfo.get(physicalId);
-            final Rect activeArraySize = staticInfo.getActiveArraySizeChecked();
-            final Float maxDigitalZoom = staticInfo.getAvailableMaxDigitalZoomChecked();
-            int maxWidth = activeArraySize.width();
-            int minWidth = (int)(activeArraySize.width() / maxDigitalZoom);
-            int expectedCropWidth = Math.max(Math.min(Math.round(fov * 2 * physicalFocalLength),
-                    maxWidth), minWidth);
+            double physicalFov = 2 * Math.toDegrees(Math.atan2(
+                    physicalSensorSize.getWidth() * physicalCropRegion.width() /
+                    (2 * physicalZoomRatio * physicalActiveArraySize.width()), physicalFocalLength));
 
-            // Makes sure FOV matches to the maximum extent.
-            assertTrue("Physical stream FOV (Field of view) should match logical stream to most "
-                    + "extent. Crop region actual width " + physicalCropRegion.width() +
-                    " vs expected width " + expectedCropWidth,
-                    Math.abs((float)physicalCropRegion.width() - expectedCropWidth) /
-                    expectedCropWidth < FOV_THRESHOLD);
+            double maxPhysicalFov = 2 * Math.toDegrees(Math.atan2(physicalSensorSize.getWidth() / 2,
+                    physicalFocalLength));
+            double expectedPhysicalFov = Math.min(maxPhysicalFov, fov);
 
-            // Makes sure aspect ratio matches.
-            float physicalCropAspectRatio =
-                    (float)physicalCropRegion.width() / physicalCropRegion.height();
-            assertTrue("Physical stream for camera " + physicalId + " aspect ratio " +
-                    physicalCropAspectRatio + " should match logical streams aspect ratio " +
-                    cropAspectRatio, Math.abs(physicalCropAspectRatio - cropAspectRatio) <
-                    ASPECT_RATIO_THRESHOLD);
+            if (VERBOSE) {
+                Log.v(TAG, "Logical camera Fov: " + fov + ", maxPhyiscalFov: " + maxPhysicalFov +
+                        ", physicalFov: " + physicalFov);
+            }
+            assertTrue("Physical stream FOV (Field of view) should be greater or equal to"
+                    + " min(logical stream FOV, max physical stream FOV). Physical FOV: "
+                    + physicalFov + " vs min(" + fov + ", " + maxPhysicalFov,
+                    physicalFov - expectedPhysicalFov > -FOV_THRESHOLD);
         }
-
-
     }
 
     /**
diff --git a/tests/camera/src/android/hardware/camera2/cts/OfflineSessionTest.java b/tests/camera/src/android/hardware/camera2/cts/OfflineSessionTest.java
index 6c60e5f..2eb6004 100644
--- a/tests/camera/src/android/hardware/camera2/cts/OfflineSessionTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/OfflineSessionTest.java
@@ -59,6 +59,8 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import junit.framework.AssertionFailedError;
+
 @RunWith(Parameterized.class)
 public class OfflineSessionTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "OfflineSessionTest";
@@ -325,19 +327,19 @@
                 }
 
                 openDevice(mCameraIdsUnderTest[i]);
-                camera2OfflineSessionTest(mCameraIdsUnderTest[i], mOrderedStillSizes.get(0),
-                        ImageFormat.JPEG, OfflineTestSequence.CloseDeviceAndOpenRemote);
-
-                // Verify that the remote camera was opened correctly
-                List<ErrorLoggingService.LogEvent> allEvents = null;
-                try {
-                    allEvents = errorConnection.getLog(WAIT_FOR_STATE_TIMEOUT_MS,
-                            TestConstants.EVENT_CAMERA_CONNECT);
-                } catch (TimeoutException e) {
-                    fail("Timed out waiting on remote offline process error log!");
+                if (camera2OfflineSessionTest(mCameraIdsUnderTest[i], mOrderedStillSizes.get(0),
+                            ImageFormat.JPEG, OfflineTestSequence.CloseDeviceAndOpenRemote)) {
+                    // Verify that the remote camera was opened correctly
+                    List<ErrorLoggingService.LogEvent> allEvents = null;
+                    try {
+                        allEvents = errorConnection.getLog(WAIT_FOR_STATE_TIMEOUT_MS,
+                                TestConstants.EVENT_CAMERA_CONNECT);
+                    } catch (TimeoutException e) {
+                        fail("Timed out waiting on remote offline process error log!");
+                    }
+                    assertNotNull("Failed to connect to camera device in remote offline process!",
+                            allEvents);
                 }
-                assertNotNull("Failed to connect to camera device in remote offline process!",
-                        allEvents);
             } finally {
                 closeDevice();
 
@@ -481,6 +483,17 @@
         }
     }
 
+    private void checkForSequenceAbort(SimpleCaptureCallback resultListener, int sequenceId) {
+        ArrayList<Integer> abortedSeq = resultListener.geAbortedSequences(
+                1 /*maxNumbAborts*/);
+        assertNotNull("No aborted capture sequence ids present", abortedSeq);
+        assertTrue("Unexpected number of aborted capture sequence ids : " +
+                abortedSeq.size() + " expected 1", abortedSeq.size() == 1);
+        assertTrue("Unexpected abort capture sequence id: " +
+                abortedSeq.get(0).intValue() + " expected capture sequence id: " +
+                sequenceId, abortedSeq.get(0).intValue() == sequenceId);
+    }
+
     private void verifyCaptureResults(SimpleCaptureCallback resultListener,
             SimpleImageReaderListener imageListener, int sequenceId, boolean offlineResults)
             throws Exception {
@@ -524,8 +537,18 @@
                 sequenceLastFrameNumber, lastFrameNumberReceived);
     }
 
-    private void camera2OfflineSessionTest(String cameraId, Size offlineSize, int offlineFormat,
+    /**
+     * Verify offline session behavior during common use cases
+     *
+     * @param cameraId      Id of the camera device under test
+     * @param offlineSize   The offline surface size
+     * @param offlineFormat The offline surface pixel format
+     * @param testSequence  Specific scenario to be verified
+     * @return true if the offline session switch is successful, false if there is any failure.
+     */
+    private boolean camera2OfflineSessionTest(String cameraId, Size offlineSize, int offlineFormat,
             OfflineTestSequence testSequence) throws Exception {
+        boolean ret = false;
         int remoteOfflinePID = -1;
         Size previewSize = mOrderedPreviewSizes.get(0);
         for (Size sz : mOrderedPreviewSizes) {
@@ -571,7 +594,7 @@
 
         if (!mSession.supportsOfflineProcessing(mReaderSurface)) {
             Log.i(TAG, "Camera does not support offline processing for still capture output");
-            return;
+            return false;
         }
 
         // Configure the requests.
@@ -626,8 +649,16 @@
             verify(mockOfflineCb, times(0)).onError(offlineSession,
                     CameraOfflineSessionCallback.STATUS_INTERNAL_ERROR);
 
-            verifyCaptureResults(resultListener, null /*imageListener*/, repeatingSeqId,
-                    false /*offlineResults*/);
+            try {
+                verifyCaptureResults(resultListener, null /*imageListener*/, repeatingSeqId,
+                        false /*offlineResults*/);
+            } catch (AssertionFailedError e) {
+                if (testSequence == OfflineTestSequence.RepeatingSequenceAbort) {
+                    checkForSequenceAbort(resultListener, repeatingSeqId);
+                } else {
+                    throw e;
+                }
+            }
             verifyCaptureResults(offlineResultListener, null /*imageListener*/, offlineSeqId,
                     true /*offlineResults*/);
         } else {
@@ -636,14 +667,7 @@
 
             switch (testSequence) {
                 case RepeatingSequenceAbort:
-                    ArrayList<Integer> abortedSeq = resultListener.geAbortedSequences(
-                            1 /*maxNumbAborts*/);
-                    assertNotNull("No aborted capture sequence ids present", abortedSeq);
-                    assertTrue("Unexpected number of aborted capture sequence ids : " +
-                            abortedSeq.size() + " expected 1", abortedSeq.size() == 1);
-                    assertTrue("Unexpected abort capture sequence id: " +
-                            abortedSeq.get(0).intValue() + " expected capture sequence id: " +
-                            repeatingSeqId, abortedSeq.get(0).intValue() == repeatingSeqId);
+                    checkForSequenceAbort(resultListener, repeatingSeqId);
                     break;
                 case CloseDeviceAndOpenRemote:
                     // According to the documentation, closing the initial camera device and
@@ -741,11 +765,15 @@
             offlineCb.waitForState(BlockingOfflineSessionCallback.STATE_CLOSED,
                   WAIT_FOR_STATE_TIMEOUT_MS);
             verify(mockOfflineCb, times(1)).onClosed(offlineSession);
+
+            ret = true;
         }
 
         closeImageReader();
 
         stopRemoteOfflineTestProcess(remoteOfflinePID);
+
+        return ret;
     }
 
     private void checkInitialResults(SimpleCaptureCallback resultListener) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
index 067104c..bf42ab7 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
@@ -2046,7 +2046,7 @@
     }
 
     /**
-     * Validate video snapshot capture image object sanity and test.
+     * Validate video snapshot capture image object validity and test.
      *
      * <p> Check for size, format and jpeg decoding</p>
      *
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index 80a2fe95..0a24671 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -1829,7 +1829,7 @@
                 { LEGACY_COMBINATIONS, LIMITED_COMBINATIONS, BURST_COMBINATIONS, FULL_COMBINATIONS,
                   RAW_COMBINATIONS, LEVEL_3_COMBINATIONS };
 
-        sanityCheckConfigurationTables(TABLES);
+        validityCheckConfigurationTables(TABLES);
 
         for (String id : mCameraIdsUnderTest) {
             openDevice(id);
@@ -1965,7 +1965,7 @@
         final int[][][] TABLES =
                 { LIMITED_COMBINATIONS, FULL_COMBINATIONS, RAW_COMBINATIONS, LEVEL_3_COMBINATIONS };
 
-        sanityCheckConfigurationTables(TABLES);
+        validityCheckConfigurationTables(TABLES);
 
         for (String id : mCameraIdsUnderTest) {
             openDevice(id);
@@ -2091,9 +2091,9 @@
     }
 
     /**
-     * Sanity check the configuration tables.
+     * Verify correctness of the configuration tables.
      */
-    private void sanityCheckConfigurationTables(final int[][][] tables) throws Exception {
+    private void validityCheckConfigurationTables(final int[][][] tables) throws Exception {
         int tableIdx = 0;
         for (int[][] table : tables) {
             int rowIdx = 0;
diff --git a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
index 991649e..5f2f961 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -1564,9 +1564,9 @@
     }
 
     /**
-     * Validate JPEG capture image object sanity and test.
+     * Validate JPEG capture image object correctness and test.
      * <p>
-     * In addition to image object sanity, this function also does the decoding
+     * In addition to image object correctness, this function also does the decoding
      * test, which is slower.
      * </p>
      *
diff --git a/tests/camera/src/android/hardware/cts/CameraTest.java b/tests/camera/src/android/hardware/cts/CameraTest.java
index 192d7ad..c2645ad 100644
--- a/tests/camera/src/android/hardware/cts/CameraTest.java
+++ b/tests/camera/src/android/hardware/cts/CameraTest.java
@@ -152,31 +152,50 @@
      * receive the callback messages.
      */
     private void initializeMessageLooper(final int cameraId) throws IOException {
+        LooperInfo looperInfo = new LooperInfo();
+        initializeMessageLooper(cameraId, mErrorCallback, looperInfo);
+        mIsExternalCamera = looperInfo.isExternalCamera;
+        mCamera = looperInfo.camera;
+        mLooper = looperInfo.looper;
+    }
+
+    private final class LooperInfo {
+        Camera camera = null;
+        Looper looper = null;
+        boolean isExternalCamera = false;
+    };
+
+    /*
+     * Initializes the message looper so that the Camera object can
+     * receive the callback messages.
+     */
+    private void initializeMessageLooper(final int cameraId, final ErrorCallback errorCallback,
+            LooperInfo looperInfo) throws IOException {
         final ConditionVariable startDone = new ConditionVariable();
         final CameraCtsActivity activity = mActivityRule.getActivity();
         new Thread() {
             @Override
             public void run() {
-                Log.v(TAG, "start loopRun");
+                Log.v(TAG, "start loopRun for cameraId " + cameraId);
                 // Set up a looper to be used by camera.
                 Looper.prepare();
                 // Save the looper so that we can terminate this thread
                 // after we are done with it.
-                mLooper = Looper.myLooper();
+                looperInfo.looper = Looper.myLooper();
                 try {
-                    mIsExternalCamera = CameraUtils.isExternal(
+                    looperInfo.isExternalCamera = CameraUtils.isExternal(
                             activity.getApplicationContext(), cameraId);
                 } catch (Exception e) {
                     Log.e(TAG, "Unable to query external camera!" + e);
                 }
 
                 try {
-                    mCamera = Camera.open(cameraId);
-                    mCamera.setErrorCallback(mErrorCallback);
+                    looperInfo.camera = Camera.open(cameraId);
+                    looperInfo.camera.setErrorCallback(errorCallback);
                 } catch (RuntimeException e) {
-                    Log.e(TAG, "Fail to open camera." + e);
+                    Log.e(TAG, "Fail to open camera id " + cameraId + ": " + e);
                 }
-                Log.v(TAG, "camera is opened");
+                Log.v(TAG, "camera" + cameraId + " is opened");
                 startDone.open();
                 Looper.loop(); // Blocks forever until Looper.quit() is called.
                 if (VERBOSE) Log.v(TAG, "initializeMessageLooper: quit.");
@@ -188,9 +207,8 @@
             Log.v(TAG, "initializeMessageLooper: start timeout");
             fail("initializeMessageLooper: start timeout");
         }
-        assertNotNull("Fail to open camera.", mCamera);
-        mCamera.setPreviewDisplay(activity.getSurfaceView().getHolder());
-
+        assertNotNull("Fail to open camera " + cameraId, looperInfo.camera);
+        looperInfo.camera.setPreviewDisplay(activity.getSurfaceView().getHolder());
         File parent = activity.getPackageManager().isInstantApp()
                 ? activity.getFilesDir()
                 : activity.getExternalFilesDir(null);
@@ -210,21 +228,33 @@
      * Terminates the message looper thread, optionally allowing evict error
      */
     private void terminateMessageLooper(boolean allowEvict) throws Exception {
-        mLooper.quit();
+        LooperInfo looperInfo = new LooperInfo();
+        looperInfo.camera = mCamera;
+        looperInfo.looper = mLooper;
+        terminateMessageLooper(allowEvict, mCameraErrorCode, looperInfo);
+        mCamera = null;
+    }
+
+    /*
+     * Terminates the message looper thread, optionally allowing evict error
+     */
+    private void terminateMessageLooper(final boolean allowEvict, final int errorCode,
+            final LooperInfo looperInfo) throws Exception {
+        looperInfo.looper.quit();
         // Looper.quit() is asynchronous. The looper may still has some
         // preview callbacks in the queue after quit is called. The preview
         // callback still uses the camera object (setHasPreviewCallback).
         // After camera is released, RuntimeException will be thrown from
         // the method. So we need to join the looper thread here.
-        mLooper.getThread().join();
-        mCamera.release();
-        mCamera = null;
+        looperInfo.looper.getThread().join();
+        looperInfo.camera.release();
+        looperInfo.camera = null;
         if (allowEvict) {
             assertTrue("Got unexpected camera error callback.",
-                    (NO_ERROR == mCameraErrorCode ||
-                    Camera.CAMERA_ERROR_EVICTED == mCameraErrorCode));
+                    (NO_ERROR == errorCode ||
+                    Camera.CAMERA_ERROR_EVICTED == errorCode));
         } else {
-            assertEquals("Got camera error callback.", NO_ERROR, mCameraErrorCode);
+            assertEquals("Got camera error callback.", NO_ERROR, errorCode);
         }
     }
 
@@ -344,6 +374,15 @@
         }
     }
 
+    // parent independent version of TestErrorCallback
+    private static final class TestErrorCallbackI implements ErrorCallback {
+        private int mCameraErrorCode = NO_ERROR;
+        public void onError(int error, Camera camera) {
+            Log.e(TAG, "Got camera error=" + error);
+            mCameraErrorCode = error;
+        }
+    }
+
     private final class AutoFocusCallback
             implements android.hardware.Camera.AutoFocusCallback {
         public void onAutoFocus(boolean success, Camera camera) {
@@ -1006,9 +1045,9 @@
     }
 
     /**
-     * Sanity check of some extra exif tags.
+     * Correctness check of some extra exif tags.
      * <p>
-     * Sanity check some extra exif tags without asserting the check failures
+     * Check some extra exif tags without asserting the check failures
      * immediately. When a failure is detected, the failure cause is logged,
      * the rest of the tests are still executed. The caller can assert with the
      * failure cause based on the returned test status.
@@ -2554,54 +2593,53 @@
         testCamera0.release();
         testCamera1.release();
 
-        // Start first camera
-        if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Opening camera 0");
-        initializeMessageLooper(0);
-        SimplePreviewStreamCb callback0 = new SimplePreviewStreamCb(0);
-        mCamera.setPreviewCallback(callback0);
+        LooperInfo looperInfo0 = new LooperInfo();
+        LooperInfo looperInfo1 = new LooperInfo();
+
+        ConditionVariable previewDone0 = new ConditionVariable();
+        ConditionVariable previewDone1 = new ConditionVariable();
+        // Open both cameras camera
+        if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Opening cameras 0 and 1");
+        TestErrorCallbackI errorCallback0 = new TestErrorCallbackI();
+        TestErrorCallbackI errorCallback1 = new TestErrorCallbackI();
+        initializeMessageLooper(0, errorCallback0, looperInfo0);
+        initializeMessageLooper(1, errorCallback1, looperInfo1);
+
+        SimplePreviewStreamCbI callback0 = new SimplePreviewStreamCbI(0, previewDone0);
+        looperInfo0.camera.setPreviewCallback(callback0);
         if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Starting preview on camera 0");
-        mCamera.startPreview();
+        looperInfo0.camera.startPreview();
         // Run preview for a bit
         for (int f = 0; f < 100; f++) {
-            mPreviewDone.close();
+            previewDone0.close();
             assertTrue("testMultiCameraRelease: First camera preview timed out on frame " + f + "!",
-                       mPreviewDone.block( WAIT_FOR_COMMAND_TO_COMPLETE));
+                       previewDone0.block( WAIT_FOR_COMMAND_TO_COMPLETE));
         }
         if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Stopping preview on camera 0");
-        mCamera.stopPreview();
-        // Save message looper and camera to deterministically release them, instead
-        // of letting GC do it at some point.
-        Camera firstCamera = mCamera;
-        Looper firstLooper = mLooper;
-        //terminateMessageLooper(); // Intentionally not calling this
-        // Preview surface should be released though!
-        mCamera.setPreviewDisplay(null);
+        looperInfo0.camera.stopPreview();
 
-        // Start second camera without releasing the first one (will
-        // set mCamera and mLooper to new objects)
-        if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Opening camera 1");
-        initializeMessageLooper(1);
-        SimplePreviewStreamCb callback1 = new SimplePreviewStreamCb(1);
-        mCamera.setPreviewCallback(callback1);
+        // Preview surface should be released though!
+        looperInfo0.camera.setPreviewDisplay(null);
+
+        SimplePreviewStreamCbI callback1 = new SimplePreviewStreamCbI(1, previewDone1);
+        looperInfo1.camera.setPreviewCallback(callback1);
         if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Starting preview on camera 1");
-        mCamera.startPreview();
-        // Run preview for a bit - GC of first camera instance should not impact the second's
-        // operation.
+        looperInfo1.camera.startPreview();
         for (int f = 0; f < 100; f++) {
-            mPreviewDone.close();
+            previewDone1.close();
             assertTrue("testMultiCameraRelease: Second camera preview timed out on frame " + f + "!",
-                       mPreviewDone.block( WAIT_FOR_COMMAND_TO_COMPLETE));
+                       previewDone1.block( WAIT_FOR_COMMAND_TO_COMPLETE));
             if (f == 50) {
                 // Release first camera mid-preview, should cause no problems
                 if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Releasing camera 0");
-                firstCamera.release();
+                looperInfo0.camera.release();
             }
         }
-        if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Stopping preview on camera 0");
-        mCamera.stopPreview();
+        if (VERBOSE) Log.v(TAG, "testMultiCameraRelease: Stopping preview on camera 1");
+        looperInfo1.camera.stopPreview();
 
-        firstLooper.quit();
-        terminateMessageLooper(true/*allowEvict*/);
+        looperInfo0.looper.quit();
+        terminateMessageLooper(true, errorCallback1.mCameraErrorCode, looperInfo1);
     }
 
     // This callback just signals on the condition variable, making it useful for checking that
@@ -2618,6 +2656,21 @@
         }
     }
 
+    // Parent independent version of SimplePreviewStreamCb
+    private static final class SimplePreviewStreamCbI
+            implements android.hardware.Camera.PreviewCallback {
+        private int mId;
+        private ConditionVariable mPreviewDone = null;
+        public SimplePreviewStreamCbI(int id, ConditionVariable previewDone) {
+            mId = id;
+            mPreviewDone = previewDone;
+        }
+        public void onPreviewFrame(byte[] data, android.hardware.Camera camera) {
+            if (VERBOSE) Log.v(TAG, "Preview frame callback, id " + mId + ".");
+            mPreviewDone.open();
+        }
+    }
+
     @UiThreadTest
     @Test
     public void testFocusAreas() throws Exception {
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 9561eb0..ad0ed57 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -395,7 +395,7 @@
                 image = reader.acquireNextImage();
             } finally {
                 if (image != null) {
-                    // Should only do some quick sanity check in callback, as the ImageReader
+                    // Should only do some quick validity checks in callback, as the ImageReader
                     // could be closed asynchronously, which will close all images acquired from
                     // this ImageReader.
                     checkImage(image, mSize.getWidth(), mSize.getHeight(), mFormat);
@@ -2443,7 +2443,7 @@
     /**
      * Simple validation of JPEG image size and format.
      * <p>
-     * Only validate the image object sanity. It is fast, but doesn't actually
+     * Only validate the image object basic correctness. It is fast, but doesn't actually
      * check the buffer data. Assert is used here as it make no sense to
      * continue the test if the jpeg image captured has some serious failures.
      * </p>
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java
index cb9e522..bef3e26 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java
@@ -22,7 +22,7 @@
 /**
  * Helper set of methods to perform precondition checks before starting method execution.
  *
- * <p>Typically used to sanity check arguments or the current object state.</p>
+ * <p>Typically used to validity check arguments or the current object state.</p>
  */
 public final class Preconditions {
 
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 332964c..a05af2a 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -518,7 +518,7 @@
     }
 
     /**
-     * Get max AE regions and do sanity check.
+     * Get max AE regions and do validity check.
      *
      * @return AE max regions supported by the camera device
      */
@@ -531,7 +531,7 @@
     }
 
     /**
-     * Get max AWB regions and do sanity check.
+     * Get max AWB regions and do validity check.
      *
      * @return AWB max regions supported by the camera device
      */
@@ -544,7 +544,7 @@
     }
 
     /**
-     * Get max AF regions and do sanity check.
+     * Get max AF regions and do validity check.
      *
      * @return AF max regions supported by the camera device
      */
@@ -628,7 +628,7 @@
     }
 
     /**
-     * Get available thumbnail sizes and do the sanity check.
+     * Get available thumbnail sizes and do the validity check.
      *
      * @return The array of available thumbnail sizes
      */
@@ -656,7 +656,7 @@
     }
 
     /**
-     * Get available focal lengths and do the sanity check.
+     * Get available focal lengths and do the validity check.
      *
      * @return The array of available focal lengths
      */
@@ -677,7 +677,7 @@
     }
 
     /**
-     * Get available apertures and do the sanity check.
+     * Get available apertures and do the validity check.
      *
      * @return The non-null array of available apertures
      */
@@ -992,7 +992,7 @@
     }
 
     /**
-     * Get hyperfocalDistance and do the sanity check.
+     * Get hyperfocalDistance and do the validity check.
      * <p>
      * Note that, this tag is optional, will return -1 if this tag is not
      * available.
@@ -1151,7 +1151,7 @@
     }
 
     /**
-     * get android.control.availableModes and do the sanity check.
+     * get android.control.availableModes and do the validity check.
      *
      * @return available control modes.
      */
@@ -1207,7 +1207,7 @@
     }
 
     /**
-     * Get aeAvailableModes and do the sanity check.
+     * Get aeAvailableModes and do the validity check.
      *
      * <p>Depending on the check level this class has, for WAR or COLLECT levels,
      * If the aeMode list is invalid, return an empty mode array. The the caller doesn't
@@ -1277,7 +1277,7 @@
     }
 
     /**
-     * Get available AWB modes and do the sanity check.
+     * Get available AWB modes and do the validity check.
      *
      * @return array that contains available AWB modes, empty array if awbAvailableModes is
      * unavailable.
@@ -1303,7 +1303,7 @@
     }
 
     /**
-     * Get available AF modes and do the sanity check.
+     * Get available AF modes and do the validity check.
      *
      * @return array that contains available AF modes, empty array if afAvailableModes is
      * unavailable.
@@ -1691,7 +1691,7 @@
     }
 
     /**
-     * Get value of key android.control.aeCompensationStep and do the sanity check.
+     * Get value of key android.control.aeCompensationStep and do the validity check.
      *
      * @return default value if the value is null.
      */
@@ -1716,7 +1716,7 @@
     }
 
     /**
-     * Get value of key android.control.aeCompensationRange and do the sanity check.
+     * Get value of key android.control.aeCompensationRange and do the validity check.
      *
      * @return default value if the value is null or malformed.
      */
@@ -1746,7 +1746,7 @@
     }
 
     /**
-     * Get availableVideoStabilizationModes and do the sanity check.
+     * Get availableVideoStabilizationModes and do the validity check.
      *
      * @return available video stabilization modes, empty array if it is unavailable.
      */
@@ -1777,7 +1777,7 @@
     }
 
     /**
-     * Get availableOpticalStabilization and do the sanity check.
+     * Get availableOpticalStabilization and do the validity check.
      *
      * @return available optical stabilization modes, empty array if it is unavailable.
      */
@@ -1967,7 +1967,7 @@
     }
 
     /**
-     * Get max pipeline depth and do the sanity check.
+     * Get max pipeline depth and do the validity check.
      *
      * @return max pipeline depth, default value if it is not available.
      */
@@ -2033,7 +2033,7 @@
 
 
     /**
-     * Get available capabilities and do the sanity check.
+     * Get available capabilities and do the validity check.
      *
      * @return reported available capabilities list, empty list if the value is unavailable.
      */
@@ -2299,7 +2299,7 @@
     }
 
     /**
-     * Get max number of output raw streams and do the basic sanity check.
+     * Get max number of output raw streams and do the basic validity check.
      *
      * @return reported max number of raw output stream
      */
@@ -2312,7 +2312,7 @@
     }
 
     /**
-     * Get max number of output processed streams and do the basic sanity check.
+     * Get max number of output processed streams and do the basic validity check.
      *
      * @return reported max number of processed output stream
      */
@@ -2325,7 +2325,7 @@
     }
 
     /**
-     * Get max number of output stalling processed streams and do the basic sanity check.
+     * Get max number of output stalling processed streams and do the basic validity check.
      *
      * @return reported max number of stalling processed output stream
      */
@@ -2338,7 +2338,7 @@
     }
 
     /**
-     * Get lens facing and do the sanity check
+     * Get lens facing and do the validity check
      * @return lens facing, return default value (BACK) if value is unavailable.
      */
     public int getLensFacingChecked() {
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/LaunchPipOnPipActivity.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/LaunchPipOnPipActivity.java
index 3adf5d7..fd44271 100644
--- a/tests/framework/base/windowmanager/app/src/android/server/wm/app/LaunchPipOnPipActivity.java
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/LaunchPipOnPipActivity.java
@@ -26,7 +26,6 @@
     public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
             Configuration newConfig) {
         super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
-        AlwaysFocusablePipActivity.launchAlwaysFocusablePipActivity(this,
-            getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK));
+        AlwaysFocusablePipActivity.launchAlwaysFocusablePipActivity(this, false);
     }
 }
diff --git a/tests/framework/base/windowmanager/jetpack/Android.bp b/tests/framework/base/windowmanager/jetpack/Android.bp
index f330299..f0cc7cc 100644
--- a/tests/framework/base/windowmanager/jetpack/Android.bp
+++ b/tests/framework/base/windowmanager/jetpack/Android.bp
@@ -13,6 +13,21 @@
 // limitations under the License.
 
 android_library_import {
+    name: "cts_window-extensions_nodeps",
+    aars: ["window-extensions-release.aar"],
+    sdk_version: "current",
+}
+
+java_library {
+    name: "cts_window-extensions",
+    sdk_version: "current",
+    static_libs: [
+        "cts_window-extensions_nodeps",
+    ],
+    installable: false,
+}
+
+android_library_import {
     name: "cts_window-sidecar_nodeps",
     aars: ["window-sidecar-release.aar"],
     sdk_version: "current",
@@ -39,8 +54,8 @@
         "platform-test-annotations",
     ],
     libs: [
-        "androidx.window.extensions",
         "android.test.base.stubs",
+        "cts_window-extensions",
         "cts_window-sidecar",
     ],
     test_suites: [
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java
index 8880904..0686443 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java
@@ -16,6 +16,8 @@
 
 package android.server.wm.jetpack;
 
+import static android.server.wm.jetpack.ExtensionUtils.assertEqualsState;
+
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assume.assumeFalse;
@@ -168,8 +170,8 @@
         mExtension.onDeviceStateListenersChanged(true /* isEmpty */);
         TestDeviceState deviceState3 = mExtension.getDeviceState();
 
-        assertThat(deviceState1).isEqualTo(deviceState2);
-        assertThat(deviceState1).isEqualTo(deviceState3);
+        assertEqualsState(deviceState1, deviceState2);
+        assertEqualsState(deviceState1, deviceState3);
     }
 
     @Test
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionUtils.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionUtils.java
index 82b049e..1aef84e 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionUtils.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionUtils.java
@@ -21,9 +21,11 @@
 import static org.junit.Assume.assumeFalse;
 
 import android.content.Context;
+import android.server.wm.jetpack.wrapper.TestDeviceState;
 import android.server.wm.jetpack.wrapper.extensionwrapperimpl.TestExtensionCompat;
 import android.server.wm.jetpack.wrapper.sidecarwrapperimpl.TestSidecarCompat;
 import android.server.wm.jetpack.wrapper.TestInterfaceCompat;
+import android.server.wm.jetpack.wrapper.sidecarwrapperimpl.TestSidecarDeviceState;
 import android.text.TextUtils;
 import android.util.Log;
 
@@ -53,15 +55,22 @@
         }
     }
 
+    static void assertEqualsState(TestDeviceState left, TestDeviceState right) {
+        if (left instanceof TestSidecarDeviceState && right instanceof TestSidecarDeviceState) {
+            assertThat(left.getPosture()).isEqualTo(right.getPosture());
+        } else {
+            assertThat(left).isEqualTo(right);
+        }
+    }
+
     /**
      * Gets the vendor provided Extension implementation if available. If not available, gets the
      * Sidecar implementation (deprecated). If neither is available, returns {@code null}.
      */
     @Nullable
     static TestInterfaceCompat getInterfaceCompat(Context context) {
-        if (!TextUtils.isEmpty(getExtensionVersion())) {
-            return getExtensionInterfaceCompat(context);
-        } else if (!TextUtils.isEmpty(getSidecarVersion())) {
+        // TODO(b/158876142) Reinstate android.window.extension
+        if (!TextUtils.isEmpty(getSidecarVersion())) {
             return getSidecarInterfaceCompat(context);
         }
         return null;
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/wrapper/sidecarwrapperimpl/TestSidecarDeviceState.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/wrapper/sidecarwrapperimpl/TestSidecarDeviceState.java
index 63a2a44..76e920a 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/wrapper/sidecarwrapperimpl/TestSidecarDeviceState.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/wrapper/sidecarwrapperimpl/TestSidecarDeviceState.java
@@ -24,7 +24,7 @@
 
 /** Extension interface compatibility wrapper for v0.1 sidecar. */
 @SuppressWarnings("deprecation")
-final class TestSidecarDeviceState implements TestDeviceState {
+public final class TestSidecarDeviceState implements TestDeviceState {
 
     @Nullable
     static TestSidecarDeviceState create(@Nullable SidecarDeviceState sidecarDeviceState) {
diff --git a/tests/framework/base/windowmanager/jetpack/window-extensions-release.aar b/tests/framework/base/windowmanager/jetpack/window-extensions-release.aar
new file mode 100644
index 0000000..0ebbb86
--- /dev/null
+++ b/tests/framework/base/windowmanager/jetpack/window-extensions-release.aar
Binary files differ
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
index e005059..859eb29 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
@@ -64,12 +64,10 @@
 import android.hardware.display.DisplayManager;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
-import android.provider.Settings;
 import android.server.wm.CommandSession.ActivitySession;
 import android.server.wm.CommandSession.ConfigInfo;
 import android.server.wm.CommandSession.SizeInfo;
 import android.server.wm.TestJournalProvider.TestJournalContainer;
-import android.server.wm.settings.SettingsSession;
 import android.view.Display;
 
 import org.junit.Test;
@@ -452,10 +450,9 @@
     public void testRotatedInfoWithFixedRotationTransform() {
         assumeTrue("Skipping test: no rotation support", supportsRotation());
 
-        // TODO(b/143053092): Remove the settings if it becomes stable.
-        mObjectTracker.manage(new SettingsSession<>(
-                Settings.Global.getUriFor("fixed_rotation_transform"),
-                Settings.Global::getInt, Settings.Global::putInt)).set(1);
+        // Start a portrait activity first to ensure that the orientation will change.
+        launchActivity(PORTRAIT_ORIENTATION_ACTIVITY);
+        mWmState.waitForLastOrientation(SCREEN_ORIENTATION_PORTRAIT);
 
         getLaunchActivityBuilder()
                 .setUseInstrumentation()
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
index 0f89ea2..267bec9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
@@ -25,7 +25,7 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.server.wm.WindowManagerState.STATE_RESUMED;
 import static android.server.wm.ComponentNameUtils.getActivityName;
-import static android.server.wm.UiDeviceUtils.pressBackButton;
+import static android.server.wm.UiDeviceUtils.pressHomeButton;
 import static android.server.wm.app.Components.ANIMATION_TEST_ACTIVITY;
 import static android.server.wm.app.Components.ASSISTANT_ACTIVITY;
 import static android.server.wm.app.Components.ASSISTANT_VOICE_INTERACTION_SERVICE;
@@ -172,11 +172,22 @@
                     TEST_ACTIVITY, ACTIVITY_TYPE_STANDARD, expectedWindowingMode);
         }
 
-        mWmState.assertFocusedActivity("TestActivity should be resumed", TEST_ACTIVITY);
-        mWmState.assertFrontStack("Fullscreen stack should be on top.",
-                expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
-        mWmState.assertFocusedStack("Fullscreen stack should be focused.",
-                expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
+        if (isAssistantOnTop()) {
+            // If the assistant is configured to be always-on-top, then the new task should have
+            // been started behind it and the assistant stack should still be on top.
+            mWmState.assertFocusedActivity(
+                    "AssistantActivity should be focused", ASSISTANT_ACTIVITY);
+            mWmState.assertFrontStackActivityType(
+                    "Assistant stack should be on top.", ACTIVITY_TYPE_ASSISTANT);
+            mWmState.assertFocusedStack("Assistant stack should be focused.",
+                    WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT);
+        } else {
+            mWmState.assertFocusedActivity("TestActivity should be resumed", TEST_ACTIVITY);
+            mWmState.assertFrontStack("Fullscreen stack should be on top.",
+                    expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
+            mWmState.assertFocusedStack("Fullscreen stack should be focused.",
+                    expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
+        }
 
         // Now, tell it to finish itself and ensure that the assistant stack is brought back forward
         mBroadcastActionTrigger.doAction(TEST_ACTIVITY_ACTION_FINISH_SELF);
@@ -189,6 +200,13 @@
 
     @Test
     public void testAssistantStackFinishToPreviousApp() throws Exception {
+        // If the Assistant is configured to be always-on-top, then the assistant activity
+        // started in setUp() will not allow any other activities to start. Therefore we should
+        // remove it before launching a fullscreen activity.
+        if (isAssistantOnTop()) {
+            removeStacksWithActivityTypes(ACTIVITY_TYPE_ASSISTANT);
+        }
+
         // Launch an assistant activity on top of an existing fullscreen activity, and ensure that
         // the fullscreen activity is still visible and on top after the assistant activity finishes
         launchActivityOnDisplay(TEST_ACTIVITY, mAssistantDisplayId);
@@ -232,7 +250,8 @@
             // Go home, launch the assistant and check to see that home is visible
             removeStacksInWindowingModes(WINDOWING_MODE_FULLSCREEN,
                     WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
-            launchHomeActivity();
+            pressHomeButton();
+            resumeAppSwitches();
             launchActivityNoWait(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_ASSISTANT_IS_TRANSLUCENT, "true");
             waitForValidStateWithActivityType(
@@ -257,7 +276,8 @@
             // Go home, launch assistant, launch app into fullscreen with activity present, and go
             // back.Ensure home is visible.
             removeStacksWithActivityTypes(ACTIVITY_TYPE_ASSISTANT);
-            launchHomeActivity();
+            pressHomeButton();
+            resumeAppSwitches();
             launchActivityNoWait(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_ASSISTANT_IS_TRANSLUCENT, "true",
                     EXTRA_ASSISTANT_LAUNCH_NEW_TASK, getActivityName(TEST_ACTIVITY));
@@ -266,7 +286,7 @@
 
             final ComponentName homeActivity = mWmState.getHomeActivityName();
             mWmState.waitAndAssertVisibilityGone(homeActivity);
-            pressBackButton();
+            mBroadcastActionTrigger.doAction(TEST_ACTIVITY_ACTION_FINISH_SELF);
             mWmState.waitForFocusedStack(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT);
             assertAssistantStackExists();
             mWmState.waitForHomeActivityVisible();
@@ -319,7 +339,7 @@
             launchActivityOnDisplay(ANIMATION_TEST_ACTIVITY, mAssistantDisplayId);
             // Wait for animation finished.
             mWmState.waitForActivityState(ANIMATION_TEST_ACTIVITY, STATE_RESUMED);
-            mWmState.assertVisibility(ASSISTANT_ACTIVITY, false);
+            mWmState.assertVisibility(ASSISTANT_ACTIVITY, isAssistantOnTop());
 
             // Launch the assistant again and ensure that it goes into the same task
             launchActivityOnDisplayNoWait(LAUNCH_ASSISTANT_ACTIVITY_FROM_SESSION,
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java b/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java
index 856b4fa..5b3a250 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DialogFrameTests.java
@@ -36,10 +36,12 @@
 import static org.junit.Assert.assertEquals;
 
 import android.content.ComponentName;
+import android.graphics.Insets;
 import android.graphics.Rect;
 import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.Presubmit;
 import android.server.wm.WindowManagerState.WindowState;
+import android.view.WindowInsets;
 
 import androidx.test.rule.ActivityTestRule;
 
@@ -97,9 +99,9 @@
     // the same content frame as the main activity window
     @Test
     public void testMatchParentDialog() throws Exception {
-        doParentChildTest(TEST_MATCH_PARENT, (parent, dialog) ->
-                assertEquals(parent.getContentFrame(), dialog.getFrame())
-        );
+        doParentChildTest(TEST_MATCH_PARENT, (parent, dialog) -> { ;
+            assertEquals(getParentFrameWithInsets(parent), dialog.getFrame());
+        });
     }
 
     private static final int explicitDimension = 200;
@@ -108,12 +110,12 @@
     @Test
     public void testExplicitSizeDefaultGravity() throws Exception {
         doParentChildTest(TEST_EXPLICIT_SIZE, (parent, dialog) -> {
-            Rect contentFrame = parent.getContentFrame();
+            Rect parentFrame = getParentFrameWithInsets(parent);
             Rect expectedFrame = new Rect(
-                    contentFrame.left + (contentFrame.width() - explicitDimension) / 2,
-                    contentFrame.top + (contentFrame.height() - explicitDimension) / 2,
-                    contentFrame.left + (contentFrame.width() + explicitDimension) / 2,
-                    contentFrame.top + (contentFrame.height() + explicitDimension) / 2);
+                    parentFrame.left + (parentFrame.width() - explicitDimension) / 2,
+                    parentFrame.top + (parentFrame.height() - explicitDimension) / 2,
+                    parentFrame.left + (parentFrame.width() + explicitDimension) / 2,
+                    parentFrame.top + (parentFrame.height() + explicitDimension) / 2);
             assertEquals(expectedFrame, dialog.getFrame());
         });
     }
@@ -121,12 +123,12 @@
     @Test
     public void testExplicitSizeTopLeftGravity() throws Exception {
         doParentChildTest(TEST_EXPLICIT_SIZE_TOP_LEFT_GRAVITY, (parent, dialog) -> {
-            Rect contentFrame = parent.getContentFrame();
+            Rect parentFrame = getParentFrameWithInsets(parent);
             Rect expectedFrame = new Rect(
-                    contentFrame.left,
-                    contentFrame.top,
-                    contentFrame.left + explicitDimension,
-                    contentFrame.top + explicitDimension);
+                    parentFrame.left,
+                    parentFrame.top,
+                    parentFrame.left + explicitDimension,
+                    parentFrame.top + explicitDimension);
             assertEquals(expectedFrame, dialog.getFrame());
         });
     }
@@ -134,12 +136,12 @@
     @Test
     public void testExplicitSizeBottomRightGravity() throws Exception {
         doParentChildTest(TEST_EXPLICIT_SIZE_BOTTOM_RIGHT_GRAVITY, (parent, dialog) -> {
-            Rect contentFrame = parent.getContentFrame();
+            Rect parentFrame = getParentFrameWithInsets(parent);
             Rect expectedFrame = new Rect(
-                    contentFrame.left + contentFrame.width() - explicitDimension,
-                    contentFrame.top + contentFrame.height() - explicitDimension,
-                    contentFrame.left + contentFrame.width(),
-                    contentFrame.top + contentFrame.height());
+                    parentFrame.left + parentFrame.width() - explicitDimension,
+                    parentFrame.top + parentFrame.height() - explicitDimension,
+                    parentFrame.left + parentFrame.width(),
+                    parentFrame.top + parentFrame.height());
             assertEquals(expectedFrame, dialog.getFrame());
         });
     }
@@ -152,7 +154,7 @@
         doParentChildTest(TEST_OVER_SIZED_DIMENSIONS, (parent, dialog) ->
                 // With the default flags oversize should result in clipping to
                 // parent frame.
-                assertEquals(parent.getContentFrame(), dialog.getFrame())
+                assertEquals(getParentFrameWithInsets(parent), dialog.getFrame())
         );
     }
 
@@ -166,10 +168,10 @@
         // TODO(b/36890978): We only run this in fullscreen because of the
         // unclear status of NO_LIMITS for non-child surfaces in MW modes
         doFullscreenTest(TEST_OVER_SIZED_DIMENSIONS_NO_LIMITS, (parent, dialog) -> {
-            Rect contentFrame = parent.getContentFrame();
-            Rect expectedFrame = new Rect(contentFrame.left, contentFrame.top,
-                    contentFrame.left + oversizedDimension,
-                    contentFrame.top + oversizedDimension);
+            Rect parentFrame = getParentFrameWithInsets(parent);
+            Rect expectedFrame = new Rect(parentFrame.left, parentFrame.top,
+                    parentFrame.left + oversizedDimension,
+                    parentFrame.top + oversizedDimension);
             assertEquals(expectedFrame, dialog.getFrame());
         });
     }
@@ -180,7 +182,7 @@
     @Test
     public void testExplicitPositionMatchParent() throws Exception {
         doParentChildTest(TEST_EXPLICIT_POSITION_MATCH_PARENT, (parent, dialog) ->
-                assertEquals(parent.getContentFrame(), dialog.getFrame())
+                assertEquals(getParentFrameWithInsets(parent), dialog.getFrame())
         );
     }
 
@@ -190,8 +192,8 @@
     public void testExplicitPositionMatchParentNoLimits() throws Exception {
         final int explicitPosition = 100;
         doParentChildTest(TEST_EXPLICIT_POSITION_MATCH_PARENT_NO_LIMITS, (parent, dialog) -> {
-            Rect contentFrame = parent.getContentFrame();
-            Rect expectedFrame = new Rect(contentFrame);
+            Rect parentFrame = getParentFrameWithInsets(parent);
+            Rect expectedFrame = new Rect(parentFrame);
             expectedFrame.offset(explicitPosition, explicitPosition);
             assertEquals(expectedFrame, dialog.getFrame());
         });
@@ -218,7 +220,7 @@
         float horizontalMargin = .10f;
         float verticalMargin = .15f;
         doParentChildTest(TEST_WITH_MARGINS, (parent, dialog) -> {
-            Rect frame = parent.getContentFrame();
+            Rect frame = getParentFrameWithInsets(parent);
             Rect expectedFrame = new Rect(
                     (int) (horizontalMargin * frame.width() + frame.left),
                     (int) (verticalMargin * frame.height() + frame.top),
@@ -237,4 +239,26 @@
                 assertThat(wmState.getZOrder(dialog), greaterThan(wmState.getZOrder(parent)))
         );
     }
+
+    private Rect getParentFrameWithInsets(WindowState parent) {
+        Rect parentFrame = parent.getFrame();
+        return inset(parentFrame, getActivitySystemInsets());
+    }
+
+    private Insets getActivitySystemInsets() {
+        return mDialogTestActivity
+                .getActivity()
+                .getWindow()
+                .getDecorView()
+                .getRootWindowInsets()
+                .getInsets(WindowInsets.Type.systemBars());
+    }
+
+    private static Rect inset(Rect original, Insets insets) {
+        final int left = original.left + insets.left;
+        final int top = original.top + insets.top;
+        final int right = original.right - insets.right;
+        final int bottom = original.bottom - insets.bottom;
+        return new Rect(left, top, right, bottom);
+    }
 }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
index 2d8d3a2..3ac15bb 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
@@ -1003,6 +1003,8 @@
     @Test
     @FlakyTest(bugId=156314330)
     public void testFinishPipActivityWithTaskOverlay() throws Exception {
+        // Trigger PiP menu activity to properly lose focuse when going home
+        launchActivity(TEST_ACTIVITY);
         // Launch PiP activity
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
         waitForEnterPip(PIP_ACTIVITY);
@@ -1045,7 +1047,6 @@
         assertEquals("onPause", 0, lifecycleCounts.getCount(ActivityCallback.ON_PAUSE));
     }
 
-    @FlakyTest(bugId = 156003518)
     @Test
     public void testPinnedStackWithDockedStack() throws Exception {
         assumeTrue(supportsSplitScreenMultiWindow());
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/PresentationTest.java b/tests/framework/base/windowmanager/src/android/server/wm/PresentationTest.java
index dfc42c3..4b34c9b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/PresentationTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/PresentationTest.java
@@ -72,6 +72,7 @@
         WindowManagerState.DisplayContent display = virtualDisplaySession
                         .setPresentationDisplay(true)
                         .setPublicDisplay(true)
+                        .setResizeDisplay(false) // resize only through resizeDisplay call
                         .createDisplay();
 
         assertThat(display.getFlags() & Display.FLAG_PRESENTATION)
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 1863487..0fc4bc8 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
@@ -16,6 +16,7 @@
 
 package android.server.wm;
 
+import static android.server.wm.WindowManagerState.STATE_RESUMED;
 import static android.server.wm.app.Components.SPLASHSCREEN_ACTIVITY;
 import static android.view.Display.DEFAULT_DISPLAY;
 
@@ -53,6 +54,8 @@
     @Test
     public void testSplashscreenContent() {
         launchActivityNoWait(SPLASHSCREEN_ACTIVITY);
+        // Activity may not be launched yet even if app transition is in idle state.
+        mWmState.waitForActivityState(SPLASHSCREEN_ACTIVITY, STATE_RESUMED);
         mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY);
         mWmState.getStableBounds();
         final Bitmap image = takeScreenshot();
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
index 00fc83b..e3566b9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
@@ -178,18 +178,23 @@
      */
     @Test
     public void testReparentOff() throws Throwable {
+        final SurfaceControl sc = buildDefaultRedSurface(null);
         verifyTest(
                 new SurfaceControlTestCase.ParentSurfaceConsumer () {
                     @Override
                     public void addChildren(SurfaceControl parent) {
-                        final SurfaceControl sc = buildDefaultRedSurface(parent);
-
+                        new SurfaceControl.Transaction().reparent(sc, parent).apply();
                         new SurfaceControl.Transaction().reparent(sc, null).apply();
-
-                        sc.release();
                     }
                 },
                 new RectChecker(new Rect(0, 0, 100, 100), PixelColor.WHITE));
+      // Since the SurfaceControl is parented off-screen, if we release our reference
+      // it may completely die. If this occurs while the render thread is still rendering
+      // the RED background we could trigger a crash. For this test defer destroying the
+      // Surface until we have collected our test results.
+      if (sc != null) {
+        sc.release();
+      }
     }
 
     /**
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
index 6299fc8..de7ecc8 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
@@ -19,13 +19,16 @@
 import static android.server.wm.WindowInsetsAnimationControllerTests.ControlListener.Event.CANCELLED;
 import static android.server.wm.WindowInsetsAnimationControllerTests.ControlListener.Event.FINISHED;
 import static android.server.wm.WindowInsetsAnimationControllerTests.ControlListener.Event.READY;
-import static android.server.wm.WindowInsetsAnimationTestBase.showImeWithHardKeyboardSetting;
 import static android.server.wm.WindowInsetsAnimationUtils.INSETS_EVALUATOR;
 import static android.view.WindowInsets.Type.ime;
 import static android.view.WindowInsets.Type.navigationBars;
 import static android.view.WindowInsets.Type.statusBars;
 
 import static androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.android.cts.mockime.ImeEventStreamTestUtils.editorMatcher;
+import static com.android.cts.mockime.ImeEventStreamTestUtils.expectEvent;
 
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.hasItem;
@@ -33,14 +36,17 @@
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.not;
 import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
 import static org.hamcrest.Matchers.sameInstance;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeThat;
 import static org.junit.Assume.assumeTrue;
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
 import android.animation.ValueAnimator;
+import android.app.Instrumentation;
 import android.graphics.Insets;
 import android.os.CancellationSignal;
 import android.platform.test.annotations.Presubmit;
@@ -60,6 +66,10 @@
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 
+import com.android.cts.mockime.ImeEventStream;
+import com.android.cts.mockime.ImeSettings;
+import com.android.cts.mockime.MockImeSession;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
@@ -85,7 +95,7 @@
  * Build/Install/Run:
  *     atest CtsWindowManagerDeviceTestCases:WindowInsetsAnimationControllerTests
  */
-//TODO(b/159038873) @Presubmit
+//TODO(b/159167851) @Presubmit
 @RunWith(Parameterized.class)
 public class WindowInsetsAnimationControllerTests extends WindowManagerTestBase {
 
@@ -102,6 +112,13 @@
     @Rule
     public LimitedErrorCollector mErrorCollector = new LimitedErrorCollector();
 
+    /**
+     * {@link MockImeSession} used when {@link #mType} is
+     * {@link android.view.WindowInsets.Type#ime()}.
+     */
+    @Nullable
+    private MockImeSession mMockImeSession;
+
     @Parameter(0)
     public int mType;
 
@@ -120,15 +137,41 @@
     @Before
     public void setUp() throws Exception {
         super.setUp();
+        final ImeEventStream mockImeEventStream;
+        if (mType == ime()) {
+            final Instrumentation instrumentation = getInstrumentation();
+            assumeThat(MockImeSession.getUnavailabilityReason(instrumentation.getContext()),
+                    nullValue());
+
+            // For the best test stability MockIme should be selected before launching TestActivity.
+            mMockImeSession = MockImeSession.create(
+                    instrumentation.getContext(), instrumentation.getUiAutomation(),
+                    new ImeSettings.Builder());
+            mockImeEventStream = mMockImeSession.openEventStream();
+        } else {
+            mockImeEventStream = null;
+        }
+
         mActivity = startActivity(TestActivity.class);
         mRootView = mActivity.getWindow().getDecorView();
         mListener = new ControlListener(mErrorCollector);
-        showImeWithHardKeyboardSetting(mObjectTracker);
         assumeTestCompatibility();
+
+        if (mockImeEventStream != null) {
+            // TestActivity has a focused EditText. Hence MockIme should receive onStartInput() for
+            // that EditText within a reasonable time.
+            expectEvent(mockImeEventStream,
+                    editorMatcher("onStartInput", mActivity.getEditTextMarker()),
+                    TimeUnit.SECONDS.toMillis(10));
+        }
     }
 
     @After
     public void tearDown() throws Throwable {
+        if (mMockImeSession != null) {
+            mMockImeSession.close();
+            mMockImeSession = null;
+        }
         runOnUiThread(() -> {});  // Fence to make sure we dispatched everything.
         mCallbacks.forEach(VerifyingCallback::assertNoRunningAnimations);
     }
@@ -140,6 +183,7 @@
         }
     }
 
+    @Presubmit
     @Test
     public void testControl_andCancel() throws Throwable {
         runOnUiThread(() -> {
@@ -172,6 +216,7 @@
         mListener.assertWasNotCalled(FINISHED);
     }
 
+    @Presubmit
     @Test
     public void testControl_immediately_show() throws Throwable {
         setVisibilityAndWait(mType, false);
@@ -192,6 +237,7 @@
         mListener.assertWasNotCalled(CANCELLED);
     }
 
+    @Presubmit
     @Test
     public void testControl_immediately_hide() throws Throwable {
         setVisibilityAndWait(mType, true);
@@ -212,6 +258,7 @@
         mListener.assertWasNotCalled(CANCELLED);
     }
 
+    @Presubmit
     @Test
     public void testControl_transition_show() throws Throwable {
         setVisibilityAndWait(mType, false);
@@ -230,6 +277,7 @@
         mListener.assertWasNotCalled(CANCELLED);
     }
 
+    @Presubmit
     @Test
     public void testControl_transition_hide() throws Throwable {
         setVisibilityAndWait(mType, true);
@@ -248,6 +296,7 @@
         mListener.assertWasNotCalled(CANCELLED);
     }
 
+    @Presubmit
     @Test
     public void testControl_transition_show_interpolator() throws Throwable {
         mInterpolator = new DecelerateInterpolator();
@@ -267,6 +316,7 @@
         mListener.assertWasNotCalled(CANCELLED);
     }
 
+    @Presubmit
     @Test
     public void testControl_transition_hide_interpolator() throws Throwable {
         mInterpolator = new AccelerateInterpolator();
@@ -309,6 +359,7 @@
         mListener.assertWasNotCalled(FINISHED);
     }
 
+    @Presubmit
     @Test
     public void testImeControl_isntInterruptedByStartingInput() throws Throwable {
         if (mType != ime()) {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java
index 32255d2..373e1e5 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java
@@ -19,6 +19,7 @@
 import static android.graphics.Insets.NONE;
 import static android.view.WindowInsets.Type.ime;
 import static android.view.WindowInsets.Type.navigationBars;
+import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
 
 import static androidx.test.InstrumentationRegistry.getInstrumentation;
 
@@ -32,7 +33,9 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.withSettings;
 
+import android.app.Instrumentation;
 import android.content.pm.PackageManager;
+import android.graphics.Color;
 import android.platform.test.annotations.Presubmit;
 import android.view.WindowInsets;
 
@@ -40,10 +43,9 @@
 import androidx.test.platform.app.InstrumentationRegistry;
 
 import com.android.cts.mockime.ImeSettings;
-import com.android.cts.mockime.MockImeSessionRule;
+import com.android.cts.mockime.MockImeSession;
 
 import org.junit.Before;
-import org.junit.Rule;
 import org.junit.Test;
 import org.mockito.InOrder;
 
@@ -56,12 +58,7 @@
 @Presubmit
 public class WindowInsetsAnimationImeTests extends WindowInsetsAnimationTestBase {
 
-    @Rule
-    public final MockImeSessionRule mMockImeSessionRule = new MockImeSessionRule(
-            InstrumentationRegistry.getInstrumentation().getContext(),
-            InstrumentationRegistry.getInstrumentation().getUiAutomation(),
-            new ImeSettings.Builder()
-    );
+    private static final int KEYBOARD_HEIGHT = 600;
 
     @Before
     public void setup() throws Exception {
@@ -69,33 +66,34 @@
         assumeTrue("MockIme cannot be used for devices that do not support installable IMEs",
                 mInstrumentation.getContext().getPackageManager().hasSystemFeature(
                         PackageManager.FEATURE_INPUT_METHODS));
+    }
+
+    private void initActivity(boolean useFloating) throws Exception {
+        initMockImeSession(useFloating);
+
         mActivity = startActivity(TestActivity.class);
         mRootView = mActivity.getWindow().getDecorView();
     }
 
+    private MockImeSession initMockImeSession(boolean useFloating) throws Exception {
+        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        return MockImeSession.create(
+                instrumentation.getContext(), instrumentation.getUiAutomation(),
+                useFloating ? getFloatingImeSettings()
+                        : new ImeSettings.Builder().setInputViewHeight(KEYBOARD_HEIGHT)
+                                .setDrawsBehindNavBar(true));
+    }
+
     @Test
-    public void testImeAnimationCallbacksShowAndHide() {
-        WindowInsets before = mActivity.mLastWindowInsets;
-        getInstrumentation().runOnMainSync(
-                () -> mRootView.getWindowInsetsController().show(ime()));
-
-        waitForOrFail("Waiting until animation done", () -> mActivity.mCallback.animationDone);
-        commonAnimationAssertions(mActivity, before, true /* show */, ime());
-        mActivity.mCallback.animationDone = false;
-
-        before = mActivity.mLastWindowInsets;
-
-        getInstrumentation().runOnMainSync(
-                () -> mRootView.getWindowInsetsController().hide(ime()));
-
-        waitForOrFail("Waiting until animation done", () -> mActivity.mCallback.animationDone);
-
-        commonAnimationAssertions(mActivity, before, false /* show */, ime());
+    public void testImeAnimationCallbacksShowAndHide() throws Exception {
+        initActivity(false /* useFloating */);
+        testShowAndHide();
     }
 
     @Test
     @FlakyTest(detail = "Promote once confirmed non-flaky")
-    public void testAnimationCallbacks_overlapping_opposite() {
+    public void testAnimationCallbacks_overlapping_opposite() throws Exception {
+        initActivity(false /* useFloating */);
         WindowInsets before = mActivity.mLastWindowInsets;
 
         MultiAnimCallback callbackInner = new MultiAnimCallback();
@@ -153,4 +151,39 @@
                 callback.imeAnimSteps.get(callback.imeAnimSteps.size() - 1).insets
                         .getInsets(ime()));
     }
+
+    @Test
+    public void testZeroInsetsImeAnimates() throws Exception {
+        initActivity(true /* useFloating */);
+        testShowAndHide();
+    }
+
+    private void testShowAndHide() {
+        WindowInsets before = mActivity.mLastWindowInsets;
+        getInstrumentation().runOnMainSync(
+                () -> mRootView.getWindowInsetsController().show(ime()));
+
+        waitForOrFail("Waiting until animation done", () -> mActivity.mCallback.animationDone);
+        commonAnimationAssertions(mActivity, before, true /* show */, ime());
+        mActivity.mCallback.animationDone = false;
+
+        before = mActivity.mLastWindowInsets;
+
+        getInstrumentation().runOnMainSync(
+                () -> mRootView.getWindowInsetsController().hide(ime()));
+
+        waitForOrFail("Waiting until animation done", () -> mActivity.mCallback.animationDone);
+
+        commonAnimationAssertions(mActivity, before, false /* show */, ime());
+    }
+
+    private static ImeSettings.Builder getFloatingImeSettings() {
+        final ImeSettings.Builder builder = new ImeSettings.Builder();
+        builder.setWindowFlags(0, FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
+        // As documented, Window#setNavigationBarColor() is actually ignored when the IME window
+        // does not have FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS.  We are calling setNavigationBarColor()
+        // to ensure it.
+        builder.setNavigationBarColor(Color.BLACK);
+        return builder;
+    }
 }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationSynchronicityTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationSynchronicityTests.java
index d4e6472..f51708f 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationSynchronicityTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationSynchronicityTests.java
@@ -20,6 +20,7 @@
 import static android.server.wm.WindowInsetsAnimationUtils.requestControlThenTransitionToVisibility;
 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
 import static android.view.WindowInsets.Type.ime;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN;
 
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
@@ -43,6 +44,7 @@
 import android.view.WindowInsetsAnimation;
 import android.view.WindowInsetsAnimation.Callback;
 import android.view.WindowInsetsController;
+import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.EditText;
 import android.widget.FrameLayout;
@@ -136,8 +138,10 @@
             super.onCreate(savedInstanceState);
             getWindow().requestFeature(Window.FEATURE_NO_TITLE);
             getWindow().setDecorFitsSystemWindows(false);
+            getWindow().setSoftInputMode(SOFT_INPUT_STATE_ALWAYS_HIDDEN);
             mTestView = new TestView(this);
             mEditText = new EditText(this);
+            mEditText.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN);
             mTestView.addView(mEditText);
             mTestView.mEvaluator = () -> {
                 if (mEvaluator != null) {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTestBase.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTestBase.java
index da69b92..af8ed0b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTestBase.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTestBase.java
@@ -22,6 +22,7 @@
 import static android.view.WindowInsets.Type.statusBars;
 import static android.view.WindowInsets.Type.systemBars;
 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
@@ -34,9 +35,8 @@
 import static org.mockito.Mockito.spy;
 
 import android.os.Bundle;
-import android.provider.Settings;
+import android.os.SystemClock;
 import android.server.wm.WindowInsetsAnimationTestBase.AnimCallback.AnimationStep;
-import android.server.wm.settings.SettingsSession;
 import android.util.ArraySet;
 import android.view.View;
 import android.view.WindowInsets;
@@ -45,6 +45,8 @@
 import android.widget.LinearLayout;
 import android.widget.TextView;
 
+import androidx.annotation.NonNull;
+
 import org.junit.Assert;
 import org.mockito.InOrder;
 
@@ -156,23 +158,6 @@
         }
     }
 
-    /**
-     * Workaround for b/158637229: force the keyboard to show even when there is a hardware keyboard
-     * during IME related insets tests to avoid issues when testing on devices that have a hardware
-     * keyboard.
-     *
-     * @param tracker the test's {@link ObjectTracker}, used to clean up the setting override after
-     *                the test finishes.
-     */
-    static void showImeWithHardKeyboardSetting(ObjectTracker tracker) {
-        final SettingsSession<Integer> showImeWithHardKeyboardSetting = new SettingsSession<>(
-                Settings.Secure.getUriFor(Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD),
-                Settings.Secure::getInt,
-                Settings.Secure::putInt);
-        tracker.manage(showImeWithHardKeyboardSetting);
-        showImeWithHardKeyboardSetting.set(1);
-    }
-
     public static class AnimCallback extends WindowInsetsAnimation.Callback {
 
         public static class AnimationStep {
@@ -300,6 +285,10 @@
 
     public static class TestActivity extends FocusableActivity {
 
+        private final String mEditTextMarker =
+                "android.server.wm.WindowInsetsAnimationTestBase.TestActivity"
+                        + SystemClock.elapsedRealtimeNanos();
+
         AnimCallback mCallback =
                 spy(new AnimCallback(WindowInsetsAnimation.Callback.DISPATCH_MODE_STOP));
         WindowInsets mLastWindowInsets;
@@ -318,6 +307,11 @@
             }
         }
 
+        @NonNull
+        String getEditTextMarker() {
+            return mEditTextMarker;
+        }
+
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
@@ -327,12 +321,14 @@
             mView.setOnApplyWindowInsetsListener(mListener);
             mChild = new TextView(this);
             mEditor = new EditText(this);
+            mEditor.setPrivateImeOptions(mEditTextMarker);
             mView.addView(mChild);
             mView.addView(mEditor);
 
             getWindow().setDecorFitsSystemWindows(false);
             getWindow().getAttributes().layoutInDisplayCutoutMode =
                     LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+            getWindow().setSoftInputMode(SOFT_INPUT_STATE_HIDDEN);
             setContentView(mView);
             mEditor.requestFocus();
         }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTests.java
index dfed6c3..23fabe7 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationTests.java
@@ -52,8 +52,6 @@
 
 import java.util.List;
 
-import androidx.test.filters.FlakyTest;
-
 /**
  * Test whether {@link WindowInsetsAnimation.Callback} are properly dispatched to views.
  *
@@ -106,7 +104,6 @@
     }
 
     @Test
-    @FlakyTest(detail = "Promote once confirmed non-flaky")
     public void testAnimationCallbacks_overlapping() {
         WindowInsets before = mActivity.mLastWindowInsets;
 
@@ -250,10 +247,9 @@
             });
         });
 
-        getWmState().waitFor(state -> !state.isWindowVisible("StatusBar"),
-                "Waiting for status bar to be hidden");
-        assertFalse(getWmState().isWindowVisible("StatusBar"));
+        waitForOrFail("Waiting until animation done", () -> mActivity.mCallback.animationDone);
 
+        assertFalse(getWmState().isWindowVisible("StatusBar"));
         verify(mActivity.mCallback).onPrepare(any());
         verify(mActivity.mCallback).onStart(any(), any());
         verify(mActivity.mCallback, atLeastOnce()).onProgress(any(), any());
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
index de2ddd9..aca3a97 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
@@ -17,7 +17,6 @@
 package android.server.wm;
 
 import static android.graphics.PixelFormat.TRANSLUCENT;
-import static android.server.wm.WindowInsetsAnimationTestBase.showImeWithHardKeyboardSetting;
 import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;
 import static android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
 import static android.view.View.SYSTEM_UI_FLAG_IMMERSIVE;
@@ -30,17 +29,24 @@
 import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
 import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
 import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
 
 import static androidx.test.InstrumentationRegistry.getInstrumentation;
 
+import static com.android.cts.mockime.ImeEventStreamTestUtils.editorMatcher;
+import static com.android.cts.mockime.ImeEventStreamTestUtils.expectEvent;
+
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assume.assumeThat;
 import static org.junit.Assume.assumeTrue;
 
 import android.app.Activity;
 import android.app.AlertDialog;
+import android.app.Instrumentation;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.os.Bundle;
@@ -56,10 +62,14 @@
 import android.widget.LinearLayout;
 import android.widget.TextView;
 
+import androidx.annotation.Nullable;
 import androidx.test.filters.FlakyTest;
 
 import com.android.compatibility.common.util.PollingCheck;
 import com.android.compatibility.common.util.SystemUtil;
+import com.android.cts.mockime.ImeEventStream;
+import com.android.cts.mockime.ImeSettings;
+import com.android.cts.mockime.MockImeSession;
 
 import org.junit.Rule;
 import org.junit.Test;
@@ -74,7 +84,7 @@
  * Build/Install/Run:
  *     atest CtsWindowManagerDeviceTestCases:WindowInsetsControllerTests
  */
-//TODO(b/159038873) @Presubmit
+@Presubmit
 public class WindowInsetsControllerTests extends WindowManagerTestBase {
 
     private final static long TIMEOUT = 1000; // milliseconds
@@ -180,19 +190,27 @@
     }
 
     @Test
-    public void testImeShowAndHide() {
-        showImeWithHardKeyboardSetting(mObjectTracker);
+    public void testImeShowAndHide() throws Exception {
+        final Instrumentation instrumentation = getInstrumentation();
+        assumeThat(MockImeSession.getUnavailabilityReason(instrumentation.getContext()),
+                nullValue());
+        try (MockImeSession imeSession = MockImeSession.create(instrumentation.getContext(),
+                instrumentation.getUiAutomation(), new ImeSettings.Builder())) {
+            final ImeEventStream stream = imeSession.openEventStream();
 
-        final TestActivity activity = startActivity(TestActivity.class);
-        final View rootView = activity.getWindow().getDecorView();
-        getInstrumentation().runOnMainSync(() -> {
-            rootView.getWindowInsetsController().show(ime());
-        });
-        PollingCheck.waitFor(TIMEOUT, () -> rootView.getRootWindowInsets().isVisible(ime()));
-        getInstrumentation().runOnMainSync(() -> {
-            rootView.getWindowInsetsController().hide(ime());
-        });
-        PollingCheck.waitFor(TIMEOUT, () -> !rootView.getRootWindowInsets().isVisible(ime()));
+            final TestActivity activity = startActivity(TestActivity.class);
+            expectEvent(stream, editorMatcher("onStartInput", activity.mEditTextMarker), TIMEOUT);
+
+            final View rootView = activity.getWindow().getDecorView();
+            getInstrumentation().runOnMainSync(() -> {
+                rootView.getWindowInsetsController().show(ime());
+            });
+            PollingCheck.waitFor(TIMEOUT, () -> rootView.getRootWindowInsets().isVisible(ime()));
+            getInstrumentation().runOnMainSync(() -> {
+                rootView.getWindowInsetsController().hide(ime());
+            });
+            PollingCheck.waitFor(TIMEOUT, () -> !rootView.getRootWindowInsets().isVisible(ime()));
+        }
     }
 
     @Test
@@ -462,13 +480,17 @@
 
     @Test
     public void testShowImeOnCreate() throws Exception {
-        showImeWithHardKeyboardSetting(mObjectTracker);
-
-        final TestShowOnCreateActivity activity = startActivity(TestShowOnCreateActivity.class);
-        final View rootView = activity.getWindow().getDecorView();
-        ANIMATION_CALLBACK.waitForFinishing(TIMEOUT);
-        PollingCheck.waitFor(TIMEOUT,
-                () -> rootView.getRootWindowInsets().isVisible(ime()));
+        final Instrumentation instrumentation = getInstrumentation();
+        assumeThat(MockImeSession.getUnavailabilityReason(instrumentation.getContext()),
+                nullValue());
+        try (MockImeSession imeSession = MockImeSession.create(instrumentation.getContext(),
+                instrumentation.getUiAutomation(), new ImeSettings.Builder())) {
+            final TestShowOnCreateActivity activity = startActivity(TestShowOnCreateActivity.class);
+            final View rootView = activity.getWindow().getDecorView();
+            ANIMATION_CALLBACK.waitForFinishing(TIMEOUT);
+            PollingCheck.waitFor(TIMEOUT,
+                    () -> rootView.getRootWindowInsets().isVisible(ime()));
+        }
     }
 
     @Test
@@ -616,10 +638,11 @@
         }
     }
 
-    private static View setViews(Activity activity) {
+    private static View setViews(Activity activity, @Nullable String privateImeOptions) {
         LinearLayout layout = new LinearLayout(activity);
         View text = new TextView(activity);
         EditText editor = new EditText(activity);
+        editor.setPrivateImeOptions(privateImeOptions);
         layout.addView(text);
         layout.addView(editor);
         activity.setContentView(layout);
@@ -628,11 +651,14 @@
     }
 
     public static class TestActivity extends FocusableActivity {
+        final String mEditTextMarker =
+                getClass().getName() + "/" + SystemClock.elapsedRealtimeNanos();
 
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
-            setViews(this);
+            setViews(this, mEditTextMarker);
+            getWindow().setSoftInputMode(SOFT_INPUT_STATE_HIDDEN);
         }
     }
 
@@ -641,7 +667,7 @@
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
-            View layout = setViews(this);
+            View layout = setViews(this, null /* privateImeOptions */);
             ANIMATION_CALLBACK.reset();
             getWindow().getDecorView().setWindowInsetsAnimationCallback(ANIMATION_CALLBACK);
             getWindow().getInsetsController().hide(statusBars());
@@ -650,11 +676,10 @@
     }
 
     public static class TestShowOnCreateActivity extends FocusableActivity {
-
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
-            View layout = setViews(this);
+            setViews(this, null /* privateImeOptions */);
             ANIMATION_CALLBACK.reset();
             getWindow().getDecorView().setWindowInsetsAnimationCallback(ANIMATION_CALLBACK);
             getWindow().getInsetsController().show(ime());
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 77391b9..7ddc020 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
@@ -215,6 +215,7 @@
     private static Boolean sHasHomeScreen = null;
     private static Boolean sSupportsSystemDecorsOnSecondaryDisplays = null;
     private static Boolean sSupportsInsecureLockScreen = null;
+    private static Boolean sIsAssistantOnTop = null;
     private static boolean sStackTaskLeakFound;
 
     protected static final int INVALID_DEVICE_ROTATION = -1;
@@ -1092,6 +1093,14 @@
         return sSupportsInsecureLockScreen;
     }
 
+    protected boolean isAssistantOnTop() {
+        if (sIsAssistantOnTop == null) {
+            sIsAssistantOnTop = mContext.getResources().getBoolean(
+                    android.R.bool.config_assistantOnTopOfDream);
+        }
+        return sIsAssistantOnTop;
+    }
+
     /**
      * Rotation support is indicated by explicitly having both landscape and portrait
      * features or not listing either at all.
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeEventStreamTestUtils.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeEventStreamTestUtils.java
index f08633f..1b71ff0 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeEventStreamTestUtils.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeEventStreamTestUtils.java
@@ -340,4 +340,21 @@
             throw new RuntimeException("notExpectEvent failed: " + stream.dump(), e);
         }
     }
+
+    /**
+     * Clear all events with  {@code eventName} in given {@code stream} and returns a forked
+     * {@link ImeEventStream} without events with {@code eventName}.
+     * <p>It is used to make sure previous events influence the test. </p>
+     *
+     * @param stream {@link ImeEventStream} to be cleared
+     * @param eventName The targeted cleared event name
+     * @return A forked {@link ImeEventStream} without event with {@code eventName}
+     */
+    public static ImeEventStream clearAllEvents(@NonNull ImeEventStream stream,
+            @NonNull String eventName) {
+        while (stream.seekToFirst(event -> eventName.equals(event.getEventName())).isPresent()) {
+            stream.skip(1);
+        }
+        return stream.copy();
+    }
 }
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java
index 917f7b3..6731e85 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/ImeSettings.java
@@ -52,6 +52,7 @@
     private static final String INLINE_SUGGESTIONS_ENABLED = "InlineSuggestionsEnabled";
     private static final String INLINE_SUGGESTION_VIEW_CONTENT_DESC =
             "InlineSuggestionViewContentDesc";
+    private static final String STRICT_MODE_ENABLED = "StrictModeEnabled";
 
     @NonNull
     private final PersistableBundle mBundle;
@@ -127,6 +128,10 @@
         return mBundle.getString(INLINE_SUGGESTION_VIEW_CONTENT_DESC, defaultValue);
     }
 
+    public boolean isStrictModeEnabled() {
+        return mBundle.getBoolean(STRICT_MODE_ENABLED, false);
+    }
+
     static Bundle serializeToBundle(@NonNull String eventCallbackActionName,
             @Nullable Builder builder) {
         final Bundle result = new Bundle();
@@ -280,5 +285,10 @@
             return this;
         }
 
+        /** Sets whether to enable {@link android.os.StrictMode} or not. */
+        public Builder setStrictModeEnabled(boolean enabled) {
+            mBundle.putBoolean(STRICT_MODE_ENABLED, enabled);
+            return this;
+        }
     }
 }
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
index 5be50de..3acf57b 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
@@ -36,6 +36,7 @@
 import android.os.Looper;
 import android.os.Process;
 import android.os.ResultReceiver;
+import android.os.StrictMode;
 import android.os.SystemClock;
 import android.text.TextUtils;
 import android.util.Log;
@@ -44,6 +45,7 @@
 import android.view.Gravity;
 import android.view.KeyEvent;
 import android.view.View;
+import android.view.ViewConfiguration;
 import android.view.Window;
 import android.view.WindowInsets;
 import android.view.WindowManager;
@@ -59,9 +61,9 @@
 import android.view.inputmethod.InputContentInfo;
 import android.view.inputmethod.InputMethod;
 import android.widget.FrameLayout;
+import android.widget.HorizontalScrollView;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
-import android.widget.HorizontalScrollView;
 import android.widget.TextView;
 import android.widget.inline.InlinePresentationSpec;
 
@@ -288,8 +290,7 @@
                         return ImeEvent.RETURN_VALUE_UNAVAILABLE;
                     }
                     case "getDisplayId":
-                        return getSystemService(WindowManager.class)
-                                .getDefaultDisplay().getDisplayId();
+                        return getDisplay().getDisplayId();
                     case "verifyLayoutInflaterContext":
                         return getLayoutInflater().getContext() == this;
                     case "setHeight":
@@ -299,6 +300,17 @@
                     case "setInlineSuggestionsExtras":
                         mInlineSuggestionsExtras = command.getExtras();
                         return ImeEvent.RETURN_VALUE_UNAVAILABLE;
+                    case "verifyGetDisplay":
+                        Context configContext = createConfigurationContext(new Configuration());
+                        return getDisplay() != null && configContext.getDisplay() != null;
+                    case "verifyGetWindowManager":
+                        configContext = createConfigurationContext(new Configuration());
+                        return getSystemService(WindowManager.class) != null
+                                && configContext.getSystemService(WindowManager.class) != null;
+                    case "verifyGetViewConfiguration":
+                            configContext = createConfigurationContext(new Configuration());
+                            return ViewConfiguration.get(this) != null
+                                    && ViewConfiguration.get(configContext) != null;
                 }
             }
             return ImeEvent.RETURN_VALUE_UNAVAILABLE;
@@ -368,6 +380,16 @@
         mClientPackageName.set(mSettings.getClientPackageName());
         mImeEventActionName.set(mSettings.getEventCallbackActionName());
 
+        // TODO(b/159593676): consider to detect more violations
+        if (mSettings.isStrictModeEnabled()) {
+            StrictMode.setVmPolicy(
+                    new StrictMode.VmPolicy.Builder()
+                            .detectIncorrectContextUse()
+                            .penaltyLog()
+                            .build());
+            StrictMode.setViolationLogger(info -> getTracer().onStrictModeViolated(() -> {}));
+        }
+
         getTracer().onCreate(() -> {
             super.onCreate();
             mHandlerThread.start();
@@ -613,12 +635,7 @@
     @Override
     public void onStartInput(EditorInfo editorInfo, boolean restarting) {
         getTracer().onStartInput(editorInfo, restarting,
-                () -> {
-                    super.onStartInput(editorInfo, restarting);
-                    if (mSettings.getInlineSuggestionsEnabled()) {
-                        maybeClearExistingInlineSuggestions();
-                    }
-                });
+                () -> super.onStartInput(editorInfo, restarting));
     }
 
     @Override
@@ -727,13 +744,6 @@
         final AtomicInteger mInflatedViewCount;
         final AtomicBoolean mValid = new AtomicBoolean(true);
 
-        PendingInlineSuggestions() {
-            mResponse = null;
-            mTotalCount = 0;
-            mViews = null;
-            mInflatedViewCount = null;
-        }
-
         PendingInlineSuggestions(InlineSuggestionsResponse response) {
             mResponse = response;
             mTotalCount = response.getInlineSuggestions().size();
@@ -780,7 +790,9 @@
             }
             mPendingInlineSuggestions = pendingInlineSuggestions;
             if (pendingInlineSuggestions.mTotalCount == 0) {
-                mView.updateInlineSuggestions(pendingInlineSuggestions);
+                if (mView != null) {
+                    mView.updateInlineSuggestions(pendingInlineSuggestions);
+                }
                 return true;
             }
 
@@ -811,15 +823,6 @@
         });
     }
 
-    @MainThread
-    private void maybeClearExistingInlineSuggestions() {
-        if (mPendingInlineSuggestions != null
-                && mPendingInlineSuggestions.mTotalCount > 0) {
-            mView.updateInlineSuggestions(new PendingInlineSuggestions());
-            mPendingInlineSuggestions = null;
-        }
-    }
-
     /**
      * Event tracing helper class for {@link MockIme}.
      */
@@ -1059,5 +1062,10 @@
             return recordEventInternal("onInlineSuggestionsResponse", supplier::getAsBoolean,
                     arguments);
         }
+
+        void onStrictModeViolated(@NonNull Runnable runnable) {
+            final Bundle arguments = new Bundle();
+            recordEventInternal("onStrictModeViolated", runnable, arguments);
+        }
     }
 }
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockImeSession.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockImeSession.java
index 699da4c..5a7d94a 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockImeSession.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockImeSession.java
@@ -1006,4 +1006,19 @@
     public ImeCommand callSetInlineSuggestionsExtras(@NonNull Bundle bundle) {
         return callCommandInternal("setInlineSuggestionsExtras", bundle);
     }
+
+    @NonNull
+    public ImeCommand callVerifyGetDisplay() {
+        return callCommandInternal("verifyGetDisplay", new Bundle());
+    }
+
+    @NonNull
+    public ImeCommand callVerifyGetWindowManager() {
+        return callCommandInternal("verifyGetWindowManager", new Bundle());
+    }
+
+    @NonNull
+    public ImeCommand callVerifyGetViewConfiguration() {
+        return callCommandInternal("verifyGetViewConfiguration", new Bundle());
+    }
 }
diff --git a/tests/media/jni/NativeCodecTestBase.cpp b/tests/media/jni/NativeCodecTestBase.cpp
index 750abe6..b07c1c3 100644
--- a/tests/media/jni/NativeCodecTestBase.cpp
+++ b/tests/media/jni/NativeCodecTestBase.cpp
@@ -528,10 +528,11 @@
 
 int CodecTestBase::getWidth(AMediaFormat* format) {
     int width = -1;
-    int cropLeft, cropRight;
+    int cropLeft, cropRight, cropTop, cropBottom;
     AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &width);
-    if (AMediaFormat_getInt32(format, "crop-left", &cropLeft) &&
-        AMediaFormat_getInt32(format, "crop-right", &cropRight)) {
+    if (AMediaFormat_getRect(format, "crop", &cropLeft, &cropTop, &cropRight, &cropBottom) ||
+        (AMediaFormat_getInt32(format, "crop-left", &cropLeft) &&
+        AMediaFormat_getInt32(format, "crop-right", &cropRight))) {
         width = cropRight + 1 - cropLeft;
     }
     return width;
@@ -539,10 +540,11 @@
 
 int CodecTestBase::getHeight(AMediaFormat* format) {
     int height = -1;
-    int cropTop, cropBottom;
+    int cropLeft, cropRight, cropTop, cropBottom;
     AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &height);
-    if (AMediaFormat_getInt32(format, "crop-top", &cropTop) &&
-        AMediaFormat_getInt32(format, "crop-bottom", &cropBottom)) {
+    if (AMediaFormat_getRect(format, "crop", &cropLeft, &cropTop, &cropRight, &cropBottom) ||
+        (AMediaFormat_getInt32(format, "crop-top", &cropTop) &&
+        AMediaFormat_getInt32(format, "crop-bottom", &cropBottom))) {
         height = cropBottom + 1 - cropTop;
     }
     return height;
diff --git a/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java b/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java
index 3ef2eef..c6b247b 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java
@@ -40,6 +40,7 @@
  * together so that they form a tree.
  */
 public class SensorStats {
+    private static final String TAG = "SensorStats";
     public static final String DELIMITER = "__";
 
     public static final String ERROR = "error";
@@ -146,23 +147,39 @@
         }
     }
 
+    /* Checks if external storage is available for read and write */
+    private boolean isExternalStorageWritable() {
+        String state = Environment.getExternalStorageState();
+        return Environment.MEDIA_MOUNTED.equals(state);
+    }
+
     /**
      * Utility method to log the stats to a file. Will overwrite the file if it already exists.
      */
     public void logToFile(Context context, String fileName) throws IOException {
-        // Only log to file if currently not an Instant App since Instant Apps do not have access to
-        // external storage.
-        if (!context.getPackageManager().isInstantApp()) {
-            File statsDirectory = SensorCtsHelper.getSensorTestDataDirectory("stats/");
-            File logFile = new File(statsDirectory, fileName);
-            final Map<String, Object> flattened = flatten();
-            FileWriter fileWriter = new FileWriter(logFile, false /* append */);
-            try (BufferedWriter writer = new BufferedWriter(fileWriter)) {
-                for (String key : getSortedKeys(flattened)) {
-                    Object value = flattened.get(key);
-                    writer.write(String.format("%s: %s\n", key, getValueString(value)));
+        if (!isExternalStorageWritable()) {
+            Log.w(TAG,
+                "External storage unavailable, skipping log to file: " + fileName);
+            return;
+        }
+
+        try {
+            // Only log to file if currently not an Instant App since Instant Apps do not have access to
+            // external storage.
+            if (!context.getPackageManager().isInstantApp()) {
+                File statsDirectory = SensorCtsHelper.getSensorTestDataDirectory("stats/");
+                File logFile = new File(statsDirectory, fileName);
+                final Map<String, Object> flattened = flatten();
+                FileWriter fileWriter = new FileWriter(logFile, false /* append */);
+                try (BufferedWriter writer = new BufferedWriter(fileWriter)) {
+                    for (String key : getSortedKeys(flattened)) {
+                        Object value = flattened.get(key);
+                        writer.write(String.format("%s: %s\n", key, getValueString(value)));
+                    }
                 }
             }
+        } catch(IOException e) {
+            Log.w(TAG, "Unable to write to file: " + fileName, e);
         }
     }
 
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java b/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java
index 4440010..92e351a 100644
--- a/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java
+++ b/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java
@@ -105,14 +105,11 @@
     private static final String APPOPS_SET_SHELL_COMMAND = "appops set {0} " +
             AppOpsManager.OPSTR_GET_USAGE_STATS + " {1}";
 
-    private static final String USAGE_SOURCE_GET_SHELL_COMMAND = "settings get global " +
-            Settings.Global.APP_TIME_LIMIT_USAGE_SOURCE;
+    private static final String GET_SHELL_COMMAND = "settings get global ";
 
-    private static final String USAGE_SOURCE_SET_SHELL_COMMAND = "settings put global " +
-            Settings.Global.APP_TIME_LIMIT_USAGE_SOURCE + " {0}";
+    private static final String SET_SHELL_COMMAND = "settings put global ";
 
-    private static final String USAGE_SOURCE_DELETE_SHELL_COMMAND = "settings delete global " +
-            Settings.Global.APP_TIME_LIMIT_USAGE_SOURCE;
+    private static final String DELETE_SHELL_COMMAND = "settings delete global ";
 
     private static final String TEST_APP_PKG = "android.app.usage.cts.test1";
     private static final String TEST_APP_CLASS = "android.app.usage.cts.test1.SomeActivity";
@@ -139,6 +136,7 @@
     private KeyguardManager mKeyguardManager;
     private String mTargetPackage;
     private String mCachedUsageSourceSetting;
+    private String mCachedEnableRestrictedBucketSetting;
 
     @Before
     public void setUp() throws Exception {
@@ -152,16 +150,18 @@
 
         assumeTrue("App Standby not enabled on device", AppStandbyUtils.isAppStandbyEnabled());
         setAppOpsMode("allow");
-        mCachedUsageSourceSetting = getUsageSourceSetting();
+        mCachedUsageSourceSetting = getSetting(Settings.Global.APP_TIME_LIMIT_USAGE_SOURCE);
+        mCachedEnableRestrictedBucketSetting = getSetting(Settings.Global.ENABLE_RESTRICTED_BUCKET);
     }
 
     @After
     public void cleanUp() throws Exception {
         if (mCachedUsageSourceSetting != null &&
-            !mCachedUsageSourceSetting.equals(getUsageSourceSetting())) {
+                !mCachedUsageSourceSetting.equals(
+                    getSetting(Settings.Global.APP_TIME_LIMIT_USAGE_SOURCE))) {
             setUsageSourceSetting(mCachedUsageSourceSetting);
-            mUsageStatsManager.forceUsageSourceSettingRead();
         }
+        setSetting(Settings.Global.ENABLE_RESTRICTED_BUCKET, mCachedEnableRestrictedBucketSetting);
         // Force stop test package to avoid any running test code from carrying over to the next run
         SystemUtil.runWithShellPermissionIdentity(() -> mAm.forceStopPackage(TEST_APP_PKG));
         mUiDevice.pressHome();
@@ -179,16 +179,20 @@
         executeShellCmd(MessageFormat.format(APPOPS_SET_SHELL_COMMAND, mTargetPackage, mode));
     }
 
-    private String getUsageSourceSetting() throws Exception {
-        return executeShellCmd(USAGE_SOURCE_GET_SHELL_COMMAND);
+    private String getSetting(String name) throws Exception {
+        return executeShellCmd(GET_SHELL_COMMAND + name);
     }
 
-    private void setUsageSourceSetting(String usageSource) throws Exception {
-        if (usageSource.equals("null")) {
-            executeShellCmd(USAGE_SOURCE_DELETE_SHELL_COMMAND);
+    private void setSetting(String name, String setting) throws Exception {
+        if (setting == null || setting.equals("null")) {
+            executeShellCmd(DELETE_SHELL_COMMAND + name);
         } else {
-            executeShellCmd(MessageFormat.format(USAGE_SOURCE_SET_SHELL_COMMAND, usageSource));
+            executeShellCmd(SET_SHELL_COMMAND + name + " " + setting);
         }
+    }
+
+    private void setUsageSourceSetting(String value) throws Exception {
+        setSetting(Settings.Global.APP_TIME_LIMIT_USAGE_SOURCE, value);
         mUsageStatsManager.forceUsageSourceSettingRead();
     }
 
@@ -683,7 +687,9 @@
     // TODO(148887416): get this test to work for instant apps
     @AppModeFull(reason = "Test APK Activity not found when installed as an instant app")
     @Test
-    public void testUserForceIntoRestricted() throws IOException {
+    public void testUserForceIntoRestricted() throws Exception {
+        setSetting(Settings.Global.ENABLE_RESTRICTED_BUCKET, "1");
+
         launchSubActivity(TaskRootActivity.class);
         assertEquals("Activity launch didn't bring app up to ACTIVE bucket",
                 UsageStatsManager.STANDBY_BUCKET_ACTIVE,
@@ -700,7 +706,28 @@
     // TODO(148887416): get this test to work for instant apps
     @AppModeFull(reason = "Test APK Activity not found when installed as an instant app")
     @Test
-    public void testUserLaunchRemovesFromRestricted() throws IOException {
+    public void testUserForceIntoRestricted_BucketDisabled() throws Exception {
+        setSetting(Settings.Global.ENABLE_RESTRICTED_BUCKET, "0");
+
+        launchSubActivity(TaskRootActivity.class);
+        assertEquals("Activity launch didn't bring app up to ACTIVE bucket",
+                UsageStatsManager.STANDBY_BUCKET_ACTIVE,
+                mUsageStatsManager.getAppStandbyBucket(mTargetPackage));
+
+        // User force shouldn't have to deal with the timeout.
+        setStandByBucket(mTargetPackage, "restricted");
+        assertNotEquals("User was able to force into RESTRICTED bucket when bucket disabled",
+                UsageStatsManager.STANDBY_BUCKET_RESTRICTED,
+                mUsageStatsManager.getAppStandbyBucket(mTargetPackage));
+
+    }
+
+    // TODO(148887416): get this test to work for instant apps
+    @AppModeFull(reason = "Test APK Activity not found when installed as an instant app")
+    @Test
+    public void testUserLaunchRemovesFromRestricted() throws Exception {
+        setSetting(Settings.Global.ENABLE_RESTRICTED_BUCKET, "1");
+
         setStandByBucket(mTargetPackage, "restricted");
         assertEquals("User was unable to force an app into RESTRICTED bucket",
                 UsageStatsManager.STANDBY_BUCKET_RESTRICTED,
@@ -712,6 +739,26 @@
                 mUsageStatsManager.getAppStandbyBucket(mTargetPackage));
     }
 
+    /** Confirm the default value of {@link Settings.Global.ENABLE_RESTRICTED_BUCKET}. */
+    // TODO(148887416): get this test to work for instant apps
+    @AppModeFull(reason = "Test APK Activity not found when installed as an instant app")
+    @Test
+    public void testDefaultEnableRestrictedBucketOff() throws Exception {
+        setSetting(Settings.Global.ENABLE_RESTRICTED_BUCKET, null);
+
+        launchSubActivity(TaskRootActivity.class);
+        assertEquals("Activity launch didn't bring app up to ACTIVE bucket",
+                UsageStatsManager.STANDBY_BUCKET_ACTIVE,
+                mUsageStatsManager.getAppStandbyBucket(mTargetPackage));
+
+        // User force shouldn't have to deal with the timeout.
+        setStandByBucket(mTargetPackage, "restricted");
+        assertNotEquals("User was able to force into RESTRICTED bucket when bucket disabled",
+                UsageStatsManager.STANDBY_BUCKET_RESTRICTED,
+                mUsageStatsManager.getAppStandbyBucket(mTargetPackage));
+
+    }
+
     // TODO(148887416): get this test to work for instant apps
     @AppModeFull(reason = "Test APK Activity not found when installed as an instant app")
     @Test
diff --git a/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AppOpsUserService.kt b/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AppOpsUserService.kt
index 832eb49..100b9af 100644
--- a/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AppOpsUserService.kt
+++ b/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AppOpsUserService.kt
@@ -107,10 +107,10 @@
 
                     setNotedAppOpsCollector()
 
-                    assertThat(asyncNoted).isEmpty()
+                    assertThat(noted).isEmpty()
                     assertThat(selfNoted).isEmpty()
                     eventually {
-                        assertThat(noted.map { it.first.op }).containsExactly(OPSTR_COARSE_LOCATION)
+                        assertThat(asyncNoted.map { it.op }).containsExactly(OPSTR_COARSE_LOCATION)
                     }
                 }
             }
diff --git a/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt b/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt
index 222059f..3dd5c21 100644
--- a/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt
+++ b/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt
@@ -21,6 +21,8 @@
 
 class AutoClosingActivity : Activity() {
     override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+
         finish()
     }
 }
diff --git a/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt b/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
index 1d14a77..9f785b8 100644
--- a/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
@@ -29,7 +29,6 @@
 private const val APK_PATH = "/data/local/tmp/cts/appops/"
 
 private const val APP_PKG = "android.app.appops.cts.apptocollect"
-private const val MESSAGE = "Stack trace message"
 
 @AppModeFull(reason = "Test relies on seeing other apps. Instant apps can't see other apps")
 class RuntimeMessageCollectionTest {
@@ -58,7 +57,7 @@
             val start = System.currentTimeMillis()
             runWithShellPermissionIdentity {
                 appOpsManager.noteOp(AppOpsManager.OPSTR_READ_CONTACTS, appUid, APP_PKG,
-                        TEST_ATTRIBUTION_TAG, MESSAGE)
+                        TEST_ATTRIBUTION_TAG, null)
             }
             while (System.currentTimeMillis() - start < TIMEOUT_MILLIS) {
                 sleep(200)
@@ -71,7 +70,7 @@
                         assertThat(message.op).isEqualTo(AppOpsManager.OPSTR_READ_CONTACTS)
                         assertThat(message.uid).isEqualTo(appUid)
                         assertThat(message.attributionTag).isEqualTo(TEST_ATTRIBUTION_TAG)
-                        assertThat(message.message).isEqualTo(MESSAGE)
+                        assertThat(message.message).isNotNull()
                         return
                     }
                 }
diff --git a/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java b/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
index 8e6adcc..9383460 100644
--- a/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
@@ -47,6 +47,9 @@
 @RunWith(AndroidJUnit4.class)
 public class CarAppFocusManagerTest extends CarApiTestBase {
     private static final String TAG = CarAppFocusManagerTest.class.getSimpleName();
+
+    private static final long NO_EVENT_WAIT_TIME_MS = 50;
+
     private final Context mContext =
             InstrumentationRegistry.getInstrumentation().getTargetContext();
     private CarAppFocusManager mManager;
@@ -150,6 +153,7 @@
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
         assertTrue(mManager.isOwningFocus(owner, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
         assertFalse(manager2.isOwningFocus(owner2, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
+        // should update as it became active
         assertTrue(change2.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
                 CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
         assertTrue(change.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
@@ -163,34 +167,38 @@
         Assert.assertArrayEquals(expectedFocuses, mManager.getActiveAppTypes());
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
 
-        // this should be no-op
         change.reset();
         change2.reset();
         assertEquals(CarAppFocusManager.APP_FOCUS_REQUEST_SUCCEEDED,
                 mManager.requestAppFocus(CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, owner));
         assertTrue(owner.waitForOwnershipGrantAndAssert(
                 DEFAULT_WAIT_TIMEOUT_MS, APP_FOCUS_TYPE_NAVIGATION));
-
         Assert.assertArrayEquals(expectedFocuses, mManager.getActiveAppTypes());
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
+        // The same owner requesting again triggers update
         assertTrue(change2.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
                 CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
         assertTrue(change.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
                 CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
 
+        change.reset();
+        change2.reset();
         assertEquals(CarAppFocusManager.APP_FOCUS_REQUEST_SUCCEEDED,
                 manager2.requestAppFocus(CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, owner2));
         assertTrue(owner2.waitForOwnershipGrantAndAssert(
                 DEFAULT_WAIT_TIMEOUT_MS, APP_FOCUS_TYPE_NAVIGATION));
-
         assertFalse(mManager.isOwningFocus(owner, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
         assertTrue(manager2.isOwningFocus(owner2, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
         Assert.assertArrayEquals(expectedFocuses, mManager.getActiveAppTypes());
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
         assertTrue(owner.waitForOwnershipLossAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
                 CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
+        // ownership change should send update
+        assertTrue(change2.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
+                CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
+        assertTrue(change.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
+                CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
 
-        // no-op as it is not owning it
         change.reset();
         change2.reset();
         mManager.abandonAppFocus(owner, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION);
@@ -198,15 +206,19 @@
         assertTrue(manager2.isOwningFocus(owner2, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
         Assert.assertArrayEquals(expectedFocuses, mManager.getActiveAppTypes());
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
+        // abandoning from non-owner should not trigger update
+        assertFalse(change2.waitForFocusChangedAndAssert(NO_EVENT_WAIT_TIME_MS,
+                CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
+        assertFalse(change.waitForFocusChangedAndAssert(NO_EVENT_WAIT_TIME_MS,
+                CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
 
-        change.reset();
-        change2.reset();
         assertFalse(mManager.isOwningFocus(owner, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
         assertTrue(manager2.isOwningFocus(owner2, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION));
         expectedFocuses = new int[] {CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION};
         Assert.assertArrayEquals(expectedFocuses, mManager.getActiveAppTypes());
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
 
+        manager2.removeFocusListener(change2);
         change.reset();
         change2.reset();
         manager2.abandonAppFocus(owner2, CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION);
@@ -215,10 +227,14 @@
         expectedFocuses = emptyFocus;
         Assert.assertArrayEquals(expectedFocuses, mManager.getActiveAppTypes());
         Assert.assertArrayEquals(expectedFocuses, manager2.getActiveAppTypes());
+        // abandoning from owner should trigger update
         assertTrue(change.waitForFocusChangedAndAssert(DEFAULT_WAIT_TIMEOUT_MS,
                 CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, false));
+        // removed focus listener should not get events
+        assertFalse(change2.waitForFocusChangedAndAssert(NO_EVENT_WAIT_TIME_MS,
+                CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, true));
         mManager.removeFocusListener(change);
-        manager2.removeFocusListener(change2);
+
     }
 
     @Test
@@ -304,6 +320,7 @@
         public void reset() {
             mLastChangeAppType = 0;
             mLastChangeAppActive = false;
+            mChangeWait.drainPermits();
         }
 
         @Override
diff --git a/tests/tests/content/src/android/content/pm/cts/FeatureTest.java b/tests/tests/content/src/android/content/pm/cts/FeatureTest.java
index 99d7268..beab1c4 100644
--- a/tests/tests/content/src/android/content/pm/cts/FeatureTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/FeatureTest.java
@@ -76,6 +76,11 @@
             return;
         }
 
+        // Skip the tests for low-RAM devices
+        if (mActivityManager.isLowRamDevice()) {
+            return;
+        }
+
         fail("Device should support managed profiles, but "
                 + PackageManager.FEATURE_MANAGED_USERS + " is not enabled");
     }
diff --git a/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java b/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java
index ba6a589..75f7cc4 100644
--- a/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java
@@ -268,8 +268,11 @@
         });
         readFromProcess.start();
 
-        installPackage(TEST_APK);
-        assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+        for (int i = 0; i < 3; ++i) {
+            installPackage(TEST_APK);
+            assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+            uninstallPackageSilently(TEST_APP_PACKAGE);
+        }
 
         readFromProcess.join();
         assertNotEquals(0, result.size());
diff --git a/tests/tests/deviceconfig/AndroidManifest.xml b/tests/tests/deviceconfig/AndroidManifest.xml
index ee3a34c..eafb00a 100755
--- a/tests/tests/deviceconfig/AndroidManifest.xml
+++ b/tests/tests/deviceconfig/AndroidManifest.xml
@@ -22,6 +22,12 @@
         <uses-library android:name="android.test.runner" />
     </application>
 
+    <!--
+       - Must set INTERACT_ACROSS_USERS because DeviceConfig always run as user 0, and the CTS tests
+       - might be running as a secondary user
+      -->
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
+
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
                      android:targetPackage="android.deviceconfig.cts"
                      android:label="CTS tests for DeviceConfig API">
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
index 15fb469..6d77ebb 100644
--- a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
@@ -189,8 +189,8 @@
             violations.append("DeviceConfig.setProperties() for public namespaces must not be "
                     + " accessible without WRITE_DEVICE_CONFIG permission\n");
         } catch (DeviceConfig.BadConfigException e) {
-            violations.append("DeviceConfig.setProperties() should not throw BadConfigException "
-                    + "without a known bad configuration.");
+            addExceptionToViolations(violations, "DeviceConfig.setProperties() should not throw "
+                    + "BadConfigException without a known bad configuration", e);
         } catch (SecurityException e) {
         }
 
@@ -200,8 +200,8 @@
         try {
             DeviceConfig.setProperty(PUBLIC_NAMESPACE, KEY, VALUE, /*makeDefault=*/ false);
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.setProperty() must be accessible with"
-                    + " WRITE_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.setProperty() must be accessible "
+                    + "with WRITE_DEVICE_CONFIG permission", e);
         }
 
         try {
@@ -209,11 +209,11 @@
                     new Properties.Builder(PUBLIC_NAMESPACE).setString(KEY, VALUE).build();
             DeviceConfig.setProperties(properties);
         } catch (DeviceConfig.BadConfigException e) {
-            violations.append("DeviceConfig.setProperties() should not throw BadConfigException"
-                    + " without a known bad configuration.");
+            addExceptionToViolations(violations, "DeviceConfig.setProperties() should not throw "
+                    + "BadConfigException without a known bad configuration", e);
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.setProperties() must be accessible with"
-                    + " WRITE_DEVICE_CONFIG permission.\n");
+            addExceptionToViolations(violations, "DeviceConfig.setProperties() must be accessible "
+                    + "with WRITE_DEVICE_CONFIG permission", e);
         }
 
         try {
@@ -221,8 +221,8 @@
             assertEquals("Value read from DeviceConfig API public namespace does not match written"
                     + " value.", VALUE, property);
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.getProperty() for public namespaces must be accessible "
-                    + "without READ_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.getProperty() for public namespaces "
+                    + "must be accessible without READ_DEVICE_CONFIG permission", e);
         }
 
         try {
@@ -230,16 +230,17 @@
             assertEquals("Value read from DeviceConfig API public namespace does not match written"
                     + " value.", VALUE, properties.getString(KEY, "default_value"));
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.getProperties() for public namespaces must be "
-                    + "accessible without READ_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.getProperties() for public "
+                    + "namespaces must be accessible without READ_DEVICE_CONFIG permission", e);
         }
 
         try {
             DeviceConfig.addOnPropertiesChangedListener(
                     PUBLIC_NAMESPACE, EXECUTOR, new TestOnPropertiesListener());
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.addOnPropertiesChangeListener() for public namespaces "
-                    + "must be accessible without READ_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.addOnPropertiesChangeListener() for "
+                    + "public namespaces must be accessible without READ_DEVICE_CONFIG permission",
+                    e);
         }
 
         // Bail if we found any violations
@@ -271,8 +272,8 @@
             violations.append("DeviceConfig.setProperties() must not be accessible without "
                     + "WRITE_DEVICE_CONFIG permission.\n");
         } catch (DeviceConfig.BadConfigException e) {
-            violations.append("DeviceConfig.setProperties() should not throw BadConfigException "
-                    + "without a known bad configuration.");
+            addExceptionToViolations(violations, "DeviceConfig.setProperties() should not throw "
+                    + "BadConfigException without a known bad configuration.", e);
         } catch (SecurityException e) {
         }
     }
@@ -309,8 +310,8 @@
         try {
             DeviceConfig.setProperty(NAMESPACE, KEY, VALUE, /*makeDefault=*/ false);
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.setProperty() must be accessible with"
-                    + " WRITE_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.setProperty() must be accessible "
+                    + "with WRITE_DEVICE_CONFIG permission", e);
         }
     }
 
@@ -323,8 +324,8 @@
             violations.append("DeviceConfig.setProperties() should not throw BadConfigException"
                     + " without a known bad configuration.");
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.setProperties() must be accessible with"
-                    + " WRITE_DEVICE_CONFIG permission.\n");
+            addExceptionToViolations(violations, "DeviceConfig.setProperties() must be accessible "
+                    + "with WRITE DEVICE_CONFIG permission", e);
         }
     }
 
@@ -333,8 +334,8 @@
         try {
             property = DeviceConfig.getProperty(NAMESPACE, KEY);
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.getProperty() must be accessible with"
-                    + " READ_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.getProperty() must be accessible "
+                    + "with READ_DEVICE_CONFIG permission", e);
         }
         return property;
     }
@@ -344,8 +345,8 @@
         try {
             properties = DeviceConfig.getProperties(NAMESPACE2);
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.getProperties() must be accessible with"
-                    + " READ_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.getProperties() must be accessible "
+                    + "with READ_DEVICE_CONFIG permission", e);
         }
         return properties;
     }
@@ -355,8 +356,13 @@
             DeviceConfig.addOnPropertiesChangedListener(
                     NAMESPACE, EXECUTOR, new TestOnPropertiesListener());
         } catch (SecurityException e) {
-            violations.append("DeviceConfig.addOnPropertiesChangeListener() must be accessible with"
-                    + " READ_DEVICE_CONFIG permission\n");
+            addExceptionToViolations(violations, "DeviceConfig.addOnPropertiesChangeListener() must"
+                    + " be accessible with READ_DEVICE_CONFIG permission", e);
         }
     }
+
+    private static void addExceptionToViolations(StringBuilder violations, String message,
+            Exception e) {
+        violations.append(message).append(": ").append(e).append("\n");
+    }
 }
diff --git a/tests/tests/display/src/android/display/cts/DisplayTest.java b/tests/tests/display/src/android/display/cts/DisplayTest.java
index aeb5ce0..94295e2 100644
--- a/tests/tests/display/src/android/display/cts/DisplayTest.java
+++ b/tests/tests/display/src/android/display/cts/DisplayTest.java
@@ -297,14 +297,12 @@
         assertEquals((float)SECONDARY_DISPLAY_DPI, outMetrics.ydpi, 0.0001f);
     }
 
-    /**
-     * Test that the getFlags method returns no flag bits set for the overlay display.
-     */
+    /** Test that the getFlags method returns expected flag bits set for the overlay display. */
     @Test
     public void testFlags() {
         Display display = getSecondaryDisplay(mDisplayManager.getDisplays());
 
-        assertEquals(Display.FLAG_PRESENTATION, display.getFlags());
+        assertEquals(Display.FLAG_PRESENTATION | Display.FLAG_TRUSTED, display.getFlags());
     }
 
     /**
diff --git a/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java b/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
index 7e29288..2333601 100644
--- a/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
+++ b/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
@@ -44,7 +44,7 @@
                 (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
         Display display = windowManager.getDefaultDisplay();
         mMetrics = new DisplayMetrics();
-        display.getMetrics(mMetrics);
+        display.getRealMetrics(mMetrics);
     }
 
     @Presubmit
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index 2eef41d..e3fbad5 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -430,6 +430,59 @@
         }
     }
 
+    /*
+     * This test performs a round trip en/decryption. It does so while the current thread
+     * is in interrupted state which cannot be signaled to the user of the Java Crypto
+     * API.
+     */
+    public void testEncryptsAndDecryptsInterrupted()
+            throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+        final byte[] originalPlaintext = EmptyArray.BYTE;
+        for (String algorithm : EXPECTED_ALGORITHMS) {
+            for (ImportedKey key : importKatKeys(
+                    algorithm,
+                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT,
+                    false)) {
+                try {
+                    Key encryptionKey = key.getKeystoreBackedEncryptionKey();
+                    byte[] plaintext = truncatePlaintextIfNecessary(
+                            algorithm, encryptionKey, originalPlaintext);
+                    if (plaintext == null) {
+                        // Key is too short to encrypt anything using this transformation
+                        continue;
+                    }
+                    Cipher cipher = Cipher.getInstance(algorithm, provider);
+                    Thread.currentThread().interrupt();
+                    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
+                    AlgorithmParameters params = cipher.getParameters();
+                    byte[] ciphertext = cipher.doFinal(plaintext);
+                    byte[] expectedPlaintext = plaintext;
+                    if ("RSA/ECB/NoPadding".equalsIgnoreCase(algorithm)) {
+                        // RSA decryption without padding left-pads resulting plaintext with NUL
+                        // bytes to the length of RSA modulus.
+                        int modulusLengthBytes = (TestUtils.getKeySizeBits(encryptionKey) + 7) / 8;
+                        expectedPlaintext = TestUtils.leftPadWithZeroBytes(
+                                expectedPlaintext, modulusLengthBytes);
+                    }
+
+                    cipher = Cipher.getInstance(algorithm, provider);
+                    Key decryptionKey = key.getKeystoreBackedDecryptionKey();
+                    cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params);
+                    byte[] actualPlaintext = cipher.doFinal(ciphertext);
+                    assertTrue(Thread.currentThread().interrupted());
+                    MoreAsserts.assertEquals(expectedPlaintext, actualPlaintext);
+                } catch (Throwable e) {
+                    throw new RuntimeException(
+                            "Failed for " + algorithm + " with key " + key.getAlias(),
+                            e);
+                }
+            }
+        }
+    }
+
+
     private boolean isDecryptValid(byte[] expectedPlaintext, byte[] ciphertext, Cipher cipher,
             AlgorithmParameters params, ImportedKey key) {
         try {
diff --git a/tests/tests/media/libmediandkjni/Android.bp b/tests/tests/media/libmediandkjni/Android.bp
index e501daa..becae52 100644
--- a/tests/tests/media/libmediandkjni/Android.bp
+++ b/tests/tests/media/libmediandkjni/Android.bp
@@ -46,7 +46,6 @@
         "native-media-jni.cpp",
         "native_media_utils.cpp",
         "native_media_decoder_source.cpp",
-        "native_media_encoder_jni.cpp",
     ],
     include_dirs: ["system/core/include"],
     shared_libs: [
diff --git a/tests/tests/media/libmediandkjni/native_media_encoder_jni.cpp b/tests/tests/media/libmediandkjni/native_media_encoder_jni.cpp
deleted file mode 100644
index 2333ddd..0000000
--- a/tests/tests/media/libmediandkjni/native_media_encoder_jni.cpp
+++ /dev/null
@@ -1,412 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "NativeMediaEnc"
-
-#include <stddef.h>
-#include <inttypes.h>
-#include <log/log.h>
-
-#include <assert.h>
-#include <jni.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <semaphore.h>
-#include <list>
-#include <memory>
-#include <string>
-
-#include <android/native_window_jni.h>
-
-#include "media/NdkMediaFormat.h"
-#include "media/NdkMediaExtractor.h"
-#include "media/NdkMediaCodec.h"
-#include "media/NdkMediaCrypto.h"
-#include "media/NdkMediaFormat.h"
-#include "media/NdkMediaMuxer.h"
-
-#include "native_media_source.h"
-using namespace Utils;
-
-class NativeEncoder : Thread {
-public:
-
-    NativeEncoder(const std::string&);
-    NativeEncoder(const NativeEncoder&) = delete;
-    ~NativeEncoder();
-    static std::shared_ptr<ANativeWindow> getPersistentSurface();
-    std::shared_ptr<ANativeWindow> getSurface() const;
-
-    Status prepare(std::unique_ptr<RunConfig> config, std::shared_ptr<ANativeWindow> anw = nullptr);
-    Status start();
-    Status waitForCompletion();
-    Status validate();
-
-    Status reset();
-
-protected:
-    void run() override;
-
-private:
-    std::shared_ptr<AMediaCodec> mEnc;
-    std::shared_ptr<ANativeWindow> mLocalSurface; // the one created by createInputSurface()
-    std::string mOutFileName;
-    bool mStarted;
-
-    Stats mStats;
-    std::unique_ptr<RunConfig> mRunConfig;
-
-};
-
-NativeEncoder::NativeEncoder(const std::string& outFileName)
-    : mEnc(nullptr),
-      mLocalSurface(nullptr),
-      mOutFileName(outFileName),
-      mStarted(false) {
-    mRunConfig = nullptr;
-}
-
-NativeEncoder::~NativeEncoder() {
-    mEnc = nullptr;
-    mLocalSurface = nullptr;
-    mRunConfig = nullptr;
-}
-
-//static
-std::shared_ptr<ANativeWindow> NativeEncoder::getPersistentSurface() {
-    ANativeWindow *ps;
-    media_status_t ret = AMediaCodec_createPersistentInputSurface(&ps);
-    if (ret != AMEDIA_OK) {
-        ALOGE("Failed to create persistent surface !");
-        return nullptr;
-    }
-    ALOGI("Encoder: created persistent surface %p", ps);
-    return std::shared_ptr<ANativeWindow>(ps, deleter_ANativeWindow);
-}
-
-std::shared_ptr<ANativeWindow> NativeEncoder::getSurface() const {
-    return mLocalSurface;
-}
-
-Status NativeEncoder::prepare(
-        std::unique_ptr<RunConfig> runConfig, std::shared_ptr<ANativeWindow> surface) {
-    assert(runConfig != nullptr);
-    assert(runConfig->format() != nullptr);
-
-    ALOGI("NativeEncoder::prepare");
-    mRunConfig = std::move(runConfig);
-
-    AMediaFormat *config = mRunConfig->format();
-    ALOGI("Encoder format: %s", AMediaFormat_toString(config));
-
-    const char *mime;
-    AMediaFormat_getString(config, AMEDIAFORMAT_KEY_MIME, &mime);
-
-    AMediaCodec *enc = AMediaCodec_createEncoderByType(mime);
-    mEnc = std::shared_ptr<AMediaCodec>(enc, deleter_AMediaCodec);
-
-    media_status_t status = AMediaCodec_configure(
-            mEnc.get(), config, NULL, NULL /* crypto */, AMEDIACODEC_CONFIGURE_FLAG_ENCODE);
-    if (status != AMEDIA_OK) {
-        ALOGE("failed to configure encoder");
-        return FAIL;
-    }
-
-    if (surface == nullptr) {
-        ANativeWindow *anw;
-        status = AMediaCodec_createInputSurface(mEnc.get(), &anw);
-        mLocalSurface = std::shared_ptr<ANativeWindow>(anw, deleter_ANativeWindow);
-        ALOGI("created input surface = %p", mLocalSurface.get());
-    } else {
-        ALOGI("setting persistent input surface %p", surface.get());
-        status = AMediaCodec_setInputSurface(mEnc.get(), surface.get());
-    }
-
-    return status == AMEDIA_OK ? OK : FAIL;
-}
-
-Status NativeEncoder::start() {
-    ALOGI("starting encoder..");
-
-    media_status_t status = AMediaCodec_start(mEnc.get());
-    if (status != AMEDIA_OK) {
-        ALOGE("failed to start decoder");
-        return FAIL;
-    }
-    if (startThread() != OK) {
-        return FAIL;
-    }
-    mStarted = true;
-    return OK;
-}
-
-Status NativeEncoder::waitForCompletion() {
-    joinThread();
-    ALOGI("encoder done..");
-    return OK;
-}
-
-Status NativeEncoder::validate() {
-    const char *s = AMediaFormat_toString(mRunConfig->format());
-    ALOGI("RESULT: Encoder Output Format: %s", s);
-
-    {
-        int32_t encodedFrames = mStats.frameCount();
-        int32_t inputFrames = mRunConfig->frameCount();
-        ALOGI("RESULT: input frames = %d, Encoded frames = %d",
-                inputFrames, encodedFrames);
-        if (encodedFrames != inputFrames) {
-            ALOGE("RESULT: ERROR: output frame count does not match input");
-            return FAIL;
-        }
-    }
-
-    if (Validator::checkOverallBitrate(mStats, *mRunConfig) != OK) {
-        ALOGE("Overall bitrate check failed!");
-        return FAIL;
-    }
-    if (Validator::checkIntraPeriod(mStats, *mRunConfig) != OK) {
-        ALOGE("I-period check failed!");
-        return FAIL;
-    }
-    if (Validator::checkDynamicKeyFrames(mStats, *mRunConfig) != OK) {
-        ALOGE("Dynamic-I-frame-request check failed!");
-        return FAIL;
-    }
-    if (Validator::checkDynamicBitrate(mStats, *mRunConfig) != OK) {
-        ALOGE("Dynamic-bitrate-update check failed!");
-        return FAIL;
-    }
-
-    return OK;
-}
-
-Status NativeEncoder::reset() {
-
-    mEnc = nullptr;
-    return OK;
-}
-
-void NativeEncoder::run() {
-
-    assert(mRunConfig != nullptr);
-
-    int32_t framesToEncode = mRunConfig->frameCount();
-    auto dynamicParams = mRunConfig->dynamicParams();
-    auto paramItr = dynamicParams.begin();
-    int32_t nFrameCount = 0;
-
-    while (nFrameCount < framesToEncode) {
-        // apply frame-specific settings
-        for (;paramItr != dynamicParams.end()
-                && (*paramItr)->frameNum() <= nFrameCount; ++paramItr) {
-            DParamRef& p = *paramItr;
-            if (p->frameNum() == nFrameCount) {
-                assert(p->param() != nullptr);
-                const char *s = AMediaFormat_toString(p->param());
-                ALOGI("Encoder DynamicParam @frame[%d] - applying setting : %s",
-                        nFrameCount, s);
-                AMediaCodec_setParameters(mEnc.get(), p->param());
-            }
-        }
-
-        AMediaCodecBufferInfo info;
-        int status = AMediaCodec_dequeueOutputBuffer(mEnc.get(), &info, 5000000);
-        if (status >= 0) {
-            ALOGV("got encoded buffer[%d] of size=%d @%lld us flags=%x",
-                    nFrameCount, info.size, (long long)info.presentationTimeUs, info.flags);
-            mStats.add(info);
-            AMediaCodec_releaseOutputBuffer(mEnc.get(), status, false);
-            ++nFrameCount;
-
-            if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
-                ALOGV("saw EOS");
-                break;
-            }
-
-        } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
-        } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
-            std::shared_ptr<AMediaFormat> format = std::shared_ptr<AMediaFormat>(
-                    AMediaCodec_getOutputFormat(mEnc.get()), deleter_AMediaFormat);
-            mStats.setOutputFormat(format);
-            ALOGV("format changed: %s", AMediaFormat_toString(format.get()));
-        } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
-            ALOGE("no frame in 5 seconds, assume stuck");
-            break;
-        } else {
-            ALOGV("Invalid status : %d", status);
-        }
-    }
-
-    ALOGV("Encoder exited !");
-    AMediaCodec_stop(mEnc.get());
-}
-
-static std::shared_ptr<AMediaFormat> createMediaFormat(
-        std::string mime,
-        int32_t w, int32_t h, int32_t colorFormat,
-        int32_t bitrate, float framerate,
-        int32_t i_interval) {
-
-    std::shared_ptr<AMediaFormat> config(AMediaFormat_new(), deleter_AMediaFormat);
-
-    AMediaFormat_setString(config.get(), AMEDIAFORMAT_KEY_MIME, mime.c_str());
-    AMediaFormat_setInt32(config.get(), AMEDIAFORMAT_KEY_WIDTH, w);
-    AMediaFormat_setInt32(config.get(), AMEDIAFORMAT_KEY_HEIGHT, h);
-    AMediaFormat_setFloat(config.get(), AMEDIAFORMAT_KEY_FRAME_RATE, framerate);
-    AMediaFormat_setInt32(config.get(), AMEDIAFORMAT_KEY_BIT_RATE, bitrate);
-    AMediaFormat_setInt32(config.get(), AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, i_interval);
-    AMediaFormat_setInt32(config.get(), AMEDIAFORMAT_KEY_COLOR_FORMAT, colorFormat);
-
-    return config;
-}
-
-static int32_t getOptimalBitrate(int w, int h) {
-    return (w * h <= 640 * 480) ? 1000000 :
-            (w * h <= 1280 * 720) ? 2000000 :
-            (w * h <= 1920 * 1080) ? 6000000 :
-            10000000;
-}
-
-//-----------------------------------------------------------------------------
-// Tests
-//-----------------------------------------------------------------------------
-static bool runNativeEncoderTest(
-        JNIEnv *env, int fd, jlong offset, jlong fileSize,
-        jstring jmime, int w, int h,
-        const std::vector<DParamRef>& dynParams,
-        int32_t numFrames,
-        bool usePersistentSurface) {
-
-    // If dynamic I-frame is requested, set large-enough i-period
-    // so that auto I-frames do not interfere with the ones explicitly requested,
-    // and hence simplify validation.
-    bool hasDynamicSyncRequest = false;
-
-    // If dynamic bitrate updates are requested, set bitrate mode to CBR to
-    // ensure bitrate within 'window of two updates' remains constant
-    bool hasDynamicBitrateChanges = false;
-
-    for (const DParamRef &d : dynParams) {
-        int32_t temp;
-        if (AMediaFormat_getInt32(d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME, &temp)) {
-            hasDynamicSyncRequest = true;
-        } else if (AMediaFormat_getInt32(d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE, &temp)) {
-            hasDynamicBitrateChanges = true;
-        }
-    }
-
-    const char* cmime = env->GetStringUTFChars(jmime, nullptr);
-    std::string mime = cmime;
-    env->ReleaseStringUTFChars(jmime, cmime);
-
-    float fps = 30.0f;
-    std::shared_ptr<AMediaFormat> config = createMediaFormat(
-            mime, w, h, kColorFormatSurface,
-            getOptimalBitrate(w, h),
-            fps,
-            hasDynamicSyncRequest ? numFrames / fps : 1 /*sec*/);
-
-    if (hasDynamicBitrateChanges) {
-        AMediaFormat_setInt32(config.get(), TBD_AMEDIAFORMAT_KEY_BIT_RATE_MODE, kBitrateModeConstant);
-    }
-
-    std::shared_ptr<Source> src = createDecoderSource(
-            w, h, kColorFormatSurface, fps,
-            true /*looping*/,
-            hasDynamicSyncRequest | hasDynamicBitrateChanges, /*regulate feeding rate*/
-            fd, offset, fileSize);
-
-    std::unique_ptr<RunConfig> runConfig = std::make_unique<RunConfig>(numFrames, config);
-    for (const DParamRef &d : dynParams) {
-        runConfig->add(d);
-    }
-
-    std::string debugOutputFileName = "";
-    std::shared_ptr<NativeEncoder> enc(new NativeEncoder(debugOutputFileName));
-
-    if (usePersistentSurface) {
-        std::shared_ptr<ANativeWindow> persistentSurface = enc->getPersistentSurface();
-        enc->prepare(std::move(runConfig), persistentSurface);
-        src->prepare(nullptr /*bufferListener*/, persistentSurface);
-    } else {
-        enc->prepare(std::move(runConfig));
-        src->prepare(nullptr /*bufferListener*/, enc->getSurface());
-    }
-
-    src->start();
-    enc->start();
-
-    enc->waitForCompletion();
-
-    Status status = enc->validate();
-
-    src->stop();
-    enc->reset();
-
-    return status == OK;
-}
-
-extern "C" jboolean Java_android_media_cts_NativeEncoderTest_testEncodeSurfaceNative(
-        JNIEnv *env, jclass /*clazz*/, int fd, jlong offset, jlong fileSize,
-        jstring jmime, int w, int h) {
-
-    std::vector<DParamRef> dynParams;
-    return runNativeEncoderTest(env, fd, offset, fileSize, jmime, w, h,
-            dynParams, 300, false /*usePersistentSurface*/);
-
-}
-
-extern "C" jboolean Java_android_media_cts_NativeEncoderTest_testEncodePersistentSurfaceNative(
-        JNIEnv *env, jclass /*clazz*/, int fd, jlong offset, jlong fileSize,
-        jstring jmime, int w, int h) {
-
-    std::vector<DParamRef> dynParams;
-    return runNativeEncoderTest(env, fd, offset, fileSize, jmime, w, h,
-            dynParams, 300, true /*usePersistentSurface*/);
-}
-
-extern "C" jboolean Java_android_media_cts_NativeEncoderTest_testEncodeSurfaceDynamicSyncFrameNative(
-        JNIEnv *env, jclass /*clazz*/, int fd, jlong offset, jlong fileSize,
-        jstring jmime, int w, int h) {
-
-    std::vector<DParamRef> dynParams;
-    for (int32_t frameNum : {40, 75, 160, 180, 250}) {
-        dynParams.push_back(DynamicParam::newRequestSync(frameNum));
-    }
-
-    return runNativeEncoderTest(env, fd, offset, fileSize, jmime, w, h,
-            dynParams, 300, false /*usePersistentSurface*/);
-}
-
-extern "C" jboolean Java_android_media_cts_NativeEncoderTest_testEncodeSurfaceDynamicBitrateNative(
-        JNIEnv *env, jclass /*clazz*/, int fd, jlong offset, jlong fileSize,
-        jstring jmime, int w, int h) {
-
-    int32_t bitrate = getOptimalBitrate(w, h);
-    std::vector<DParamRef> dynParams;
-
-    dynParams.push_back(DynamicParam::newBitRate(100,  bitrate/2));
-    dynParams.push_back(DynamicParam::newBitRate(200,  3*bitrate/4));
-    dynParams.push_back(DynamicParam::newBitRate(300,  bitrate));
-
-    return runNativeEncoderTest(env, fd, offset, fileSize, jmime, w, h,
-            dynParams, 400, false /*usePersistentSurface*/);
-}
-
diff --git a/tests/tests/media/libmediandkjni/native_media_utils.cpp b/tests/tests/media/libmediandkjni/native_media_utils.cpp
index 7596cbb..21b7f7f 100644
--- a/tests/tests/media/libmediandkjni/native_media_utils.cpp
+++ b/tests/tests/media/libmediandkjni/native_media_utils.cpp
@@ -27,11 +27,6 @@
 
 namespace Utils {
 
-const char * TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME = "request-sync";
-const char * TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE = "video-bitrate";
-
-const char * TBD_AMEDIAFORMAT_KEY_BIT_RATE_MODE = "bitrate-mode";
-
 Status Thread::startThread() {
     assert(mHandle == 0);
     if (pthread_create(&mHandle, nullptr, Thread::thread_wrapper, this) != 0) {
@@ -56,273 +51,4 @@
     return nullptr;
 }
 
-int32_t RunConfig::dynamicParamsOfKind(
-        const char *key, std::vector<DParamRef>& paramsList) const {
-    paramsList.clear();
-    for (const DParamRef& d : mParams) {
-        assert(d->param() != nullptr);
-
-        if (!strncmp(key, TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME,
-                strlen(TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME))) {
-            int32_t tmp;
-            if (AMediaFormat_getInt32(d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME, &tmp)) {
-                paramsList.push_back(d);
-            }
-
-        } else if (!strncmp(key, TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE,
-                strlen(TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE))) {
-            int32_t tmp;
-            if (AMediaFormat_getInt32(d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE, &tmp)) {
-                paramsList.push_back(d);
-            }
-        }
-    }
-    return (int32_t)paramsList.size();
-}
-
-static bool comparePTS(const AMediaCodecBufferInfo& l, const AMediaCodecBufferInfo& r) {
-    return l.presentationTimeUs < r.presentationTimeUs;
-}
-
-int32_t Stats::getBitrateAverage(int32_t frameNumFrom, int32_t frameNumTo) const {
-    int64_t sum = 0;
-    assert(frameNumFrom >= 0 && frameNumTo < mInfos.size());
-    for (int i = frameNumFrom; i < frameNumTo; ++i) {
-        sum += mInfos[i].size;
-    }
-    sum *= 8; // kB -> kb
-
-    auto from = mInfos.begin() + frameNumFrom;
-    auto to = mInfos.begin() + frameNumTo;
-    int64_t duration = (*std::max_element(from, to, comparePTS)).presentationTimeUs
-            - (*std::min_element(from, to, comparePTS)).presentationTimeUs;
-    if (duration <= 0) {
-        return 0;
-    }
-
-    int64_t avg = (sum * 1e6) / duration;
-    return (int32_t)avg;
-}
-
-int32_t Stats::getBitratePeak(
-        int32_t frameNumFrom, int32_t frameNumTo, int32_t windowSize) const {
-    int64_t sum = 0;
-    int64_t maxSum = 0;
-    assert(frameNumFrom >= 0 && frameNumTo < mInfos.size());
-    assert(windowSize < (frameNumTo - frameNumFrom));
-
-    for (int i = frameNumFrom; i < frameNumTo; ++i) {
-        sum += mInfos[i].size;
-        if (i >= windowSize) {
-            sum -= mInfos[i - windowSize].size;
-        }
-        maxSum = sum > maxSum ? sum : maxSum;
-    }
-    maxSum *= 8; // kB -> kb
-    int64_t duration = mInfos[frameNumTo].presentationTimeUs -
-            mInfos[frameNumFrom].presentationTimeUs;
-    if (duration <= 0) {
-        return 0;
-    }
-
-    int64_t peak = (maxSum * 1e6) / duration;
-    return (int32_t)peak;
-}
-
-int32_t Stats::getSyncFrameNext(int32_t frameNumWhence) const {
-    assert(frameNumWhence >= 0 && frameNumWhence < mInfos.size());
-    int i = frameNumWhence;
-    for (; i < (int)mInfos.size(); ++i) {
-        if (mInfos[i].flags & TBD_AMEDIACODEC_BUFFER_FLAG_KEY_FRAME) {
-            return i;
-        }
-    }
-    return -1;
-}
-
-Status Validator::checkOverallBitrate(const Stats &stats, const RunConfig& config) {
-    // skip this check if bitrate was updated dynamically
-    ALOGV("DEBUG: checkOverallBitrate");
-    std::vector<DParamRef> tmp;
-    if (config.dynamicParamsOfKind(TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE, tmp) > 0) {
-        ALOGV("DEBUG: checkOverallBitrate: dynamic bitrate enabled");
-        return OK;
-    }
-
-    int32_t bitrate = 0;
-    if (!AMediaFormat_getInt32(config.format(), AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) {
-        // should not happen
-        ALOGV("DEBUG: checkOverallBitrate: bitrate was not configured !");
-        return FAIL;
-    }
-    assert(bitrate > 0);
-
-    int32_t avgBitrate = stats.getBitrateAverage(0, config.frameCount() - 1);
-    float deviation = (avgBitrate - bitrate) * 100 / bitrate;
-    ALOGI("RESULT: Bitrate expected=%d Achieved=%d Deviation=%.2g%%",
-            bitrate, avgBitrate, deviation);
-
-    if (fabs(deviation) > kBitrateDeviationPercentMax) {
-        ALOGI("RESULT: ERROR: bitrate deviation(%.2g%%) exceeds threshold (+/-%.2g%%)",
-                deviation, kBitrateDeviationPercentMax);
-        return FAIL;
-    }
-
-    // TODO
-    // if bitrate mode was set to CBR, check for peak-bitrate deviation (+/-20%?)
-    return OK;
-}
-
-Status Validator::checkFramerate(const Stats&, const RunConfig&) {
-    // TODO - tricky if frames are reordered
-    return OK;
-}
-
-Status Validator::checkIntraPeriod(const Stats& stats, const RunConfig& config) {
-    float framerate;
-    if (!AMediaFormat_getFloat(config.format(), AMEDIAFORMAT_KEY_FRAME_RATE, &framerate)) {
-        // should not happen
-        ALOGV("DEBUG: checkIntraPeriod: framerate was not configured ! : %s",
-                AMediaFormat_toString(config.format()));
-        return OK;
-    }
-
-    int32_t intraPeriod;
-    if (!AMediaFormat_getInt32(config.format(), AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, &intraPeriod)) {
-        // should not happen
-        ALOGV("DEBUG: checkIntraPeriod: I-period was not configured !");
-        return OK;
-    }
-
-    // TODO: handle special cases
-    // intraPeriod = 0  => all I
-    // intraPeriod < 0  => infinite GOP
-    if (intraPeriod <= 0) {
-        return OK;
-    }
-
-    int32_t iInterval = framerate * intraPeriod;
-
-    if (iInterval >= stats.frameCount()) {
-        ALOGV("RESULT: Intra-period %d exceeds frame-count %d ..skipping",
-                iInterval, stats.frameCount());
-        return OK;
-    }
-
-    int32_t numGopFound = 0;
-    int32_t sumGopDistance = 0;
-    int32_t lastKeyLocation = stats.getSyncFrameNext(0);
-    for (;;) {
-        int32_t nextKeyLocation = stats.getSyncFrameNext(lastKeyLocation + iInterval - kSyncFrameDeviationFramesMax);
-        if (nextKeyLocation < 0) {
-            break;
-        }
-        if (abs(nextKeyLocation - lastKeyLocation - iInterval) > kSyncFrameDeviationFramesMax) {
-            ALOGE("RESULT: ERROR: Intra period at frame %d is %d (expected %d +/-%d)",
-                    lastKeyLocation, nextKeyLocation - lastKeyLocation, iInterval,
-                    kSyncFrameDeviationFramesMax);
-            return FAIL;
-        }
-        ++numGopFound;
-        sumGopDistance += (nextKeyLocation - lastKeyLocation);
-        lastKeyLocation = nextKeyLocation;
-    }
-
-    if (numGopFound) {
-        ALOGI("RESULT: Intra-period: configured=%d frames (%d sec). Actual=%d frames",
-                iInterval, intraPeriod, sumGopDistance / numGopFound);
-    }
-
-    return OK;
-}
-
-Status Validator::checkDynamicKeyFrames(const Stats& stats, const RunConfig& config) {
-    ALOGV("DEBUG: checkDynamicKeyFrames");
-    std::vector<DParamRef> keyRequests;
-    if (config.dynamicParamsOfKind(TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME, keyRequests) <= 0) {
-        ALOGV("DEBUG: dynamic key-frames were not requested");
-        return OK;
-    }
-
-    std::string debugStr = "";
-    bool fail = false;
-    for (DParamRef &d : keyRequests) {
-        int32_t generatedKeyLocation = stats.getSyncFrameNext(d->frameNum());
-        if (generatedKeyLocation - d->frameNum() > kSyncFrameDeviationFramesMax) {
-            ALOGI("RESULT: ERROR: Dynamic sync-frame requested at frame=%d, got at frame=%d",
-                    d->frameNum(), generatedKeyLocation);
-            fail = true;
-        }
-        char tmp[128];
-        snprintf(tmp, 128, " %d/%d,", generatedKeyLocation, d->frameNum());
-        debugStr = debugStr + std::string(tmp);
-    }
-    ALOGI("RESULT: Dynamic Key-frame locations - actual/requested :");
-    ALOGI("RESULT:         %s", debugStr.c_str());
-
-    return fail ? FAIL : OK;
-}
-
-Status Validator::checkDynamicBitrate(const Stats& stats, const RunConfig& config) {
-    // Checking bitrate convergence between two updates makes sense if requested along with CBR
-    // check if CBR mode has been set. If not, simply pass
-    int32_t bitrateMode;
-    if (!AMediaFormat_getInt32(config.format(), TBD_AMEDIAFORMAT_KEY_BIT_RATE_MODE,
-            &bitrateMode) || bitrateMode != kBitrateModeConstant) {
-        ALOGV("DEBUG: checkDynamicBitrate: skipping since CBR not requested");
-        return OK; //skip
-    }
-
-    // check if dynamic bitrates were requested
-    std::vector<DParamRef> bitrateUpdates;
-    if (config.dynamicParamsOfKind(TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE, bitrateUpdates) <= 0) {
-        ALOGV("DEBUG: checkDynamicBitrate: dynamic bitrates not requested !");
-        return OK; //skip
-    }
-    int32_t bitrate = 0;
-    if (!AMediaFormat_getInt32(config.format(), AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) {
-        // should not happen
-        ALOGV("DEBUG: checkDynamicBitrate: bitrate was not configured !");
-        return OK; //skip
-    }
-    assert(bitrate > 0);
-
-    std::string debugStr = "";
-    int32_t lastBitrateUpdateFrameNum = 0;
-    int32_t lastBitrate = bitrate;
-    bool fail = false;
-
-    for (DParamRef &d : bitrateUpdates) {
-        int32_t updatedBitrate = 0;
-        if (!AMediaFormat_getInt32(
-                d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE, &updatedBitrate)) {
-            ALOGE("BUG: expected dynamic bitrate");
-            continue;
-        }
-        assert(updatedBitrate > 0);
-
-        int32_t lastAverage = stats.getBitrateAverage(lastBitrateUpdateFrameNum,  d->frameNum() - 1);
-        float deviation = (lastAverage - lastBitrate) * 100 / lastBitrate;
-
-        if (fabs(deviation) > kBitrateDeviationPercentMax) {
-            ALOGI("RESULT: ERROR: dynamic bitrate deviation(%.2g%%) exceeds threshold (+/-%.2g%%)",
-                    deviation, kBitrateDeviationPercentMax);
-            fail |= true;
-        }
-
-        char tmp[128];
-        snprintf(tmp, 128, "  [%d - %d] %d/%d,",
-                lastBitrateUpdateFrameNum, d->frameNum() - 1, lastAverage, lastBitrate);
-        debugStr = debugStr + std::string(tmp);
-        lastBitrate = updatedBitrate;
-        lastBitrateUpdateFrameNum = d->frameNum();
-    }
-
-    ALOGI("RESULT: Dynamic Bitrates : [from-frame  -  to-frame] actual/expected :");
-    ALOGI("RESULT:        %s", debugStr.c_str());
-
-    return fail ? FAIL : OK;
-}
-
-
 }; // namespace Utils
diff --git a/tests/tests/media/libmediandkjni/native_media_utils.h b/tests/tests/media/libmediandkjni/native_media_utils.h
index 8a1751e..e5842f7 100644
--- a/tests/tests/media/libmediandkjni/native_media_utils.h
+++ b/tests/tests/media/libmediandkjni/native_media_utils.h
@@ -32,20 +32,6 @@
 
 namespace Utils {
 
-// constants not defined in NDK api
-extern const char * TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME;
-extern const char * TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE;
-static const uint32_t TBD_AMEDIACODEC_BUFFER_FLAG_KEY_FRAME = 0x1;
-
-extern const char * TBD_AMEDIAFORMAT_KEY_BIT_RATE_MODE;
-static const int32_t kBitrateModeConstant = 2;
-static const int32_t kColorFormatSurface = 0x7f000789;
-
-// tolerances
-// Keep in sync with the variation at src/android/media/cts/VideoCodecTest.java
-static const float kBitrateDeviationPercentMax = 20.0;
-static const int32_t kSyncFrameDeviationFramesMax = 5;
-
 enum Status : int32_t {
     FAIL = -1,
     OK = 0,
@@ -92,117 +78,6 @@
     ANativeWindow_release(_a);
 }
 
-/*
- * Dynamic paramater that will be applied via AMediaCodec_setParamater(..)
- *  during the encoding process, at the given frame number
- */
-struct DynamicParam {
-    DynamicParam() = delete;
-    DynamicParam(const DynamicParam&) = delete;
-    ~DynamicParam() = default;
-
-    static std::shared_ptr<DynamicParam> newBitRate(int atFrame, int32_t bitrate) {
-        DynamicParam *d = new DynamicParam(atFrame);
-        AMediaFormat_setInt32(d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_VIDEO_BITRATE, bitrate);
-        return std::shared_ptr<DynamicParam>(d);
-    }
-    static std::shared_ptr<DynamicParam> newRequestSync(int atFrame) {
-        DynamicParam *d = new DynamicParam(atFrame);
-        AMediaFormat_setInt32(d->param(), TBD_AMEDIACODEC_PARAMETER_KEY_REQUEST_SYNC_FRAME, 0 /*ignore*/);
-        return std::shared_ptr<DynamicParam>(d);
-    }
-
-    inline int frameNum() const {
-        return mFrameNum;
-    }
-    inline AMediaFormat *param() const {
-        return mParam.get();
-    }
-
-private:
-    DynamicParam(int _at)
-        : mFrameNum(_at) {
-        mParam = std::shared_ptr<AMediaFormat>(AMediaFormat_new(), deleter_AMediaFormat);
-    }
-
-    int mFrameNum;
-    std::shared_ptr<AMediaFormat> mParam;
-};
-
-using DParamRef = std::shared_ptr<DynamicParam>;
-
-/*
- * Configuration to the encoder (static + dynamic)
- */
-struct RunConfig {
-    RunConfig(const RunConfig&) = delete;
-    RunConfig(int32_t numFramesToEncode, std::shared_ptr<AMediaFormat> staticParams)
-        : mNumFramesToEncode (numFramesToEncode),
-          mStaticParams(staticParams) {
-    }
-    void add(const DParamRef& p) {
-        mParams.push_back(p);
-    }
-
-    AMediaFormat* format() const {
-        return mStaticParams.get();
-    }
-    const std::vector<DParamRef>& dynamicParams() const {
-        return mParams;
-    }
-    int32_t frameCount() const {
-        return mNumFramesToEncode;
-    }
-    int32_t dynamicParamsOfKind(
-        const char *key, std::vector<DParamRef>& ) const;
-
-private:
-    int32_t mNumFramesToEncode;
-    std::vector<DParamRef> mParams;
-    std::shared_ptr<AMediaFormat> mStaticParams;
-};
-
-/*
- * Encoded output statistics
- * provides helpers to compute windowed average of bitrate and search for I-frames
- */
-struct Stats {
-    Stats() = default;
-    Stats(const Stats&) = delete;
-    void add(const AMediaCodecBufferInfo &info) {
-        mInfos.push_back(info);
-    }
-    void setOutputFormat(std::shared_ptr<AMediaFormat> fmt) {
-        mOutputFormat = fmt;
-    }
-    int32_t frameCount() const {
-        return (int32_t)mInfos.size();
-    }
-    const std::vector<AMediaCodecBufferInfo>& infos() const {
-        return mInfos;
-    }
-
-    int32_t getBitrateAverage(int32_t frameNumFrom, int32_t frameNumTo) const;
-    int32_t getBitratePeak(int32_t frameNumFrom, int32_t frameNumTo, int32_t windowSize) const;
-    int32_t getSyncFrameNext(int32_t frameNumWhence) const;
-
-private:
-    std::vector<AMediaCodecBufferInfo> mInfos;
-    std::shared_ptr<AMediaFormat> mOutputFormat;
-};
-
-/*
- * Helpers to validate output (Stats) based on expected settings (RunConfig)
- * Check for validity of both static and dynamic settings
- */
-struct Validator {
-    static Status checkOverallBitrate(const Stats&, const RunConfig&);
-    static Status checkFramerate(const Stats&, const RunConfig&);
-    static Status checkIntraPeriod(const Stats&, const RunConfig&);
-    static Status checkDynamicKeyFrames(const Stats&, const RunConfig&);
-    static Status checkDynamicBitrate(const Stats&, const RunConfig&);
-};
-
 }; //namespace Utils
 
 #endif // _NATIVE_MEDIA_UTILS_H_
diff --git a/tests/tests/media/src/android/media/cts/DecoderTest.java b/tests/tests/media/src/android/media/cts/DecoderTest.java
index 3541454..62c6012 100644
--- a/tests/tests/media/src/android/media/cts/DecoderTest.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTest.java
@@ -1691,8 +1691,12 @@
     }
 
     private List<String> codecsFor(int resource) throws IOException {
+        return codecsFor(resource, mResources);
+    }
+
+    protected static List<String> codecsFor(int resource, Resources resources) throws IOException {
         MediaExtractor ex = new MediaExtractor();
-        AssetFileDescriptor fd = mResources.openRawResourceFd(resource);
+        AssetFileDescriptor fd = resources.openRawResourceFd(resource);
         try {
             ex.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
         } finally {
diff --git a/tests/tests/media/src/android/media/cts/DecoderTestAacDrc.java b/tests/tests/media/src/android/media/cts/DecoderTestAacDrc.java
index 8032988..0263601 100755
--- a/tests/tests/media/src/android/media/cts/DecoderTestAacDrc.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTestAacDrc.java
@@ -586,10 +586,8 @@
                 if (drcParams.mDecoderTargetLevel != 0) {
                     final int targetLevelFromCodec = codec.getOutputFormat()
                             .getInteger(MediaFormat.KEY_AAC_DRC_TARGET_REFERENCE_LEVEL);
-                    if (false) { // TODO disabled until b/157773721 fixed
-                        if (targetLevelFromCodec != drcParams.mDecoderTargetLevel) {
-                            fail("Drc Target Reference Level received from MediaCodec is not the Target Reference Level set");
-                        }
+                    if (targetLevelFromCodec != drcParams.mDecoderTargetLevel) {
+                        fail("DRC Target Ref Level received from MediaCodec is not the level set");
                     }
                 }
             }
@@ -711,12 +709,20 @@
             if (drcParams.mDecoderTargetLevel != 0) {
                 final int targetLevelFromCodec = codec.getOutputFormat()
                         .getInteger(MediaFormat.KEY_AAC_DRC_TARGET_REFERENCE_LEVEL);
-                if (false) { // TODO disabled until b/157773721 fixed
-                    if (targetLevelFromCodec != drcParams.mDecoderTargetLevel) {
-                        fail("Drc Target Reference Level received from MediaCodec is not the Target Reference Level set");
-                    }
+                if (targetLevelFromCodec != drcParams.mDecoderTargetLevel) {
+                    fail("DRC Target Ref Level received from MediaCodec is not the level set");
                 }
             }
+
+            final MediaFormat outputFormat = codec.getOutputFormat();
+            final int cutFromCodec = outputFormat.getInteger(
+                    MediaFormat.KEY_AAC_DRC_ATTENUATION_FACTOR);
+            assertEquals("Attenuation factor received from MediaCodec differs from set:",
+                    drcParams.mCut, cutFromCodec);
+            final int boostFromCodec = outputFormat.getInteger(
+                    MediaFormat.KEY_AAC_DRC_BOOST_FACTOR);
+            assertEquals("Boost factor received from MediaCodec differs from set:",
+                    drcParams.mBoost, boostFromCodec);
         }
 
         // expectedOutputLoudness == -2 indicates that output loudness is not tested
diff --git a/tests/tests/media/src/android/media/cts/DecoderTestAacFormat.java b/tests/tests/media/src/android/media/cts/DecoderTestAacFormat.java
new file mode 100755
index 0000000..4e9c43e
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/DecoderTestAacFormat.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.app.Instrumentation;
+import android.content.res.AssetFileDescriptor;
+import android.content.res.Resources;
+import android.media.MediaCodec;
+import android.media.MediaExtractor;
+import android.media.MediaFormat;
+import android.media.cts.DecoderTest.AudioParameter;
+import android.media.cts.R;
+import android.os.Build;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.ApiLevelUtil;
+import com.android.compatibility.common.util.MediaUtils;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
+public class DecoderTestAacFormat {
+    private static final String TAG = "DecoderTestAacFormat";
+
+    private static final boolean sIsAndroidRAndAbove =
+            ApiLevelUtil.isAtLeast(Build.VERSION_CODES.R);
+
+    private Resources mResources;
+
+    @Before
+    public void setUp() throws Exception {
+        final Instrumentation inst = InstrumentationRegistry.getInstrumentation();
+        assertNotNull(inst);
+        mResources = inst.getContext().getResources();
+    }
+
+    /**
+     * Verify downmixing to stereo at decoding of MPEG-4 HE-AAC 5.0 and 5.1 channel streams
+     */
+    @Test
+    public void testHeAacM4aMultichannelDownmix() throws Exception {
+        Log.i(TAG, "START testDecodeHeAacMcM4a");
+
+        if (!MediaUtils.check(sIsAndroidRAndAbove, "M-chan downmix fixed in Android R"))
+            return;
+
+        // array of multichannel resources with their expected number of channels without downmixing
+        int[][] samples = {
+                //  {resourceId, numChannels},
+                {R.raw.noise_5ch_48khz_aot5_dr_sbr_sig1_mp4, 5},
+                {R.raw.noise_6ch_44khz_aot5_dr_sbr_sig2_mp4, 6},
+        };
+        for (int[] sample: samples) {
+            for (String codecName : DecoderTest.codecsFor(sample[0] /* resource */, mResources)) {
+                // verify correct number of channels is observed without downmixing
+                AudioParameter chanParams = new AudioParameter();
+                decodeUpdateFormat(codecName, sample[0] /*resource*/, chanParams, 0 /*no downmix*/);
+                assertEquals("Number of channels differs for codec:" + codecName,
+                        sample[1], chanParams.getNumChannels());
+
+                // verify correct number of channels is observed when downmixing to stereo
+                AudioParameter downmixParams = new AudioParameter();
+                decodeUpdateFormat(codecName, sample[0] /* resource */, downmixParams,
+                        2 /*stereo downmix*/);
+                assertEquals("Number of channels differs for codec:" + codecName,
+                        2, downmixParams.getNumChannels());
+
+            }
+        }
+    }
+
+    /**
+     *
+     * @param decoderName
+     * @param testInput
+     * @param audioParams
+     * @param downmixChannelCount 0 if no downmix requested,
+     *                           positive number for number of channels in requested downmix
+     * @throws IOException
+     */
+    private void decodeUpdateFormat(String decoderName, int testInput, AudioParameter audioParams,
+            int downmixChannelCount)
+            throws IOException
+    {
+        AssetFileDescriptor testFd = mResources.openRawResourceFd(testInput);
+
+        MediaExtractor extractor = new MediaExtractor();
+        extractor.setDataSource(testFd.getFileDescriptor(), testFd.getStartOffset(),
+                testFd.getLength());
+        testFd.close();
+
+        assertEquals("wrong number of tracks", 1, extractor.getTrackCount());
+        MediaFormat format = extractor.getTrackFormat(0);
+        String mime = format.getString(MediaFormat.KEY_MIME);
+        assertTrue("not an audio file", mime.startsWith("audio/"));
+
+        MediaCodec decoder;
+        if (decoderName == null) {
+            decoder = MediaCodec.createDecoderByType(mime);
+        } else {
+            decoder = MediaCodec.createByCodecName(decoderName);
+        }
+
+        MediaFormat configFormat = format;
+        if (downmixChannelCount > 0) {
+            configFormat.setInteger(
+                    MediaFormat.KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT, downmixChannelCount);
+        }
+
+        Log.v(TAG, "configuring with " + configFormat);
+        decoder.configure(configFormat, null /* surface */, null /* crypto */, 0 /* flags */);
+
+        decoder.start();
+        ByteBuffer[] codecInputBuffers = decoder.getInputBuffers();
+        ByteBuffer[] codecOutputBuffers = decoder.getOutputBuffers();
+
+        extractor.selectTrack(0);
+
+        // start decoding
+        final long kTimeOutUs = 5000;
+        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+        boolean sawInputEOS = false;
+        boolean sawOutputEOS = false;
+        int noOutputCounter = 0;
+        int samplecounter = 0;
+        short[] decoded = new short[0];
+        int decodedIdx = 0;
+        while (!sawOutputEOS && noOutputCounter < 50) {
+            noOutputCounter++;
+            if (!sawInputEOS) {
+                int inputBufIndex = decoder.dequeueInputBuffer(kTimeOutUs);
+
+                if (inputBufIndex >= 0) {
+                    ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];
+
+                    int sampleSize =
+                            extractor.readSampleData(dstBuf, 0 /* offset */);
+
+                    long presentationTimeUs = 0;
+
+                    if (sampleSize < 0) {
+                        Log.d(TAG, "saw input EOS.");
+                        sawInputEOS = true;
+                        sampleSize = 0;
+                    } else {
+                        samplecounter++;
+                        presentationTimeUs = extractor.getSampleTime();
+                    }
+                    decoder.queueInputBuffer(
+                            inputBufIndex,
+                            0 /* offset */,
+                            sampleSize,
+                            presentationTimeUs,
+                            sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
+
+                    if (!sawInputEOS) {
+                        extractor.advance();
+                    }
+                }
+            }
+
+            int res = decoder.dequeueOutputBuffer(info, kTimeOutUs);
+
+            if (res >= 0) {
+                if (info.size > 0) {
+                    noOutputCounter = 0;
+                }
+
+                int outputBufIndex = res;
+                ByteBuffer buf = codecOutputBuffers[outputBufIndex];
+
+                if (decodedIdx + (info.size / 2) >= decoded.length) {
+                    decoded = Arrays.copyOf(decoded, decodedIdx + (info.size / 2));
+                }
+
+                buf.position(info.offset);
+                for (int i = 0; i < info.size; i += 2) {
+                    decoded[decodedIdx++] = buf.getShort();
+                }
+
+                decoder.releaseOutputBuffer(outputBufIndex, false /* render */);
+
+                if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
+                    Log.d(TAG, "saw output EOS.");
+                    sawOutputEOS = true;
+                }
+            } else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
+                codecOutputBuffers = decoder.getOutputBuffers();
+                Log.d(TAG, "output buffers have changed.");
+            } else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+                MediaFormat outputFormat = decoder.getOutputFormat();
+                audioParams.setNumChannels(outputFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
+                audioParams.setSamplingRate(outputFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE));
+                Log.i(TAG, "output format has changed to " + outputFormat);
+            } else {
+                Log.d(TAG, "dequeueOutputBuffer returned " + res);
+            }
+        }
+        if (noOutputCounter >= 50) {
+            fail("decoder stopped outputing data");
+        }
+        decoder.stop();
+        decoder.release();
+        extractor.release();
+    }
+}
+
diff --git a/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java b/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java
index 3d8891c..0b4dee5 100755
--- a/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java
@@ -1168,7 +1168,8 @@
      * @param drcParams the MPEG-D DRC decoder parameter configuration
      * @param decoderName if non null, the name of the decoder to use for the decoding, otherwise
      *     the default decoder for the format will be used
-     * @param runtimeChange defines whether the decoder is configured at runtime or not
+     * @param runtimeChange defines whether the decoder is configured at runtime or configured
+     *                      before starting to decode
      * @param expectedOutputLoudness value to check if the correct output loudness is returned
      *     by the decoder
      * @throws RuntimeException
@@ -1388,30 +1389,32 @@
             if (drcParams.mAlbumMode != 0) {
                 final int albumModeFromCodec = codec.getOutputFormat()
                         .getInteger(MediaFormat.KEY_AAC_DRC_ALBUM_MODE);
-                if (false) { // TODO disabled until b/157773721 fixed
-                    if (albumModeFromCodec != drcParams.mAlbumMode) {
-                        fail("Drc AlbumMode received from MediaCodec is not the Album Mode set");
-                    }
-                }
+                assertEquals("DRC AlbumMode received from MediaCodec is not the Album Mode set"
+                        + " runtime:" + runtimeChange, drcParams.mAlbumMode, albumModeFromCodec);
             }
             if (drcParams.mEffectType != 0) {
                 final int effectTypeFromCodec = codec.getOutputFormat()
                         .getInteger(MediaFormat.KEY_AAC_DRC_EFFECT_TYPE);
-                if (false) { // TODO disabled until b/157773721 fixed
-                    if (effectTypeFromCodec != drcParams.mEffectType) {
-                        fail("Drc Effect Type received from MediaCodec is not the Effect Type set");
-                    }
-                }
+                assertEquals("DRC Effect Type received from MediaCodec is not the Effect Type set"
+                        + " runtime:" + runtimeChange, drcParams.mEffectType, effectTypeFromCodec);
             }
             if (drcParams.mDecoderTargetLevel != 0) {
                 final int targetLevelFromCodec = codec.getOutputFormat()
                         .getInteger(MediaFormat.KEY_AAC_DRC_TARGET_REFERENCE_LEVEL);
-                if (false) { // TODO disabled until b/157773721 fixed
-                    if (targetLevelFromCodec != drcParams.mDecoderTargetLevel) {
-                        fail("Drc Target Reference Level received from MediaCodec is not the Target Reference Level set");
-                    }
-                }
+                assertEquals("DRC Target Ref Level received from MediaCodec is not the level set"
+                        + " runtime:" + runtimeChange,
+                        drcParams.mDecoderTargetLevel, targetLevelFromCodec);
             }
+
+            final MediaFormat outputFormat = codec.getOutputFormat();
+            final int cutFromCodec = outputFormat.getInteger(
+                    MediaFormat.KEY_AAC_DRC_ATTENUATION_FACTOR);
+            assertEquals("Attenuation factor received from MediaCodec differs from set:",
+                    drcParams.mCut, cutFromCodec);
+            final int boostFromCodec = outputFormat.getInteger(
+                    MediaFormat.KEY_AAC_DRC_BOOST_FACTOR);
+            assertEquals("Boost factor received from MediaCodec differs from set:",
+                    drcParams.mBoost, boostFromCodec);
         }
 
         // expectedOutputLoudness == -2 indicates that output loudness is not tested
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
index d17e702..7e75fb7 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
@@ -35,7 +35,6 @@
 import static android.media.MediaFormat.MIMETYPE_VIDEO_VP9;
 import android.media.MediaPlayer;
 import android.os.Build;
-import android.os.SystemProperties;
 import android.platform.test.annotations.AppModeFull;
 import android.util.Log;
 import android.util.Range;
@@ -697,6 +696,7 @@
     private int getActualMax(
             boolean isEncoder, String name, String mime, CodecCapabilities caps, int max) {
         int flag = isEncoder ? MediaCodec.CONFIGURE_FLAG_ENCODE : 0;
+        boolean memory_limited = false;
         MediaFormat format = createMinFormat(mime, caps);
         Log.d(TAG, "Test format " + format);
         Vector<MediaCodec> codecs = new Vector<MediaCodec>();
@@ -716,6 +716,7 @@
                 am.getMemoryInfo(outInfo);
                 if (outInfo.lowMemory) {
                     Log.d(TAG, "System is in low memory condition, stopping. max: " + i);
+                    memory_limited = true;
                     break;
                 }
             } catch (IllegalArgumentException e) {
@@ -745,6 +746,10 @@
             codecs.get(i).release();
         }
         codecs.clear();
+        // encode both actual max and whether we ran out of memory
+        if (memory_limited) {
+            actualMax = -actualMax;
+        }
         return actualMax;
     }
 
@@ -773,13 +778,20 @@
     }
 
     public void testGetMaxSupportedInstances() {
-        final int MAX_INSTANCES = 32;
         StringBuilder xmlOverrides = new StringBuilder();
         MediaCodecList allCodecs = new MediaCodecList(MediaCodecList.ALL_CODECS);
+        final boolean isLowRam = ActivityManager.isLowRamDeviceStatic();
         for (MediaCodecInfo info : allCodecs.getCodecInfos()) {
             Log.d(TAG, "codec: " + info.getName());
             Log.d(TAG, "  isEncoder = " + info.isEncoder());
 
+            // don't bother testing aliases
+            if (info.isAlias()) {
+                Log.d(TAG, "skipping: " + info.getName() + " is an alias for " +
+                                info.getCanonicalName());
+                continue;
+            }
+
             String[] types = info.getSupportedTypes();
             for (int j = 0; j < types.length; ++j) {
                 if (!knownTypes(types[j])) {
@@ -788,14 +800,55 @@
                 }
                 Log.d(TAG, "calling getCapabilitiesForType " + types[j]);
                 CodecCapabilities caps = info.getCapabilitiesForType(types[j]);
-                int max = caps.getMaxSupportedInstances();
-                Log.d(TAG, "getMaxSupportedInstances returns " + max);
-                assertTrue(max > 0);
+                int advertised = caps.getMaxSupportedInstances();
+                Log.d(TAG, "getMaxSupportedInstances returns " + advertised);
+                assertTrue(advertised > 0);
 
+                // see how well the declared max matches against reality
+
+                int tryMax = isLowRam ? 16 : 32;
+                int tryMin = isLowRam ? 4 : 16;
+
+                int trials = Math.min(advertised + 2, tryMax);
                 int actualMax = getActualMax(
-                        info.isEncoder(), info.getName(), types[j], caps, MAX_INSTANCES);
-                Log.d(TAG, "actualMax " + actualMax + " vs reported max " + max);
-                if (actualMax < (int)(max * 0.9) || actualMax > (int) Math.ceil(max * 1.1)) {
+                        info.isEncoder(), info.getName(), types[j], caps, trials);
+                Log.d(TAG, "actualMax " + actualMax + " vs advertised " + advertised
+                                + " tryMin " + tryMin + " tryMax " + tryMax);
+
+                boolean memory_limited = false;
+                if (actualMax < 0) {
+                    memory_limited = true;
+                    actualMax = -actualMax;
+                }
+
+                boolean compliant = true;
+                if (info.isHardwareAccelerated()) {
+                    // very specific bounds for HW codecs
+                    // so the adv+2 above is to see if the HW codec lets us go beyond adv
+                    // (it should not)
+                    if (actualMax != Math.min(advertised, tryMax)) {
+                        Log.d(TAG, "NO: hwcodec " + actualMax + " != min(" + advertised +
+                                            "," + tryMax + ")");
+                        compliant = false;
+                    }
+                } else {
+                    // sw codecs get a little more relaxation due to memory pressure
+                    if (actualMax >= Math.min(advertised, tryMax)) {
+                        // no memory issues, and we allocated them all
+                        Log.d(TAG, "OK: swcodec " + actualMax + " >= min(" + advertised +
+                                        "," + tryMax + ")");
+                    } else if (actualMax >= Math.min(advertised, tryMin) &&
+                                    memory_limited) {
+                        // memory issues, but we hit our floors
+                        Log.d(TAG, "OK: swcodec " + actualMax + " >= min(" + advertised +
+                                        "," + tryMin + ") + memory limited");
+                    } else {
+                        Log.d(TAG, "NO: swcodec didn't meet criteria");
+                        compliant = false;
+                    }
+                }
+
+                if (!compliant) {
                     String codec = "<MediaCodec name=\"" + info.getName() +
                             "\" type=\"" + types[j] + "\" >";
                     String limit = "    <Limit name=\"concurrent-instances\" max=\"" +
diff --git a/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java b/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java
index f648a3c..6438cd0 100644
--- a/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaDrmClearkeyTest.java
@@ -27,6 +27,9 @@
 import android.platform.test.annotations.Presubmit;
 import android.util.Base64;
 import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+
 import android.view.Surface;
 
 import com.android.compatibility.common.util.ApiLevelUtil;
@@ -115,6 +118,10 @@
         if (false == deviceHasMediaDrm()) {
             tearDown();
         }
+        // Need MANAGE_USERS or CREATE_USERS permission to access ActivityManager#getCurrentUse in
+        // MediaCas, then adopt it from shell.
+        InstrumentationRegistry
+            .getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
     }
 
     @Override
diff --git a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
index 42c9f29..48208d9 100644
--- a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
@@ -599,14 +599,20 @@
     }
 
     public void testThumbnailVP9Hdr() {
+        if (!MediaUtils.check(mIsAtLeastR, "test needs Android 11")) return;
+
         testThumbnail(R.raw.video_1280x720_vp9_hdr_static_3mbps, 1280, 720);
     }
 
     public void testThumbnailAV1Hdr() {
+        if (!MediaUtils.check(mIsAtLeastR, "test needs Android 11")) return;
+
         testThumbnail(R.raw.video_1280x720_av1_hdr_static_3mbps, 1280, 720);
     }
 
     public void testThumbnailHDR10() {
+        if (!MediaUtils.check(mIsAtLeastR, "test needs Android 11")) return;
+
         testThumbnail(R.raw.video_1280x720_hevc_hdr10_static_3mbps, 1280, 720);
     }
 
diff --git a/tests/tests/media/src/android/media/cts/MediaRouter2Test.java b/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
index 238da0b..48466d5 100644
--- a/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
+++ b/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
@@ -17,6 +17,7 @@
 package android.media.cts;
 
 import static android.content.Context.AUDIO_SERVICE;
+import static android.media.MediaRoute2Info.FEATURE_LIVE_AUDIO;
 import static android.media.MediaRoute2Info.PLAYBACK_VOLUME_VARIABLE;
 import static android.media.cts.StubMediaRoute2ProviderService.FEATURES_SPECIAL;
 import static android.media.cts.StubMediaRoute2ProviderService.FEATURE_SAMPLE;
@@ -90,6 +91,9 @@
     private static final String TEST_VALUE = "test_value";
     private static final RouteDiscoveryPreference EMPTY_DISCOVERY_PREFERENCE =
             new RouteDiscoveryPreference.Builder(Collections.emptyList(), false).build();
+    private static final RouteDiscoveryPreference LIVE_AUDIO_DISCOVERY_PREFERENCE =
+            new RouteDiscoveryPreference.Builder(
+                    Collections.singletonList(FEATURE_LIVE_AUDIO), false).build();
 
     @Before
     public void setUp() throws Exception {
@@ -124,10 +128,16 @@
 
     @Test
     public void testGetRoutesAfterCreation() {
-        List<MediaRoute2Info> initialRoutes = mRouter2.getRoutes();
-        assertFalse(initialRoutes.isEmpty());
-        for (MediaRoute2Info route : initialRoutes) {
-            assertTrue(route.isSystemRoute());
+        RouteCallback routeCallback = new RouteCallback() {};
+        mRouter2.registerRouteCallback(mExecutor, routeCallback, LIVE_AUDIO_DISCOVERY_PREFERENCE);
+        try {
+            List<MediaRoute2Info> initialRoutes = mRouter2.getRoutes();
+            assertFalse(initialRoutes.isEmpty());
+            for (MediaRoute2Info route : initialRoutes) {
+                assertTrue(route.getFeatures().contains(FEATURE_LIVE_AUDIO));
+            }
+        } finally {
+            mRouter2.unregisterRouteCallback(routeCallback);
         }
     }
 
@@ -138,18 +148,13 @@
     public void testGetRoutes() throws Exception {
         Map<String, MediaRoute2Info> routes = waitAndGetRoutes(FEATURES_SPECIAL);
 
-        int systemRouteCount = 0;
         int remoteRouteCount = 0;
         for (MediaRoute2Info route : routes.values()) {
-            if (route.isSystemRoute()) {
-                systemRouteCount++;
-            } else {
+            if (!route.isSystemRoute()) {
                 remoteRouteCount++;
             }
         }
 
-        // Can be greater than 1 if BT devices are connected.
-        assertTrue(systemRouteCount > 0);
         assertEquals(1, remoteRouteCount);
         assertNotNull(routes.get(ROUTE_ID_SPECIAL_FEATURE));
     }
@@ -280,6 +285,8 @@
         final CountDownLatch successLatch2 = new CountDownLatch(1);
         final CountDownLatch failureLatch = new CountDownLatch(1);
         final CountDownLatch stopLatch = new CountDownLatch(1);
+        final CountDownLatch onReleaseSessionLatch = new CountDownLatch(1);
+
         final List<RoutingController> createdControllers = new ArrayList<>();
 
         // Create session with this route
@@ -306,6 +313,16 @@
             }
         };
 
+        StubMediaRoute2ProviderService service = mService;
+        if (service != null) {
+            service.setProxy(new StubMediaRoute2ProviderService.Proxy() {
+                @Override
+                public void onReleaseSession(long requestId, String sessionId) {
+                    onReleaseSessionLatch.countDown();
+                }
+            });
+        }
+
         Map<String, MediaRoute2Info> routes = waitAndGetRoutes(sampleRouteType);
         MediaRoute2Info route1 = routes.get(ROUTE_ID1);
         MediaRoute2Info route2 = routes.get(ROUTE_ID2);
@@ -332,15 +349,19 @@
             RoutingController controller1 = createdControllers.get(0);
             RoutingController controller2 = createdControllers.get(1);
 
-            // The first controller is expected to be released.
-            assertTrue(controller1.isReleased());
-
             assertNotEquals(controller1.getId(), controller2.getId());
             assertTrue(createRouteMap(controller1.getSelectedRoutes()).containsKey(
                     ROUTE_ID1));
             assertTrue(createRouteMap(controller2.getSelectedRoutes()).containsKey(
                     ROUTE_ID2));
 
+            // Transferred controllers shouldn't be obtainable.
+            assertFalse(mRouter2.getControllers().contains(controller1));
+            assertTrue(mRouter2.getControllers().contains(controller2));
+
+            // Should be able to release transferred controllers.
+            controller1.release();
+            assertTrue(onReleaseSessionLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
         } finally {
             releaseControllers(createdControllers);
             mRouter2.unregisterRouteCallback(routeCallback);
@@ -996,8 +1017,7 @@
             }
         };
 
-        mRouter2.registerRouteCallback(mExecutor, routeCallback,
-                new RouteDiscoveryPreference.Builder(new ArrayList<>(), true).build());
+        mRouter2.registerRouteCallback(mExecutor, routeCallback, LIVE_AUDIO_DISCOVERY_PREFERENCE);
 
         try {
             mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, targetVolume, 0);
diff --git a/tests/tests/media/src/android/media/cts/NativeEncoderTest.java b/tests/tests/media/src/android/media/cts/NativeEncoderTest.java
deleted file mode 100644
index 5cacfe1..0000000
--- a/tests/tests/media/src/android/media/cts/NativeEncoderTest.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.media.cts;
-
-import android.media.cts.R;
-
-import android.content.res.AssetFileDescriptor;
-import android.content.res.Resources;
-import android.net.Uri;
-import android.os.Environment;
-import android.os.ParcelFileDescriptor;
-import android.platform.test.annotations.AppModeFull;
-import android.util.Log;
-import android.view.Surface;
-import android.webkit.cts.CtsTestServer;
-
-import com.android.compatibility.common.util.MediaUtils;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.RandomAccessFile;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
-@AppModeFull(reason = "TODO: evaluate and port to instant")
-public class NativeEncoderTest extends MediaPlayerTestBase {
-    private static final String TAG = "NativeEncoderTest";
-    private static Resources mResources;
-
-    private static final String MIME_AVC = "video/avc";
-    private static final String MIME_HEVC = "video/hevc";
-    private static final String MIME_VP8 = "video/x-vnd.on2.vp8";
-
-    private static int mResourceVideo720p;
-    private static int mResourceVideo360p;
-
-    static {
-        System.loadLibrary("ctsmediacodec_jni");
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mResources = mContext.getResources();
-
-        mResourceVideo720p =
-                R.raw.bbb_s4_1280x720_webm_vp8_8mbps_30fps_opus_mono_64kbps_48000hz;
-        mResourceVideo360p =
-                R.raw.bbb_s1_640x360_webm_vp8_2mbps_30fps_vorbis_5ch_320kbps_48000hz;
-    }
-
-
-    private boolean testEncode(int res, String mime, int width, int height) {
-        AssetFileDescriptor fd = mResources.openRawResourceFd(res);
-
-        return testEncodeSurfaceNative(
-            fd.getParcelFileDescriptor().getFd(), fd.getStartOffset(), fd.getLength(),
-            mime, width, height);
-    }
-    private static native boolean testEncodeSurfaceNative(int fd, long offset, long size,
-            String mime, int width, int height);
-
-    public void testEncodeSurfaceH264720p() throws Exception {
-        boolean status = testEncode(mResourceVideo720p, MIME_AVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeSurfaceVp8720p() throws Exception {
-        boolean status = testEncode(mResourceVideo720p, MIME_VP8, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeSurfaceHevc720p() throws Exception {
-        boolean status = testEncode(mResourceVideo720p, MIME_HEVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeSurfaceH264360p() throws Exception {
-        boolean status = testEncode(mResourceVideo360p, MIME_AVC, 640, 360);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeSurfaceVp8360p() throws Exception {
-        boolean status = testEncode(mResourceVideo360p, MIME_VP8, 640, 360);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeSurfaceHevc360p() throws Exception {
-        boolean status = testEncode(mResourceVideo360p, MIME_HEVC, 640, 360);
-        assertTrue("native encode error", status);
-    }
-
-
-    private boolean testEncodeDynamicSyncFrame(int res, String mime, int width, int height) {
-        AssetFileDescriptor fd = mResources.openRawResourceFd(res);
-
-        return testEncodeSurfaceDynamicSyncFrameNative(
-            fd.getParcelFileDescriptor().getFd(), fd.getStartOffset(), fd.getLength(),
-            mime, width, height);
-    }
-    private static native boolean testEncodeSurfaceDynamicSyncFrameNative(int fd, long offset, long size,
-            String mime, int width, int height);
-
-    public void testEncodeDynamicSyncFrameH264720p() throws Exception {
-        boolean status = testEncodeDynamicSyncFrame(mResourceVideo720p, MIME_AVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicSyncFrameVp8720p() throws Exception {
-        boolean status = testEncodeDynamicSyncFrame(mResourceVideo720p, MIME_VP8, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicSyncFrameHevc720p() throws Exception {
-        boolean status = testEncodeDynamicSyncFrame(mResourceVideo720p, MIME_HEVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicSyncFrameH264360p() throws Exception {
-        boolean status = testEncodeDynamicSyncFrame(mResourceVideo360p, MIME_AVC, 640,  360);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicSyncFrameVp8360p() throws Exception {
-        boolean status = testEncodeDynamicSyncFrame(mResourceVideo360p, MIME_VP8, 640, 360);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicSyncFrameHevc360p() throws Exception {
-        boolean status = testEncodeDynamicSyncFrame(mResourceVideo360p, MIME_HEVC, 640, 360);
-        assertTrue("native encode error", status);
-    }
-
-
-    private boolean testEncodeDynamicBitrate(int res, String mime, int width, int height) {
-        AssetFileDescriptor fd = mResources.openRawResourceFd(res);
-
-        return testEncodeSurfaceDynamicBitrateNative(
-            fd.getParcelFileDescriptor().getFd(), fd.getStartOffset(), fd.getLength(),
-            mime, width, height);
-    }
-    private static native boolean testEncodeSurfaceDynamicBitrateNative(int fd, long offset, long size,
-            String mime, int width, int height);
-
-    public void testEncodeDynamicBitrateH264720p() throws Exception {
-        boolean status = testEncodeDynamicBitrate(mResourceVideo720p, MIME_AVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicBitrateVp8720p() throws Exception {
-        boolean status = testEncodeDynamicBitrate(mResourceVideo720p, MIME_VP8, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicBitrateHevc720p() throws Exception {
-        boolean status = testEncodeDynamicBitrate(mResourceVideo720p, MIME_HEVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicBitrateH264360p() throws Exception {
-        boolean status = testEncodeDynamicBitrate(mResourceVideo360p, MIME_AVC, 640, 360);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicBitrateVp8360p() throws Exception {
-        boolean status = testEncodeDynamicBitrate(mResourceVideo360p, MIME_VP8, 640, 360);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodeDynamicBitrateHevc360p() throws Exception {
-        boolean status = testEncodeDynamicBitrate(mResourceVideo360p, MIME_HEVC, 640, 360);
-        assertTrue("native encode error", status);
-    }
-
-
-    private boolean testEncodePersistentSurface(int res, String mime, int width, int height) {
-        AssetFileDescriptor fd = mResources.openRawResourceFd(res);
-
-        return testEncodePersistentSurfaceNative(
-            fd.getParcelFileDescriptor().getFd(), fd.getStartOffset(), fd.getLength(),
-            mime, width, height);
-    }
-
-    private static native boolean testEncodePersistentSurfaceNative(int fd, long offset, long size,
-            String mime, int width, int height);
-
-    public void testEncodePersistentSurface720p() throws Exception {
-        boolean status = testEncodePersistentSurface(mResourceVideo720p, MIME_AVC, 1280, 720);
-        assertTrue("native encode error", status);
-    }
-    public void testEncodePersistentSurface360p() throws Exception {
-        boolean status = testEncodePersistentSurface(mResourceVideo360p, MIME_VP8, 640, 360);
-        assertTrue("native encode error", status);
-    }
-}
diff --git a/tests/tests/media/src/android/media/cts/VideoCodecTestBase.java b/tests/tests/media/src/android/media/cts/VideoCodecTestBase.java
index 82c8b18..7ba3541 100644
--- a/tests/tests/media/src/android/media/cts/VideoCodecTestBase.java
+++ b/tests/tests/media/src/android/media/cts/VideoCodecTestBase.java
@@ -832,8 +832,9 @@
             if (out.outputGenerated) {
                 if ((out.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                     Log.d(TAG, "Storing codec config separately");
-                    mCodecConfigs.add(
-                            ByteBuffer.allocate(out.buffer.length).put(out.buffer));
+                    ByteBuffer csdBuffer = ByteBuffer.allocate(out.buffer.length).put(out.buffer);
+                    csdBuffer.rewind();
+                    mCodecConfigs.add(csdBuffer);
                     out.buffer = new byte[0];
                 }
                 if (out.buffer.length > 0) {
@@ -1480,8 +1481,9 @@
                 }
                 if ((out.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                     Log.d(TAG, "Storing codec config separately");
-                    codecConfigs.add(
-                            ByteBuffer.allocate(out.buffer.length).put(out.buffer));
+                    ByteBuffer csdBuffer = ByteBuffer.allocate(out.buffer.length).put(out.buffer);
+                    csdBuffer.rewind();
+                    codecConfigs.add(csdBuffer);
                     out.buffer = new byte[0];
                 }
 
@@ -1786,8 +1788,9 @@
                     }
                     if ((out.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                         Log.d(TAG, "----Enc" + i + ". Storing codec config separately");
-                        codecConfigs.get(i).add(
-                                ByteBuffer.allocate(out.buffer.length).put(out.buffer));
+                        ByteBuffer csdBuffer = ByteBuffer.allocate(out.buffer.length).put(out.buffer);
+                        csdBuffer.rewind();
+                        codecConfigs.get(i).add(csdBuffer);
                         out.buffer = new byte[0];
                     }
 
diff --git a/tests/tests/nativemedia/aaudio/jni/test_aaudio_attributes.cpp b/tests/tests/nativemedia/aaudio/jni/test_aaudio_attributes.cpp
index 79cd3f6..4d9194f 100644
--- a/tests/tests/nativemedia/aaudio/jni/test_aaudio_attributes.cpp
+++ b/tests/tests/nativemedia/aaudio/jni/test_aaudio_attributes.cpp
@@ -274,8 +274,14 @@
 
         AAudioStreamBuilder_setUsage(aaudioBuilder, systemUsage);
 
-        // Get failed status when trying to create an AAudioStream using the Builder.
-        ASSERT_EQ(AAUDIO_ERROR_ILLEGAL_ARGUMENT, AAudioStreamBuilder_openStream(aaudioBuilder, &aaudioStream));
+        aaudio_result_t result = AAudioStreamBuilder_openStream(aaudioBuilder, &aaudioStream);
+
+        // Get failed status when trying to create an AAudioStream using the Builder. There are two
+        // potential failures: one if the device doesn't support the system usage, and the  other
+        // if it does but this test doesn't have the MODIFY_AUDIO_ROUTING permission required to
+        // use it.
+        ASSERT_TRUE(result == AAUDIO_ERROR_ILLEGAL_ARGUMENT
+                || result == AAUDIO_ERROR_INTERNAL);
         AAudioStreamBuilder_delete(aaudioBuilder);
     }
 }
diff --git a/tests/tests/net/Android.bp b/tests/tests/net/Android.bp
index 2b99a40..112799b 100644
--- a/tests/tests/net/Android.bp
+++ b/tests/tests/net/Android.bp
@@ -36,19 +36,20 @@
         "src/**/*.java",
         "src/**/*.kt",
     ],
-
+    jarjar_rules: "jarjar-rules-shared.txt",
     static_libs: [
         "FrameworksNetCommonTests",
         "TestNetworkStackLib",
-        "core-tests-support",
         "compatibility-device-util-axt",
+        "core-tests-support",
         "cts-net-utils",
         "ctstestrunner-axt",
         "ctstestserver",
-        "mockwebserver",
         "junit",
         "junit-params",
         "libnanohttpd",
+        "mockwebserver",
+        "net-utils-framework-common",
         "truth-prebuilt",
     ],
 
diff --git a/tests/tests/net/jarjar-rules-shared.txt b/tests/tests/net/jarjar-rules-shared.txt
new file mode 100644
index 0000000..11dba74
--- /dev/null
+++ b/tests/tests/net/jarjar-rules-shared.txt
@@ -0,0 +1,2 @@
+# Module library in frameworks/libs/net
+rule com.android.net.module.util.** android.net.cts.util.@1
\ No newline at end of file
diff --git a/tests/tests/net/src/android/net/cts/CaptivePortalApiTest.kt b/tests/tests/net/src/android/net/cts/CaptivePortalApiTest.kt
index 68d5281..ef2b0ce 100644
--- a/tests/tests/net/src/android/net/cts/CaptivePortalApiTest.kt
+++ b/tests/tests/net/src/android/net/cts/CaptivePortalApiTest.kt
@@ -35,8 +35,6 @@
 import android.net.dhcp.DhcpPacket.DHCP_MESSAGE_TYPE_DISCOVER
 import android.net.dhcp.DhcpPacket.DHCP_MESSAGE_TYPE_REQUEST
 import android.net.dhcp.DhcpRequestPacket
-import android.net.shared.Inet4AddressUtils.getBroadcastAddress
-import android.net.shared.Inet4AddressUtils.getPrefixMaskAsInet4Address
 import android.os.Build
 import android.os.HandlerThread
 import android.platform.test.annotations.AppModeFull
@@ -44,6 +42,8 @@
 import androidx.test.runner.AndroidJUnit4
 import com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity
 import com.android.compatibility.common.util.ThrowingRunnable
+import com.android.net.module.util.Inet4AddressUtils.getBroadcastAddress
+import com.android.net.module.util.Inet4AddressUtils.getPrefixMaskAsInet4Address
 import com.android.server.util.NetworkStackConstants.IPV4_ADDR_ANY
 import com.android.testutils.DevSdkIgnoreRule
 import com.android.testutils.DhcpClientPacketFilter
diff --git a/tests/tests/net/src/android/net/cts/CaptivePortalTest.kt b/tests/tests/net/src/android/net/cts/CaptivePortalTest.kt
index 0816aba..4a7d38a 100644
--- a/tests/tests/net/src/android/net/cts/CaptivePortalTest.kt
+++ b/tests/tests/net/src/android/net/cts/CaptivePortalTest.kt
@@ -41,6 +41,7 @@
 import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
 import androidx.test.runner.AndroidJUnit4
 import com.android.compatibility.common.util.SystemUtil
+import com.android.testutils.isDevSdkInRange
 import fi.iki.elonen.NanoHTTPD
 import fi.iki.elonen.NanoHTTPD.Response.IStatus
 import fi.iki.elonen.NanoHTTPD.Response.Status
@@ -105,6 +106,9 @@
     @After
     fun tearDown() {
         clearTestUrls()
+        if (pm.hasSystemFeature(FEATURE_WIFI)) {
+            reconnectWifi()
+        }
         server.stop()
     }
 
@@ -167,7 +171,7 @@
             assertNotEquals(network, cm.activeNetwork, wifiDefaultMessage)
 
             val startPortalAppPermission =
-                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) CONNECTIVITY_INTERNAL
+                    if (isDevSdkInRange(0, Build.VERSION_CODES.Q)) CONNECTIVITY_INTERNAL
                     else NETWORK_SETTINGS
             doAsShell(startPortalAppPermission) { cm.startCaptivePortalApp(network) }
             assertTrue(portalContentRequestCv.block(TEST_TIMEOUT_MS), "The captive portal login " +
@@ -180,9 +184,6 @@
             // disconnectFromCell should be called after connectToCell
             utils.disconnectFromCell()
         }
-
-        clearTestUrls()
-        reconnectWifi()
     }
 
     private fun setHttpsUrl(url: String?) = setConfig(TEST_CAPTIVE_PORTAL_HTTPS_URL_SETTING, url)
@@ -203,10 +204,8 @@
     }
 
     private fun reconnectWifi() {
-        doAsShell(NETWORK_SETTINGS) {
-            assertTrue(wm.disconnect())
-            assertTrue(wm.reconnect())
-        }
+        utils.ensureWifiDisconnected(null /* wifiNetworkToCheck */)
+        utils.ensureWifiConnected()
     }
 
     /**
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java
index 0248f97..34ca9a4 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java
@@ -16,6 +16,7 @@
 
 package android.net.cts;
 
+import static android.content.pm.PackageManager.FEATURE_TELEPHONY;
 import static android.net.ConnectivityDiagnosticsManager.ConnectivityDiagnosticsCallback;
 import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
 import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
@@ -31,9 +32,11 @@
 import static android.net.ConnectivityDiagnosticsManager.persistableBundleEquals;
 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
 import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED;
+import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
 import static android.net.NetworkCapabilities.TRANSPORT_TEST;
 import static android.net.cts.util.CtsNetUtils.TestNetworkCallback;
 
+import static com.android.compatibility.common.util.SystemUtil.callWithShellPermissionIdentity;
 import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
 
 import static org.junit.Assert.assertEquals;
@@ -41,9 +44,15 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 
 import android.annotation.NonNull;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
 import android.net.ConnectivityDiagnosticsManager;
 import android.net.ConnectivityManager;
 import android.net.LinkAddress;
@@ -55,25 +64,39 @@
 import android.os.Binder;
 import android.os.Build;
 import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.os.Process;
+import android.platform.test.annotations.AppModeFull;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
 import android.util.Pair;
 
 import androidx.test.InstrumentationRegistry;
 
+import com.android.internal.telephony.uicc.IccUtils;
+import com.android.internal.util.ArrayUtils;
 import com.android.testutils.ArrayTrackRecord;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
 import com.android.testutils.DevSdkIgnoreRunner;
+import com.android.testutils.SkipPresubmit;
 
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
 
 @RunWith(DevSdkIgnoreRunner.class)
 @IgnoreUpTo(Build.VERSION_CODES.Q) // ConnectivityDiagnosticsManager did not exist in Q
+@AppModeFull(reason = "CHANGE_NETWORK_STATE, MANAGE_TEST_NETWORKS not grantable to instant apps")
 public class ConnectivityDiagnosticsManagerTest {
     private static final int CALLBACK_TIMEOUT_MILLIS = 5000;
     private static final int NO_CALLBACK_INVOKED_TIMEOUT = 500;
@@ -83,6 +106,7 @@
     private static final int FAIL_RATE_PERCENTAGE = 100;
     private static final int UNKNOWN_DETECTION_METHOD = 4;
     private static final int FILTERED_UNKNOWN_DETECTION_METHOD = 0;
+    private static final int CARRIER_CONFIG_CHANGED_BROADCAST_TIMEOUT = 5000;
 
     private static final Executor INLINE_EXECUTOR = x -> x.run();
 
@@ -93,44 +117,71 @@
                     .removeCapability(NET_CAPABILITY_NOT_VPN)
                     .build();
 
-    // Callback used to keep TestNetworks up when there are no other outstanding NetworkRequests
-    // for it.
-    private static final TestNetworkCallback TEST_NETWORK_CALLBACK = new TestNetworkCallback();
+    private static final String SHA_256 = "SHA-256";
+
+    private static final NetworkRequest CELLULAR_NETWORK_REQUEST =
+            new NetworkRequest.Builder().addTransportType(TRANSPORT_CELLULAR).build();
 
     private static final IBinder BINDER = new Binder();
 
     private Context mContext;
     private ConnectivityManager mConnectivityManager;
     private ConnectivityDiagnosticsManager mCdm;
+    private CarrierConfigManager mCarrierConfigManager;
+    private PackageManager mPackageManager;
+    private TelephonyManager mTelephonyManager;
+
+    // Callback used to keep TestNetworks up when there are no other outstanding NetworkRequests
+    // for it.
+    private TestNetworkCallback mTestNetworkCallback;
     private Network mTestNetwork;
+    private ParcelFileDescriptor mTestNetworkFD;
+
+    private List<TestConnectivityDiagnosticsCallback> mRegisteredCallbacks;
 
     @Before
     public void setUp() throws Exception {
         mContext = InstrumentationRegistry.getContext();
         mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
         mCdm = mContext.getSystemService(ConnectivityDiagnosticsManager.class);
+        mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
+        mPackageManager = mContext.getPackageManager();
+        mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
 
-        mConnectivityManager.requestNetwork(TEST_NETWORK_REQUEST, TEST_NETWORK_CALLBACK);
+        mTestNetworkCallback = new TestNetworkCallback();
+        mConnectivityManager.requestNetwork(TEST_NETWORK_REQUEST, mTestNetworkCallback);
+
+        mRegisteredCallbacks = new ArrayList<>();
     }
 
     @After
     public void tearDown() throws Exception {
-        mConnectivityManager.unregisterNetworkCallback(TEST_NETWORK_CALLBACK);
-
+        mConnectivityManager.unregisterNetworkCallback(mTestNetworkCallback);
         if (mTestNetwork != null) {
             runWithShellPermissionIdentity(() -> {
                 final TestNetworkManager tnm = mContext.getSystemService(TestNetworkManager.class);
                 tnm.teardownTestNetwork(mTestNetwork);
             });
+            mTestNetwork = null;
+        }
+
+        if (mTestNetworkFD != null) {
+            mTestNetworkFD.close();
+            mTestNetworkFD = null;
+        }
+
+        for (TestConnectivityDiagnosticsCallback cb : mRegisteredCallbacks) {
+            mCdm.unregisterConnectivityDiagnosticsCallback(cb);
         }
     }
 
     @Test
     public void testRegisterConnectivityDiagnosticsCallback() throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         final String interfaceName =
                 mConnectivityManager.getLinkProperties(mTestNetwork).getInterfaceName();
@@ -139,10 +190,100 @@
         cb.assertNoCallback();
     }
 
+    @SkipPresubmit(reason = "Flaky: b/159718782; add to presubmit after fixing")
+    @Test
+    public void testRegisterCallbackWithCarrierPrivileges() throws Exception {
+        assumeTrue(mPackageManager.hasSystemFeature(FEATURE_TELEPHONY));
+
+        final int subId = SubscriptionManager.getDefaultSubscriptionId();
+        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+            fail("Need an active subscription. Please ensure that the device has working mobile"
+                    + " data.");
+        }
+
+        final CarrierConfigReceiver carrierConfigReceiver = new CarrierConfigReceiver(subId);
+        mContext.registerReceiver(
+                carrierConfigReceiver,
+                new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
+
+        final TestNetworkCallback testNetworkCallback = new TestNetworkCallback();
+
+        try {
+            doBroadcastCarrierConfigsAndVerifyOnConnectivityReportAvailable(
+                    subId, carrierConfigReceiver, testNetworkCallback);
+        } finally {
+            runWithShellPermissionIdentity(
+                    () -> mCarrierConfigManager.overrideConfig(subId, null),
+                    android.Manifest.permission.MODIFY_PHONE_STATE);
+            mConnectivityManager.unregisterNetworkCallback(testNetworkCallback);
+            mContext.unregisterReceiver(carrierConfigReceiver);
+        }
+    }
+
+    private String getCertHashForThisPackage() throws Exception {
+        final PackageInfo pkgInfo =
+                mPackageManager.getPackageInfo(
+                        mContext.getOpPackageName(), PackageManager.GET_SIGNATURES);
+        final MessageDigest md = MessageDigest.getInstance(SHA_256);
+        final byte[] certHash = md.digest(pkgInfo.signatures[0].toByteArray());
+        return IccUtils.bytesToHexString(certHash);
+    }
+
+    private void doBroadcastCarrierConfigsAndVerifyOnConnectivityReportAvailable(
+            int subId,
+            @NonNull CarrierConfigReceiver carrierConfigReceiver,
+            @NonNull TestNetworkCallback testNetworkCallback)
+            throws Exception {
+        final PersistableBundle carrierConfigs = new PersistableBundle();
+        carrierConfigs.putStringArray(
+                CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY,
+                new String[] {getCertHashForThisPackage()});
+
+        runWithShellPermissionIdentity(
+                () -> {
+                    mCarrierConfigManager.overrideConfig(subId, carrierConfigs);
+                    mCarrierConfigManager.notifyConfigChangedForSubId(subId);
+                },
+                android.Manifest.permission.MODIFY_PHONE_STATE);
+
+        // TODO(b/157779832): This should use android.permission.CHANGE_NETWORK_STATE. However, the
+        // shell does not have CHANGE_NETWORK_STATE, so use CONNECTIVITY_INTERNAL until the shell
+        // permissions are updated.
+        runWithShellPermissionIdentity(
+                () -> mConnectivityManager.requestNetwork(
+                        CELLULAR_NETWORK_REQUEST, testNetworkCallback),
+                android.Manifest.permission.CONNECTIVITY_INTERNAL);
+
+        final Network network = testNetworkCallback.waitForAvailable();
+        assertNotNull(network);
+
+        assertTrue("Didn't receive broadcast for ACTION_CARRIER_CONFIG_CHANGED for subId=" + subId,
+                carrierConfigReceiver.waitForCarrierConfigChanged());
+        assertTrue("Don't have Carrier Privileges after adding cert for this package",
+                mTelephonyManager.createForSubscriptionId(subId).hasCarrierPrivileges());
+
+        // Wait for CarrierPrivilegesTracker to receive the ACTION_CARRIER_CONFIG_CHANGED
+        // broadcast. CPT then needs to update the corresponding DataConnection, which then
+        // updates ConnectivityService. Unfortunately, this update to the NetworkCapabilities in
+        // CS does not trigger NetworkCallback#onCapabilitiesChanged as changing the
+        // administratorUids is not a publicly visible change. In lieu of a better signal to
+        // detministically wait for, use Thread#sleep here.
+        Thread.sleep(500);
+
+        final TestConnectivityDiagnosticsCallback connDiagsCallback =
+                createAndRegisterConnectivityDiagnosticsCallback(CELLULAR_NETWORK_REQUEST);
+
+        final String interfaceName =
+                mConnectivityManager.getLinkProperties(network).getInterfaceName();
+        connDiagsCallback.expectOnConnectivityReportAvailable(
+                network, interfaceName, TRANSPORT_CELLULAR);
+        connDiagsCallback.assertNoCallback();
+    }
+
     @Test
     public void testRegisterDuplicateConnectivityDiagnosticsCallback() {
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         try {
             mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
@@ -166,10 +307,11 @@
 
     @Test
     public void testOnConnectivityReportAvailable() throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
         final String interfaceName =
                 mConnectivityManager.getLinkProperties(mTestNetwork).getInterfaceName();
@@ -217,10 +359,11 @@
             long timestampMillis,
             @NonNull PersistableBundle extras)
             throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         final String interfaceName =
                 mConnectivityManager.getLinkProperties(mTestNetwork).getInterfaceName();
@@ -248,10 +391,11 @@
     }
 
     private void verifyOnNetworkConnectivityReported(boolean hasConnectivity) throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         // onConnectivityReportAvailable always invoked when the test network is established
         final String interfaceName =
@@ -272,17 +416,12 @@
         cb.assertNoCallback();
     }
 
-    @NonNull
-    private Network waitForConnectivityServiceIdleAndGetNetwork() throws InterruptedException {
-        // Get a new Network. This requires going through the ConnectivityService thread. Once it
-        // completes, all previously enqueued messages on the ConnectivityService main Handler have
-        // completed.
-        final TestNetworkCallback callback = new TestNetworkCallback();
-        mConnectivityManager.requestNetwork(TEST_NETWORK_REQUEST, callback);
-        final Network network = callback.waitForAvailable();
-        mConnectivityManager.unregisterNetworkCallback(callback);
-        assertNotNull(network);
-        return network;
+    private TestConnectivityDiagnosticsCallback createAndRegisterConnectivityDiagnosticsCallback(
+            NetworkRequest request) {
+        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
+        mCdm.registerConnectivityDiagnosticsCallback(request, INLINE_EXECUTOR, cb);
+        mRegisteredCallbacks.add(cb);
+        return cb;
     }
 
     /**
@@ -290,16 +429,16 @@
      * to the Network being validated.
      */
     @NonNull
-    private Network setUpTestNetwork() throws Exception {
+    private TestNetworkInterface setUpTestNetwork() throws Exception {
         final int[] administratorUids = new int[] {Process.myUid()};
-        runWithShellPermissionIdentity(
+        return callWithShellPermissionIdentity(
                 () -> {
                     final TestNetworkManager tnm =
                             mContext.getSystemService(TestNetworkManager.class);
                     final TestNetworkInterface tni = tnm.createTunInterface(new LinkAddress[0]);
                     tnm.setupTestNetwork(tni.getInterfaceName(), administratorUids, BINDER);
+                    return tni;
                 });
-        return waitForConnectivityServiceIdleAndGetNetwork();
     }
 
     private static class TestConnectivityDiagnosticsCallback
@@ -324,13 +463,18 @@
 
         public void expectOnConnectivityReportAvailable(
                 @NonNull Network network, @NonNull String interfaceName) {
+            expectOnConnectivityReportAvailable(network, interfaceName, TRANSPORT_TEST);
+        }
+
+        public void expectOnConnectivityReportAvailable(
+                @NonNull Network network, @NonNull String interfaceName, int transportType) {
             final ConnectivityReport result =
                     (ConnectivityReport) mHistory.poll(CALLBACK_TIMEOUT_MILLIS, x -> true);
             assertEquals(network, result.getNetwork());
 
             final NetworkCapabilities nc = result.getNetworkCapabilities();
             assertNotNull(nc);
-            assertTrue(nc.hasTransport(TRANSPORT_TEST));
+            assertTrue(nc.hasTransport(transportType));
             assertNotNull(result.getLinkProperties());
             assertEquals(interfaceName, result.getLinkProperties().getInterfaceName());
 
@@ -384,4 +528,43 @@
                     mHistory.poll(NO_CALLBACK_INVOKED_TIMEOUT, x -> true));
         }
     }
+
+    private class CarrierConfigReceiver extends BroadcastReceiver {
+        private final CountDownLatch mLatch = new CountDownLatch(1);
+        private final int mSubId;
+
+        CarrierConfigReceiver(int subId) {
+            mSubId = subId;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (!CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
+                return;
+            }
+
+            final int subId =
+                    intent.getIntExtra(
+                            CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX,
+                            SubscriptionManager.INVALID_SUBSCRIPTION_ID);
+            if (mSubId != subId) return;
+
+            final PersistableBundle carrierConfigs = mCarrierConfigManager.getConfigForSubId(subId);
+            if (!CarrierConfigManager.isConfigForIdentifiedCarrier(carrierConfigs)) return;
+
+            final String[] certs =
+                    carrierConfigs.getStringArray(
+                            CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY);
+            try {
+                if (ArrayUtils.contains(certs, getCertHashForThisPackage())) {
+                    mLatch.countDown();
+                }
+            } catch (Exception e) {
+            }
+        }
+
+        boolean waitForCarrierConfigChanged() throws Exception {
+            return mLatch.await(CARRIER_CONFIG_CHANGED_BROADCAST_TIMEOUT, TimeUnit.MILLISECONDS);
+        }
+    }
 }
diff --git a/tests/tests/net/src/android/net/cts/DnsResolverTest.java b/tests/tests/net/src/android/net/cts/DnsResolverTest.java
index 28753ff..4acbbcf 100644
--- a/tests/tests/net/src/android/net/cts/DnsResolverTest.java
+++ b/tests/tests/net/src/android/net/cts/DnsResolverTest.java
@@ -30,7 +30,6 @@
 import android.content.ContentResolver;
 import android.net.ConnectivityManager;
 import android.net.ConnectivityManager.NetworkCallback;
-import android.net.DnsPacket;
 import android.net.DnsResolver;
 import android.net.LinkProperties;
 import android.net.Network;
@@ -47,6 +46,9 @@
 import android.test.AndroidTestCase;
 import android.util.Log;
 
+import com.android.net.module.util.DnsPacket;
+import com.android.testutils.SkipPresubmit;
+
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
@@ -584,6 +586,7 @@
         doTestContinuousQueries(mExecutor);
     }
 
+    @SkipPresubmit(reason = "Flaky: b/159762682; add to presubmit after fixing")
     public void testContinuousQueriesInline() throws Exception {
         doTestContinuousQueries(mExecutorInline);
     }
diff --git a/tests/tests/net/src/android/net/cts/Ikev2VpnTest.java b/tests/tests/net/src/android/net/cts/Ikev2VpnTest.java
index 81dfed5..9eab024 100644
--- a/tests/tests/net/src/android/net/cts/Ikev2VpnTest.java
+++ b/tests/tests/net/src/android/net/cts/Ikev2VpnTest.java
@@ -16,6 +16,7 @@
 
 package android.net.cts;
 
+import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
 import static android.net.NetworkCapabilities.TRANSPORT_VPN;
 import static android.net.cts.util.CtsNetUtils.TestNetworkCallback;
 
@@ -40,6 +41,7 @@
 import android.net.IpSecAlgorithm;
 import android.net.LinkAddress;
 import android.net.Network;
+import android.net.NetworkCapabilities;
 import android.net.NetworkRequest;
 import android.net.ProxyInfo;
 import android.net.TestNetworkInterface;
@@ -47,6 +49,7 @@
 import android.net.VpnManager;
 import android.net.cts.util.CtsNetUtils;
 import android.os.Build;
+import android.os.Process;
 import android.platform.test.annotations.AppModeFull;
 
 import androidx.test.InstrumentationRegistry;
@@ -426,6 +429,11 @@
         final Network vpnNetwork = cb.currentNetwork;
         assertNotNull(vpnNetwork);
 
+        final NetworkCapabilities caps = sCM.getNetworkCapabilities(vpnNetwork);
+        assertTrue(caps.hasTransport(TRANSPORT_VPN));
+        assertTrue(caps.hasCapability(NET_CAPABILITY_INTERNET));
+        assertEquals(Process.myUid(), caps.getOwnerUid());
+
         sVpnMgr.stopProvisionedVpnProfile();
         cb.waitForLost();
         assertEquals(vpnNetwork, cb.lastLostNetwork);
diff --git a/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java b/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java
index b1f3602..85d2113 100644
--- a/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java
+++ b/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java
@@ -157,8 +157,36 @@
         }
     }
 
-    /** Enable WiFi and wait for it to become connected to a network. */
+    /**
+     * Enable WiFi and wait for it to become connected to a network.
+     *
+     * This method expects to receive a legacy broadcast on connect, which may not be sent if the
+     * network does not become default or if it is not the first network.
+     */
     public Network connectToWifi() {
+        return connectToWifi(true /* expectLegacyBroadcast */);
+    }
+
+    /**
+     * Enable WiFi and wait for it to become connected to a network.
+     *
+     * A network is considered connected when a {@link NetworkCallback#onAvailable(Network)}
+     * callback is received.
+     */
+    public Network ensureWifiConnected() {
+        return connectToWifi(false /* expectLegacyBroadcast */);
+    }
+
+    /**
+     * Enable WiFi and wait for it to become connected to a network.
+     *
+     * @param expectLegacyBroadcast Whether to check for a legacy CONNECTIVITY_ACTION connected
+     *                              broadcast. The broadcast is typically not sent if the network
+     *                              does not become the default network, and is not the first
+     *                              network to appear.
+     * @return The network that was newly connected.
+     */
+    private Network connectToWifi(boolean expectLegacyBroadcast) {
         final TestNetworkCallback callback = new TestNetworkCallback();
         mCm.registerNetworkCallback(makeWifiNetworkRequest(), callback);
         Network wifiNetwork = null;
@@ -170,15 +198,16 @@
         mContext.registerReceiver(receiver, filter);
 
         boolean connected = false;
+        final String err = "Wifi must be configured to connect to an access point for this test.";
         try {
             clearWifiBlacklist();
             SystemUtil.runShellCommand("svc wifi enable");
             SystemUtil.runWithShellPermissionIdentity(() -> mWifiManager.reconnect(),
                     NETWORK_SETTINGS);
-            // Ensure we get both an onAvailable callback and a CONNECTIVITY_ACTION.
+            // Ensure we get an onAvailable callback and possibly a CONNECTIVITY_ACTION.
             wifiNetwork = callback.waitForAvailable();
-            assertNotNull(wifiNetwork);
-            connected = receiver.waitForState();
+            assertNotNull(err, wifiNetwork);
+            connected = !expectLegacyBroadcast || receiver.waitForState();
         } catch (InterruptedException ex) {
             fail("connectToWifi was interrupted");
         } finally {
@@ -186,8 +215,7 @@
             mContext.unregisterReceiver(receiver);
         }
 
-        assertTrue("Wifi must be configured to connect to an access point for this test.",
-                connected);
+        assertTrue(err, connected);
         return wifiNetwork;
     }
 
@@ -204,8 +232,47 @@
         });
     }
 
-    /** Disable WiFi and wait for it to become disconnected from the network. */
+    /**
+     * Disable WiFi and wait for it to become disconnected from the network.
+     *
+     * This method expects to receive a legacy broadcast on disconnect, which may not be sent if the
+     * network was not default, or was not the first network.
+     *
+     * @param wifiNetworkToCheck If non-null, a network that should be disconnected. This network
+     *                           is expected to be able to establish a TCP connection to a remote
+     *                           server before disconnecting, and to have that connection closed in
+     *                           the process.
+     */
     public void disconnectFromWifi(Network wifiNetworkToCheck) {
+        disconnectFromWifi(wifiNetworkToCheck, true /* expectLegacyBroadcast */);
+    }
+
+    /**
+     * Disable WiFi and wait for it to become disconnected from the network.
+     *
+     * @param wifiNetworkToCheck If non-null, a network that should be disconnected. This network
+     *                           is expected to be able to establish a TCP connection to a remote
+     *                           server before disconnecting, and to have that connection closed in
+     *                           the process.
+     */
+    public void ensureWifiDisconnected(Network wifiNetworkToCheck) {
+        disconnectFromWifi(wifiNetworkToCheck, false /* expectLegacyBroadcast */);
+    }
+
+    /**
+     * Disable WiFi and wait for it to become disconnected from the network.
+     *
+     * @param wifiNetworkToCheck If non-null, a network that should be disconnected. This network
+     *                           is expected to be able to establish a TCP connection to a remote
+     *                           server before disconnecting, and to have that connection closed in
+     *                           the process.
+     * @param expectLegacyBroadcast Whether to check for a legacy CONNECTIVITY_ACTION disconnected
+     *                              broadcast. The broadcast is typically not sent if the network
+     *                              was not the default network and not the first network to appear.
+     *                              The check will always be skipped if the device was not connected
+     *                              to wifi in the first place.
+     */
+    private void disconnectFromWifi(Network wifiNetworkToCheck, boolean expectLegacyBroadcast) {
         final TestNetworkCallback callback = new TestNetworkCallback();
         mCm.registerNetworkCallback(makeWifiNetworkRequest(), callback);
 
@@ -238,6 +305,8 @@
                 // Ensure we get both an onLost callback and a CONNECTIVITY_ACTION.
                 assertNotNull("Did not receive onLost callback after disabling wifi",
                         callback.waitForLost());
+            }
+            if (wasWifiConnected && expectLegacyBroadcast) {
                 assertTrue("Wifi failed to reach DISCONNECTED state.", receiver.waitForState());
             }
         } catch (InterruptedException ex) {
diff --git a/tests/tests/os/Android.bp b/tests/tests/os/Android.bp
index b118392..e04630b 100644
--- a/tests/tests/os/Android.bp
+++ b/tests/tests/os/Android.bp
@@ -26,6 +26,7 @@
         "truth-prebuilt",
         "guava",
         "junit",
+        "CtsMockInputMethodLib"
     ],
     jni_uses_platform_apis: true,
     jni_libs: [
diff --git a/tests/tests/os/AndroidManifest.xml b/tests/tests/os/AndroidManifest.xml
index 07de155..5a53fa5 100644
--- a/tests/tests/os/AndroidManifest.xml
+++ b/tests/tests/os/AndroidManifest.xml
@@ -48,6 +48,7 @@
     <uses-permission android:name="android.permission.POWER_SAVER" />
     <uses-permission android:name="android.permission.INSTALL_DYNAMIC_SYSTEM" />
     <uses-permission android:name="android.permission.MANAGE_COMPANION_DEVICES" />
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
     <uses-permission android:name="android.os.cts.permission.TEST_GRANTED" />
 
diff --git a/tests/tests/os/CtsOsTestCases.xml b/tests/tests/os/CtsOsTestCases.xml
index 3718c59..7ce85d6 100644
--- a/tests/tests/os/CtsOsTestCases.xml
+++ b/tests/tests/os/CtsOsTestCases.xml
@@ -22,6 +22,15 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsOsTestCases.apk" />
     </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="force-install-mode" value="FULL"/>
+        <option name="test-file-name" value="CtsMockInputMethod.apk" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.DeviceSetup">
+        <option name="screen-always-on" value="on" />
+    </target_preparer>
+
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.os.cts" />
         <option name="runtime-hint" value="3m15s" />
diff --git a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
index db5550c..835f541 100644
--- a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
+++ b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
@@ -46,6 +46,7 @@
 
 private const val APK_PATH = "/data/local/tmp/cts/os/CtsAutoRevokeDummyApp.apk"
 private const val APK_PACKAGE_NAME = "android.os.cts.autorevokedummyapp"
+private const val READ_CALENDAR = "android.permission.READ_CALENDAR"
 
 /**
  * Test for auto revoke
@@ -278,39 +279,10 @@
     }
 
     private fun assertPermission(state: Int, packageName: String = APK_PACKAGE_NAME) {
-        // For some reason this incorrectly always returns PERMISSION_DENIED
-//        runWithShellPermissionIdentity {
-//            assertEquals(
-//                permissionStateToString(state),
-//                permissionStateToString(context.packageManager.checkPermission(READ_CALENDAR, APK_PACKAGE_NAME)))
-//        }
-
-        try {
-            goToPermissions(packageName)
-
-            waitForIdle()
-            val ui = instrumentation.uiAutomation.rootInActiveWindow
-            val permStateSection = ui.lowestCommonAncestor(
-                    { node -> node.textAsString.equals("Allowed", ignoreCase = true) },
-                    { node -> node.textAsString.equals("Denied", ignoreCase = true) }
-            ).assertNotNull {
-                "Cannot find permissions state section in\n${uiDump(ui)}"
-            }
-            val sectionHeaderIndex = permStateSection.children.indexOfFirst {
-                it?.depthFirstSearch { node ->
-                    node.textAsString.equals(
-                            if (state == PERMISSION_GRANTED) "Allowed" else "Denied",
-                            ignoreCase = true)
-                } != null
-            }
-            permStateSection.getChild(sectionHeaderIndex + 1).depthFirstSearch { node ->
-                node.textAsString.equals("Calendar", ignoreCase = true)
-            }.assertNotNull {
-                "Permission must be ${permissionStateToString(state)}\n${uiDump(ui)}"
-            }
-        } finally {
-            goBack()
-            goBack()
+        runWithShellPermissionIdentity {
+            assertEquals(
+                permissionStateToString(state),
+                permissionStateToString(context.packageManager.checkPermission(READ_CALENDAR, APK_PACKAGE_NAME)))
         }
     }
 
@@ -319,6 +291,7 @@
                 .setData(Uri.fromParts("package", packageName, null))
                 .addFlags(FLAG_ACTIVITY_NEW_TASK))
 
+        waitForIdle()
         click("Permissions")
     }
 
diff --git a/tests/tests/os/src/android/os/cts/FileObserverTest.java b/tests/tests/os/src/android/os/cts/FileObserverTest.java
index 9e61066..4c183e2 100644
--- a/tests/tests/os/src/android/os/cts/FileObserverTest.java
+++ b/tests/tests/os/src/android/os/cts/FileObserverTest.java
@@ -146,9 +146,9 @@
             expected = new int[] {UNDEFINED};
             moveEvents = waitForEvent(fileObserver);
             if (isEmulated)
-                assertEventsContains(expected, moveEvents);
+                assertEventsContains(testFile, expected, moveEvents);
             else
-                assertEventsEquals(expected, moveEvents);
+                assertEventsEquals(testFile, expected, moveEvents);
         } finally {
             fileObserver.stopWatching();
             if (out != null)
@@ -185,9 +185,9 @@
             };
             moveEvents = waitForEvent(movedFileObserver);
             if (isEmulated) {
-                assertEventsContains(expected, moveEvents);
+                assertEventsContains(testFile, expected, moveEvents);
             } else {
-                assertEventsEquals(expected, moveEvents);
+                assertEventsEquals(testFile, expected, moveEvents);
             }
         } finally {
             movedFileObserver.stopWatching();
@@ -213,9 +213,9 @@
 
         final FileEvent[] moveEvents = waitForEvent(fileObserver);
         if (isEmulated) {
-            assertEventsContains(expected, moveEvents);
+            assertEventsContains(testFile, expected, moveEvents);
         } else {
-            assertEventsEquals(expected, moveEvents);
+            assertEventsEquals(testFile, expected, moveEvents);
         }
     }
 
@@ -238,9 +238,9 @@
 
         final FileEvent[] moveEvents = waitForEvent(fileObserver);
         if (isEmulated) {
-            assertEventsContains(expected, moveEvents);
+            assertEventsContains(testFile, expected, moveEvents);
         } else {
-            assertEventsEquals(expected, moveEvents);
+            assertEventsEquals(testFile, expected, moveEvents);
         }
     }
 
@@ -311,26 +311,30 @@
         }
     }
 
-    private void assertEventsEquals(final int[] expected, final FileEvent[] moveEvents) {
+    private void assertEventsEquals(
+            File testFile, final int[] expected, final FileEvent[] moveEvents) {
         List<Integer> expectedEvents = new ArrayList<Integer>();
         for (int i = 0; i < expected.length; i++) {
             expectedEvents.add(expected[i]);
         }
         List<FileEvent> actualEvents = Arrays.asList(moveEvents);
-        String message = "Expected: " + expectedEvents + " Actual: " + actualEvents;
+        String message = "For test file [" + testFile.getAbsolutePath()
+                + "] expected: " + expectedEvents + " Actual: " + actualEvents;
         assertEquals(message, expected.length, moveEvents.length);
         for (int i = 0; i < expected.length; i++) {
             assertEquals(message, expected[i], moveEvents[i].event);
         }
     }
 
-    private void assertEventsContains(final int[] expected, final FileEvent[] moveEvents) {
+    private void assertEventsContains(
+            File testFile, final int[] expected, final FileEvent[] moveEvents) {
         List<Integer> expectedEvents = new ArrayList<Integer>();
         for (int i = 0; i < expected.length; i++) {
             expectedEvents.add(expected[i]);
         }
         List<FileEvent> actualEvents = Arrays.asList(moveEvents);
-        String message = "Expected to contain: " + expectedEvents + " Actual: " + actualEvents;
+        String message = "For test file [" + testFile.getAbsolutePath()
+                + "] expected: " + expectedEvents + " Actual: " + actualEvents;
         int j = 0;
         for (int i = 0; i < expected.length; i++) {
             while (expected[i] != moveEvents[j].event) {
diff --git a/tests/tests/os/src/android/os/cts/SimpleTestActivity.java b/tests/tests/os/src/android/os/cts/SimpleTestActivity.java
index 4242315..22c706f 100644
--- a/tests/tests/os/src/android/os/cts/SimpleTestActivity.java
+++ b/tests/tests/os/src/android/os/cts/SimpleTestActivity.java
@@ -16,7 +16,30 @@
 
 package android.os.cts;
 
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
+
 import android.app.Activity;
+import android.os.Bundle;
+import android.widget.EditText;
+import android.widget.LinearLayout;
 
 public class SimpleTestActivity extends Activity {
+    private EditText mEditText;
+
+    @Override
+    protected void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        mEditText = new EditText(this);
+        final LinearLayout layout = new LinearLayout(this);
+        layout.setOrientation(LinearLayout.VERTICAL);
+        layout.addView(mEditText);
+        setContentView(layout);
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        getWindow().setSoftInputMode(SOFT_INPUT_STATE_ALWAYS_VISIBLE);
+        mEditText.requestFocus();
+    }
 }
\ No newline at end of file
diff --git a/tests/tests/os/src/android/os/cts/StrictModeTest.java b/tests/tests/os/src/android/os/cts/StrictModeTest.java
index 8ed37ca..b1023f6 100644
--- a/tests/tests/os/src/android/os/cts/StrictModeTest.java
+++ b/tests/tests/os/src/android/os/cts/StrictModeTest.java
@@ -17,9 +17,15 @@
 package android.os.cts;
 
 import static android.content.Context.WINDOW_SERVICE;
+import static android.content.pm.PackageManager.FEATURE_INPUT_METHODS;
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
 
+import static com.android.cts.mockime.ImeEventStreamTestUtils.clearAllEvents;
+import static com.android.cts.mockime.ImeEventStreamTestUtils.expectCommand;
+import static com.android.cts.mockime.ImeEventStreamTestUtils.expectEvent;
+import static com.android.cts.mockime.ImeEventStreamTestUtils.notExpectEvent;
+
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
 
@@ -32,7 +38,7 @@
 import android.content.Intent;
 import android.content.ServiceConnection;
 import android.content.pm.PackageManager;
-import android.content.res.Resources;
+import android.content.res.Configuration;
 import android.hardware.display.DisplayManager;
 import android.inputmethodservice.InputMethodService;
 import android.net.TrafficStats;
@@ -63,10 +69,16 @@
 import android.view.ViewConfiguration;
 import android.view.WindowManager;
 
+import androidx.annotation.IntDef;
 import androidx.test.core.app.ApplicationProvider;
 import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.cts.mockime.ImeEvent;
+import com.android.cts.mockime.ImeEventStream;
+import com.android.cts.mockime.ImeSettings;
+import com.android.cts.mockime.MockImeSession;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -78,6 +90,8 @@
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.net.HttpURLConnection;
 import java.net.Socket;
 import java.net.URL;
@@ -96,10 +110,49 @@
 public class StrictModeTest {
     private static final String TAG = "StrictModeTest";
     private static final String REMOTE_SERVICE_ACTION = "android.app.REMOTESERVICE";
+    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(10); // 10 seconds
+    private static final long NOT_EXPECT_TIMEOUT = TimeUnit.SECONDS.toMillis(2);
 
     private StrictMode.ThreadPolicy mThreadPolicy;
     private StrictMode.VmPolicy mVmPolicy;
 
+    /**
+     * Verify mode to verifying if APIs violates incorrect context violation.
+     *
+     * @see #VERIFY_MODE_GET_DISPLAY
+     * @see #VERIFY_MODE_GET_WINDOW_MANAGER
+     * @see #VERIFY_MODE_GET_VIEW_CONFIGURATION
+     */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(flag = true, value = {
+            VERIFY_MODE_GET_DISPLAY,
+            VERIFY_MODE_GET_WINDOW_MANAGER,
+            VERIFY_MODE_GET_VIEW_CONFIGURATION,
+    })
+    private @interface VerifyMode {}
+
+    /**
+     * Verifies if {@link Context#getDisplay} from {@link InputMethodService} and context created
+     * from {@link InputMethodService#createConfigurationContext(Configuration)} violates
+     * incorrect context violation.
+     */
+    private static final int VERIFY_MODE_GET_DISPLAY = 1;
+    /**
+     * Verifies if get {@link android.view.WindowManager} from {@link InputMethodService} and
+     * context created from {@link InputMethodService#createConfigurationContext(Configuration)}
+     * violates incorrect context violation.
+     *
+     * @see Context#getSystemService(String)
+     * @see Context#getSystemService(Class)
+     */
+    private static final int VERIFY_MODE_GET_WINDOW_MANAGER = 2;
+    /**
+     * Verifies if passing {@link InputMethodService} and context created
+     * from {@link InputMethodService#createConfigurationContext(Configuration)} to
+     * {@link android.view.ViewConfiguration#get(Context)} violates incorrect context violation.
+     */
+    private static final int VERIFY_MODE_GET_VIEW_CONFIGURATION = 3;
+
     private Context getContext() {
         return ApplicationProvider.getApplicationContext();
     }
@@ -647,6 +700,9 @@
         final Activity activity = InstrumentationRegistry.getInstrumentation()
                 .startActivitySync(intent);
         assertNoViolation(() -> activity.getSystemService(WINDOW_SERVICE));
+
+        // TODO(b/159593676): move the logic to CtsInputMethodTestCases
+        verifyIms(VERIFY_MODE_GET_WINDOW_MANAGER);
     }
 
     @Test
@@ -669,10 +725,13 @@
 
         Intent intent = new Intent(getContext(), SimpleTestActivity.class);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
         final Activity activity = InstrumentationRegistry.getInstrumentation()
                 .startActivitySync(intent);
         assertNoViolation(() -> activity.getDisplay());
 
+        // TODO(b/159593676): move the logic to CtsInputMethodTestCases
+        verifyIms(VERIFY_MODE_GET_DISPLAY);
         try {
             getContext().getApplicationContext().getDisplay();
         } catch (UnsupportedOperationException e) {
@@ -691,14 +750,14 @@
 
         final Context baseContext = getContext();
         assertViolation(
-                "Tried to access UI constants from a non-visual Context.",
+                "Tried to access UI constants from a non-visual Context:",
                 () -> ViewConfiguration.get(baseContext));
 
         final Display display = baseContext.getSystemService(DisplayManager.class)
                 .getDisplay(DEFAULT_DISPLAY);
         final Context displayContext = baseContext.createDisplayContext(display);
         assertViolation(
-                "Tried to access UI constants from a non-visual Context.",
+                "Tried to access UI constants from a non-visual Context:",
                 () -> ViewConfiguration.get(displayContext));
 
         final Context windowContext =
@@ -711,14 +770,55 @@
                 .startActivitySync(intent);
         assertNoViolation(() -> ViewConfiguration.get(activity));
 
-        final TestInputMethodService ims = new TestInputMethodService(getContext());
-        assertNoViolation(() -> ViewConfiguration.get(ims));
+        // TODO(b/159593676): move the logic to CtsInputMethodTestCases
+        verifyIms(VERIFY_MODE_GET_VIEW_CONFIGURATION);
     }
 
-    private static class TestInputMethodService extends InputMethodService {
-        private TestInputMethodService(Context baseContext) {
-           attachBaseContext(baseContext);
+    // TODO(b/159593676): move the logic to CtsInputMethodTestCases
+    /**
+     * Verify if APIs violates incorrect context violations by {@code mode}.
+     *
+     * @see VerifyMode
+     */
+    private void verifyIms(@VerifyMode int mode) throws Exception {
+        // If devices do not support installable IMEs, finish the test gracefully. We don't use
+        // assumeTrue here because we do pass some cases, so showing "pass" instead of "skip" makes
+        // sense here.
+        if (!supportsInstallableIme()) {
+            return;
         }
+
+        try (final MockImeSession imeSession = MockImeSession.create(getContext(),
+                InstrumentationRegistry.getInstrumentation().getUiAutomation(),
+                new ImeSettings.Builder().setStrictModeEnabled(true))) {
+            final ImeEventStream stream = imeSession.openEventStream();
+            expectEvent(stream, event -> "onStartInput".equals(event.getEventName()), TIMEOUT);
+            final ImeEventStream forkedStream = clearAllEvents(stream, "onStrictModeViolated");
+            final ImeEvent imeEvent;
+            switch (mode) {
+                case VERIFY_MODE_GET_DISPLAY:
+                    imeEvent = expectCommand(forkedStream, imeSession.callVerifyGetDisplay(),
+                            TIMEOUT);
+                    break;
+                case VERIFY_MODE_GET_WINDOW_MANAGER:
+                    imeEvent = expectCommand(forkedStream, imeSession.callVerifyGetWindowManager(),
+                            TIMEOUT);
+                    break;
+                case VERIFY_MODE_GET_VIEW_CONFIGURATION:
+                    imeEvent = expectCommand(forkedStream,
+                            imeSession.callVerifyGetViewConfiguration(), TIMEOUT);
+                    break;
+                default:
+                    imeEvent = null;
+            }
+            assertTrue(imeEvent.getReturnBooleanValue());
+            notExpectEvent(stream, event -> "onStrictModeViolated".equals(event.getEventName()),
+                    NOT_EXPECT_TIMEOUT);
+        }
+    }
+
+    private boolean supportsInstallableIme() {
+        return getContext().getPackageManager().hasSystemFeature(FEATURE_INPUT_METHODS);
     }
 
     private static void runWithRemoteServiceBound(Context context, Consumer<ISecondary> consumer)
diff --git a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/IntentTest.kt b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/IntentTest.kt
index 9a24968..33a8966 100644
--- a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/IntentTest.kt
+++ b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/IntentTest.kt
@@ -24,9 +24,6 @@
 import androidx.test.InstrumentationRegistry
 import androidx.test.runner.AndroidJUnit4
 
-import com.android.compatibility.common.util.SystemUtil.runShellCommand
-import com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity
-
 import org.junit.After
 import org.junit.Assert.assertEquals
 import org.junit.Test
@@ -42,12 +39,6 @@
 class IntentTest : PackageInstallerTestBase() {
     private val context = InstrumentationRegistry.getTargetContext()
 
-    private fun setSecureFrp(secureFrp: Boolean) {
-        runWithShellPermissionIdentity {
-            runShellCommand("settings put secure secure_frp_mode ${if (secureFrp) 1 else 0}")
-        }
-    }
-
     @After
     fun disableSecureFrp() {
         setSecureFrp(false)
diff --git a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/PackageInstallerTestBase.kt b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/PackageInstallerTestBase.kt
index ad7c7fd..45eb038 100644
--- a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/PackageInstallerTestBase.kt
+++ b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/PackageInstallerTestBase.kt
@@ -198,6 +198,11 @@
         uiDevice.executeShellCommand("settings put secure $secureSetting $value")
     }
 
+    fun setSecureFrp(secureFrp: Boolean) {
+        uiDevice.executeShellCommand("settings --user 0 " +
+                "put secure secure_frp_mode ${if (secureFrp) 1 else 0}")
+    }
+
     @After
     fun unregisterInstallResultReceiver() {
         try {
diff --git a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/SessionTest.kt b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/SessionTest.kt
index 24a1128..69096f8 100644
--- a/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/SessionTest.kt
+++ b/tests/tests/packageinstaller/install/src/android/packageinstaller/install/cts/SessionTest.kt
@@ -98,7 +98,7 @@
     @Test
     fun confirmFrpInstallationFails() {
         try {
-            setSecureSetting("secure_frp_mode", 1)
+            setSecureFrp(true)
 
             try {
                 val installation = startInstallationViaSession()
@@ -111,7 +111,7 @@
             // Install should never have started
             assertNotInstalled()
         } finally {
-            setSecureSetting("secure_frp_mode", 0)
+            setSecureFrp(false)
         }
     }
 }
diff --git a/tests/tests/permission/Android.bp b/tests/tests/permission/Android.bp
index c869fab..6a41098 100644
--- a/tests/tests/permission/Android.bp
+++ b/tests/tests/permission/Android.bp
@@ -38,7 +38,10 @@
         "libctspermission_jni",
         "libnativehelper_compat_libc++",
     ],
-    srcs: ["src/**/*.java"],
+    srcs: [
+        "src/**/*.java",
+        "src/**/*.aidl"
+    ],
     sdk_version: "test_current",
     libs: [
         "android.test.runner.stubs",
diff --git a/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp b/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp
index d9432c8..04faf1b 100644
--- a/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp
+++ b/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp
@@ -24,5 +24,8 @@
         "vts10",
         "general-tests",
     ],
-    srcs: ["src/**/*.java"],
+    srcs: [
+        "src/**/*.java",
+        "src/**/*.aidl"
+    ],
 }
diff --git a/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/AccessLocationOnCommand.java b/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/AccessLocationOnCommand.java
index 77e9f9a..b248f3c 100644
--- a/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/AccessLocationOnCommand.java
+++ b/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/AccessLocationOnCommand.java
@@ -24,42 +24,47 @@
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
-import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
+import android.os.Looper;
 
 public class AccessLocationOnCommand extends Service {
     // Longer than the STATE_SETTLE_TIME in AppOpsManager
     private static final long BACKGROUND_ACCESS_SETTLE_TIME = 11000;
 
-    private void getLocation() {
-        Criteria crit = new Criteria();
-        crit.setAccuracy(ACCURACY_FINE);
+    private IAccessLocationOnCommand.Stub mBinder = new IAccessLocationOnCommand.Stub() {
+        public void accessLocation() {
+            new Handler(Looper.getMainLooper()).postDelayed(() -> {
+                Criteria crit = new Criteria();
+                crit.setAccuracy(ACCURACY_FINE);
 
-        getSystemService(LocationManager.class).requestSingleUpdate(crit, new LocationListener() {
-            @Override
-            public void onLocationChanged(Location location) {
-            }
+                AccessLocationOnCommand.this.getSystemService(LocationManager.class)
+                        .requestSingleUpdate(crit, new LocationListener() {
+                            @Override
+                            public void onLocationChanged(Location location) {
+                            }
 
-            @Override
-            public void onStatusChanged(String provider, int status, Bundle extras) {
-            }
+                            @Override
+                            public void onStatusChanged(String provider, int status,
+                                    Bundle extras) {
+                            }
 
-            @Override
-            public void onProviderEnabled(String provider) {
-            }
+                            @Override
+                            public void onProviderEnabled(String provider) {
+                            }
 
-            @Override
-            public void onProviderDisabled(String provider) {
-            }
-        }, null);
-    }
+                            @Override
+                            public void onProviderDisabled(String provider) {
+                            }
+                        }, null);
+            }, BACKGROUND_ACCESS_SETTLE_TIME);
+        }
+    };
 
     @Override
     public IBinder onBind(Intent intent) {
-        (new Handler()).postDelayed(this::getLocation, BACKGROUND_ACCESS_SETTLE_TIME);
-        return new Binder();
+        return mBinder;
     }
 
     @Override
diff --git a/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/IAccessLocationOnCommand.aidl b/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/IAccessLocationOnCommand.aidl
new file mode 100644
index 0000000..be92ed1
--- /dev/null
+++ b/tests/tests/permission/AppThatAccessesLocationOnCommand/src/android/permission/cts/appthataccesseslocation/IAccessLocationOnCommand.aidl
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.permission.cts.appthataccesseslocation;
+
+interface IAccessLocationOnCommand {
+    /** Access location on command */
+    void accessLocation();
+}
\ No newline at end of file
diff --git a/tests/tests/permission/OWNERS b/tests/tests/permission/OWNERS
index 7ad5960..a383144 100644
--- a/tests/tests/permission/OWNERS
+++ b/tests/tests/permission/OWNERS
@@ -6,3 +6,4 @@
 per-file MainlineNetworkStackPermissionTest.java = file: platform/frameworks/base:/services/net/OWNERS
 per-file Camera2PermissionTest.java = file: platform/frameworks/av:/camera/OWNERS
 per-file OneTimePermissionTest.java, AppThatRequestOneTimePermission/... = evanseverson@google.com
+per-file LocationAccessCheckTest.java = ntmyren@google.com
diff --git a/tests/tests/permission/src/android/permission/cts/ActivityPermissionRationaleTest.java b/tests/tests/permission/src/android/permission/cts/ActivityPermissionRationaleTest.java
index 947e59a..1837b32 100644
--- a/tests/tests/permission/src/android/permission/cts/ActivityPermissionRationaleTest.java
+++ b/tests/tests/permission/src/android/permission/cts/ActivityPermissionRationaleTest.java
@@ -84,7 +84,8 @@
 
     @Before
     public void clearData() {
-        runShellCommand("pm clear android.permission.cts.appthatrunsrationaletests");
+        runShellCommand("pm clear --user " + sContext.getUserId()
+                + " android.permission.cts.appthatrunsrationaletests");
         PermissionUtils.setPermissionFlags(PACKAGE_NAME, PERMISSION_NAME,
                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0);
     }
diff --git a/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java b/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
index 62a5a44..53b7d18 100644
--- a/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
+++ b/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
@@ -20,6 +20,7 @@
 import static android.Manifest.permission.ACCESS_FINE_LOCATION;
 import static android.app.Notification.EXTRA_TITLE;
 import static android.content.Context.BIND_AUTO_CREATE;
+import static android.content.Context.BIND_NOT_FOREGROUND;
 import static android.content.Intent.ACTION_BOOT_COMPLETED;
 import static android.content.Intent.FLAG_RECEIVER_FOREGROUND;
 import static android.location.Criteria.ACCURACY_FINE;
@@ -34,6 +35,7 @@
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
@@ -56,6 +58,8 @@
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.Looper;
+import android.os.SystemClock;
+import android.permission.cts.appthataccesseslocation.IAccessLocationOnCommand;
 import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.SecurityTest;
 import android.provider.DeviceConfig;
@@ -101,7 +105,8 @@
             "/data/local/tmp/cts/permissions/AppThatDoesNotHaveBgLocationAccess.apk";
 
     /** Whether to show location access check notifications. */
-    private static final String PROPERTY_LOCATION_ACCESS_CHECK_ENABLED = "location_access_check_enabled";
+    private static final String PROPERTY_LOCATION_ACCESS_CHECK_ENABLED =
+            "location_access_check_enabled";
 
     private static final long UNEXPECTED_TIMEOUT_MILLIS = 10000;
     private static final long EXPECTED_TIMEOUT_MILLIS = 1000;
@@ -125,28 +130,20 @@
      */
     private static Boolean sCanAccessFineLocation = null;
 
-    private ServiceConnection mConnection;
+    private static ServiceConnection sConnection;
+    private static IAccessLocationOnCommand sLocationAccessor;
+
     /**
      * Connected to {@value #TEST_APP_PKG} and make it access the location in the background
      */
-    private void accessLocation() {
-        mConnection = new ServiceConnection() {
-            @Override
-            public void onServiceConnected(ComponentName name, IBinder service) {
-                // ignore
-            }
-
-            @Override
-            public void onServiceDisconnected(ComponentName name) {
-                // ignore
-            }
-        };
-
-        // Connect and disconnect to service. After the service is disconnected it causes a
-        // access to the location
-        Intent testAppService = new Intent();
-        testAppService.setComponent(new ComponentName(TEST_APP_PKG, TEST_APP_SERVICE));
-        sContext.bindService(testAppService, mConnection, BIND_AUTO_CREATE);
+    private void accessLocation() throws Throwable {
+        if (sConnection == null || sLocationAccessor == null) {
+            bindService();
+        }
+        eventually(() -> {
+            assertNotNull(sLocationAccessor);
+            sLocationAccessor.accessLocation();
+        }, EXPECTED_TIMEOUT_MILLIS);
     }
 
     /**
@@ -183,9 +180,7 @@
      *
      * @param r       The {@link ThrowingCallable} to run.
      * @param timeout the maximum time to wait
-     *
      * @return the return value from the callable
-     *
      * @throws NullPointerException If the return value never becomes non-null
      */
     public static <T> T eventually(@NonNull ThrowingCallable<T> r, long timeout) throws Throwable {
@@ -225,6 +220,7 @@
      * @param pkg The name of the package to be cleared
      */
     private static void clearPackageData(@NonNull String pkg) {
+        unbindService();
         runShellCommand("pm clear --user -2 " + pkg);
     }
 
@@ -254,16 +250,24 @@
         return null;
     }
 
+    private StatusBarNotification getNotification(boolean cancelNotification) throws Throwable {
+        return getNotification(cancelNotification, false);
+    }
+
     /**
      * Get a location access notification that is currently visible.
      *
      * @param cancelNotification if {@code true} the notification is canceled inside this method
-     *
+     * @param returnImmediately if {@code true} this method returns immediately after checking once
+     *                          for the notification
      * @return The notification or {@code null} if there is none
      */
-    private StatusBarNotification getNotification(boolean cancelNotification) throws Throwable {
+    private StatusBarNotification getNotification(boolean cancelNotification,
+            boolean returnImmediately) throws Throwable {
         NotificationListenerService notificationService = NotificationListener.getInstance();
-        long start = System.currentTimeMillis();
+        long start = SystemClock.elapsedRealtime();
+        long timeout = returnImmediately ? 0 : LOCATION_ACCESS_TIMEOUT_MILLIS
+                + BACKGROUND_ACCESS_SETTLE_TIME;
         while (true) {
             runLocationCheck();
 
@@ -271,8 +275,7 @@
             if (notification == null) {
                 // Sometimes getting a location takes some time, hence not getting a notification
                 // can be caused by not having gotten a location yet
-                if (System.currentTimeMillis() - start < LOCATION_ACCESS_TIMEOUT_MILLIS
-                        + BACKGROUND_ACCESS_SETTLE_TIME) {
+                if (SystemClock.elapsedRealtime() - start < timeout) {
                     Thread.sleep(200);
                     continue;
                 }
@@ -336,19 +339,42 @@
 
     @BeforeClass
     public static void installBackgroundAccessApp() {
-        runShellCommand("pm install -r -g " + TEST_APP_LOCATION_BG_ACCESS_APK);
+        installBackgroundAccessApp(false);
+    }
+
+    private static void installBackgroundAccessApp(boolean isDowngrade) {
+        String command = "pm install -r -g ";
+        if (isDowngrade) {
+            command = command + "-d ";
+        }
+        String output = runShellCommand(command + TEST_APP_LOCATION_BG_ACCESS_APK);
+        assertTrue(output.contains("Success"));
     }
 
     @AfterClass
     public static void uninstallBackgroundAccessApp() {
+        unbindService();
         runShellCommand("pm uninstall " + TEST_APP_PKG);
     }
 
+    private static void unbindService() {
+        if (sConnection != null) {
+            sContext.unbindService(sConnection);
+        }
+        sConnection = null;
+        sLocationAccessor = null;
+    }
+
 
     private static void installForegroundAccessApp() {
+        unbindService();
         runShellCommand("pm install -r -g " + TEST_APP_LOCATION_FG_ACCESS_APK);
     }
 
+    private static void uninstallForegroundAccessApp() {
+        runShellCommand("pm uninstall " + TEST_APP_LOCATION_FG_ACCESS_APK);
+    }
+
     /**
      * Skip each test for low ram device
      */
@@ -357,6 +383,27 @@
         assumeFalse(sActivityManager.isLowRamDevice());
     }
 
+    @Before
+    public void bindService() {
+        sConnection = new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                sLocationAccessor = IAccessLocationOnCommand.Stub.asInterface(service);
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                sConnection = null;
+                sLocationAccessor = null;
+            }
+        };
+
+        Intent testAppService = new Intent();
+        testAppService.setComponent(new ComponentName(TEST_APP_PKG, TEST_APP_SERVICE));
+
+        sContext.bindService(testAppService, sConnection, BIND_AUTO_CREATE | BIND_NOT_FOREGROUND);
+    }
+
     /**
      * Reset the permission controllers state before each test
      */
@@ -481,7 +528,7 @@
     @AfterClass
     public static void disallowNotificationAccess() {
         runShellCommand("cmd notification disallow_listener " + (new ComponentName(sContext,
-                        NotificationListener.class)).flattenToString());
+                NotificationListener.class)).flattenToString());
     }
 
     /**
@@ -510,10 +557,9 @@
     }
 
     @After
-    public void locationUnbind() {
-        if (mConnection != null) {
-            sContext.unbindService(mConnection);
-        }
+    public void locationUnbind() throws Throwable {
+        unbindService();
+        getNotification(true, true);
     }
 
     @Test
@@ -523,7 +569,7 @@
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void notificationIsShownOnlyOnce() throws Throwable {
         accessLocation();
         getNotification(true);
@@ -532,7 +578,7 @@
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void notificationIsShownAgainAfterClear() throws Throwable {
         accessLocation();
         getNotification(true);
@@ -564,12 +610,12 @@
 
         eventually(() -> {
             accessLocation();
-            assertNotNull(getNotification(false));
+            assertNotNull(getNotification(true));
         }, UNEXPECTED_TIMEOUT_MILLIS);
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void removeNotificationOnUninstall() throws Throwable {
         accessLocation();
         getNotification(false);
@@ -604,12 +650,12 @@
 
             fail("Location access notification was shown");
         } finally {
-            installBackgroundAccessApp();
+            installBackgroundAccessApp(true);
         }
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void noNotificationIfFeatureDisabled() throws Throwable {
         disableLocationAccessCheck();
         accessLocation();
@@ -617,7 +663,7 @@
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void notificationOnlyForAccessesSinceFeatureWasEnabled() throws Throwable {
         // Disable the feature and access location in disabled state
         disableLocationAccessCheck();
@@ -634,8 +680,9 @@
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void noNotificationIfBlamerNotSystemOrLocationProvider() throws Throwable {
+        getNotification(true);
         // Blame the app for access from an untrusted for notification purposes package.
         runWithShellPermissionIdentity(() -> {
             AppOpsManager appOpsManager = sContext.getSystemService(AppOpsManager.class);
@@ -646,7 +693,7 @@
     }
 
     @Test
-    @SecurityTest(minPatchLevel="2019-12-01")
+    @SecurityTest(minPatchLevel = "2019-12-01")
     public void testOpeningLocationSettingsDoesNotTriggerAccess() throws Throwable {
         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
diff --git a/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java b/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java
index fac3aab..8609e33 100644
--- a/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java
+++ b/tests/tests/permission/src/android/permission/cts/ServicesInstantAppsCannotAccessTests.java
@@ -25,18 +25,14 @@
 import static android.content.Context.WIFI_P2P_SERVICE;
 import static android.content.Context.WIFI_SERVICE;
 
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNull;
 
-import android.app.WallpaperManager;
 import android.content.Context;
 import android.platform.test.annotations.AppModeInstant;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.compatibility.common.util.RequiredServiceRule;
-
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -72,14 +68,8 @@
 
     @Test
     public void cannotGetWallpaperManager() {
-        WallpaperManager mgr  = (WallpaperManager) InstrumentationRegistry.getTargetContext()
-                .getSystemService(WALLPAPER_SERVICE);
-        boolean supported = RequiredServiceRule.hasService("wallpaper");
-        if (supported) {
-            assertNull(mgr);
-        } else {
-            assertFalse(mgr.isWallpaperSupported());
-        }
+        assertNull(InstrumentationRegistry.getTargetContext().getSystemService(
+                WALLPAPER_SERVICE));
     }
 
     @Test
diff --git a/tests/tests/permission/src/android/permission/cts/appthataccesseslocation/IAccessLocationOnCommand.aidl b/tests/tests/permission/src/android/permission/cts/appthataccesseslocation/IAccessLocationOnCommand.aidl
new file mode 100644
index 0000000..be92ed1
--- /dev/null
+++ b/tests/tests/permission/src/android/permission/cts/appthataccesseslocation/IAccessLocationOnCommand.aidl
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.permission.cts.appthataccesseslocation;
+
+interface IAccessLocationOnCommand {
+    /** Access location on command */
+    void accessLocation();
+}
\ No newline at end of file
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index 2f4d98c..302e55b 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -4995,6 +4995,10 @@
     <permission android:name="android.permission.ACCESS_TV_DESCRAMBLER"
         android:protectionLevel="signature|privileged|vendorPrivileged" />
 
+    <!-- Allows an application to create trusted displays. @hide -->
+    <permission android:name="android.permission.ADD_TRUSTED_DISPLAY"
+                android:protectionLevel="signature" />
+
     <!-- @hide @SystemApi Allows an application to access locusId events in the usage stats. -->
     <permission android:name="android.permission.ACCESS_LOCUS_ID_USAGE_STATS"
                 android:protectionLevel="signature|appPredictor" />
diff --git a/tests/tests/permission2/res/raw/automotive_android_manifest.xml b/tests/tests/permission2/res/raw/automotive_android_manifest.xml
index dac484b..dd37ac9 100644
--- a/tests/tests/permission2/res/raw/automotive_android_manifest.xml
+++ b/tests/tests/permission2/res/raw/automotive_android_manifest.xml
@@ -15,205 +15,340 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
-        package="com.android.car"
-        coreApp="true"
-        android:sharedUserId="android.uid.system">
+     xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
+     package="com.android.car"
+     coreApp="true"
+     android:sharedUserId="android.uid.system">
 
-    <original-package android:name="com.android.car" />
-     <permission-group
-        android:name="android.car.permission-group.CAR_MONITORING"
-        android:icon="@drawable/perm_group_car"
-        android:description="@string/car_permission_desc"
-        android:label="@string/car_permission_label" />
-    <permission
-        android:name="android.car.permission.CAR_ENERGY"
-        android:permissionGroup="android.car.permission-group.CAR_MONITORING"
-        android:protectionLevel="dangerous"
-        android:label="@string/car_permission_label_energy"
-        android:description="@string/car_permission_desc_energy" />
-    <permission
-        android:name="android.car.permission.CAR_IDENTIFICATION"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_identification"
-        android:description="@string/car_permission_desc_car_identification" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_CLIMATE"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_hvac"
-        android:description="@string/car_permission_desc_hvac" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_DOORS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_car_doors"
-        android:description="@string/car_permission_desc_control_car_doors" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_WINDOWS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_car_windows"
-        android:description="@string/car_permission_desc_control_car_windows" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_MIRRORS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_car_mirrors"
-        android:description="@string/car_permission_desc_control_car_mirrors" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_SEATS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_car_seats"
-        android:description="@string/car_permission_desc_control_car_seats" />
-    <permission
-        android:name="android.car.permission.CAR_MILEAGE"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_mileage"
-        android:description="@string/car_permission_desc_mileage" />
-    <permission
-        android:name="android.car.permission.CAR_TIRES"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_tires"
-        android:description="@string/car_permission_desc_car_tires" />
-    <permission
-        android:name="android.car.permission.READ_CAR_STEERING"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_steering"
-        android:description="@string/car_permission_desc_car_steering" />
-    <permission
-        android:name="android.car.permission.READ_CAR_DISPLAY_UNITS"
-        android:protectionLevel="normal"
-        android:label="@string/car_permission_label_read_car_display_units"
-        android:description="@string/car_permission_desc_read_car_display_units" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_DISPLAY_UNITS"
-        android:protectionLevel="normal"
-        android:label="@string/car_permission_label_control_car_display_units"
-        android:description="@string/car_permission_desc_control_car_display_units" />
-    <permission
-        android:name="android.car.permission.CAR_SPEED"
-        android:permissionGroup="android.permission-group.LOCATION"
-        android:protectionLevel="dangerous"
-        android:label="@string/car_permission_label_speed"
-        android:description="@string/car_permission_desc_speed" />
-    <permission
-        android:name="android.car.permission.CAR_ENERGY_PORTS"
-        android:protectionLevel="normal"
-        android:label="@string/car_permission_label_car_energy_ports"
-        android:description="@string/car_permission_desc_car_energy_ports" />
-    <permission
-        android:name="android.car.permission.CAR_ENGINE_DETAILED"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_engine_detailed"
-        android:description="@string/car_permission_desc_car_engine_detailed" />
-    <permission
-        android:name="android.car.permission.CAR_DYNAMICS_STATE"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_vehicle_dynamics_state"
-        android:description="@string/car_permission_desc_vehicle_dynamics_state" />
-    <permission
-        android:name="android.car.permission.CAR_VENDOR_EXTENSION"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_vendor_extension"
-        android:description="@string/car_permission_desc_vendor_extension" />
-    <permission
-        android:name="android.car.permission.CAR_PROJECTION"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_projection"
-        android:description="@string/car_permission_desc_projection" />
-    <permission
-            android:name="android.car.permission.ACCESS_CAR_PROJECTION_STATUS"
-            android:protectionLevel="system|signature"
-            android:label="@string/car_permission_label_access_projection_status"
-            android:description="@string/car_permission_desc_access_projection_status" />
-    <permission
-            android:name="android.car.permission.BIND_PROJECTION_SERVICE"
-            android:protectionLevel="signature"
-            android:label="@string/car_permission_label_bind_projection_service"
-            android:description="@string/car_permission_desc_bind_projection_service" />
-    <permission
-        android:name="android.car.permission.CAR_MOCK_VEHICLE_HAL"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_mock_vehicle_hal"
-        android:description="@string/car_permission_desc_mock_vehicle_hal" />
-    <permission
-        android:name="android.car.permission.CAR_INFO"
-        android:protectionLevel="normal"
-        android:label="@string/car_permission_label_car_info"
-        android:description="@string/car_permission_desc_car_info" />
-    <permission
-        android:name="android.car.permission.CAR_EXTERIOR_ENVIRONMENT"
-        android:protectionLevel="normal"
-        android:label="@string/car_permission_label_car_exterior_environment"
-        android:description="@string/car_permission_desc_car_exterior_environment" />
-    <permission
-        android:name="android.car.permission.CAR_EXTERIOR_LIGHTS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_exterior_lights"
-        android:description="@string/car_permission_desc_car_exterior_lights" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_EXTERIOR_LIGHTS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_car_exterior_lights"
-        android:description="@string/car_permission_desc_control_car_exterior_lights" />
-    <permission
-        android:name="android.car.permission.READ_CAR_INTERIOR_LIGHTS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_interior_lights"
-        android:description="@string/car_permission_desc_car_interior_lights" />
-    <permission
-        android:name="android.car.permission.CONTROL_CAR_INTERIOR_LIGHTS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_car_interior_lights"
-        android:description="@string/car_permission_desc_control_car_interior_lights" />
-    <permission
-        android:name="android.car.permission.CAR_POWER"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_car_power"
-        android:description="@string/car_permission_desc_car_power" />
-    <permission
-        android:name="android.car.permission.CAR_POWERTRAIN"
-        android:protectionLevel="normal"
-        android:label="@string/car_permission_label_car_powertrain"
-        android:description="@string/car_permission_desc_car_powertrain" />
-    <permission
-        android:name="android.car.permission.CAR_NAVIGATION_MANAGER"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_car_navigation_manager"
-        android:description="@string/car_permission_desc_car_navigation_manager" />
-    <permission
-        android:name="android.car.permission.CAR_DIAGNOSTICS"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_diag_read"
-        android:description="@string/car_permission_desc_diag_read" />
-    <permission
-      android:name="android.car.permission.CLEAR_CAR_DIAGNOSTICS"
-      android:protectionLevel="system|signature"
-      android:label="@string/car_permission_label_diag_clear"
-      android:description="@string/car_permission_desc_diag_clear" />
-    <permission
-        android:name="android.car.permission.BIND_VMS_CLIENT"
-        android:protectionLevel="signature"
-        android:label="@string/car_permission_label_bind_vms_client"
-        android:description="@string/car_permission_desc_bind_vms_client" />
-    <permission
-        android:name="android.car.permission.VMS_PUBLISHER"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_vms_publisher"
-        android:description="@string/car_permission_desc_vms_publisher" />
-    <permission
-        android:name="android.car.permission.VMS_SUBSCRIBER"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_vms_subscriber"
-        android:description="@string/car_permission_desc_vms_subscriber" />
-    <permission
-        android:name="android.car.permission.CAR_DRIVING_STATE"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_driving_state"
-        android:description="@string/car_permission_desc_driving_state" />
+    <original-package android:name="com.android.car"/>
+     <permission-group android:name="android.car.permission-group.CAR_MONITORING"
+          android:icon="@drawable/perm_group_car"
+          android:description="@string/car_permission_desc"
+          android:label="@string/car_permission_label"/>
+    <permission android:name="android.car.permission.CAR_ENERGY"
+         android:permissionGroup="android.car.permission-group.CAR_MONITORING"
+         android:protectionLevel="dangerous"
+         android:label="@string/car_permission_label_energy"
+         android:description="@string/car_permission_desc_energy"/>
+    <permission android:name="android.car.permission.CAR_IDENTIFICATION"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_identification"
+         android:description="@string/car_permission_desc_car_identification"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_CLIMATE"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_hvac"
+         android:description="@string/car_permission_desc_hvac"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_DOORS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_car_doors"
+         android:description="@string/car_permission_desc_control_car_doors"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_WINDOWS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_car_windows"
+         android:description="@string/car_permission_desc_control_car_windows"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_MIRRORS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_car_mirrors"
+         android:description="@string/car_permission_desc_control_car_mirrors"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_SEATS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_car_seats"
+         android:description="@string/car_permission_desc_control_car_seats"/>
+    <permission android:name="android.car.permission.CAR_MILEAGE"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_mileage"
+         android:description="@string/car_permission_desc_mileage"/>
+    <permission android:name="android.car.permission.CAR_TIRES"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_tires"
+         android:description="@string/car_permission_desc_car_tires"/>
+    <permission android:name="android.car.permission.READ_CAR_STEERING"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_steering"
+         android:description="@string/car_permission_desc_car_steering"/>
+    <permission android:name="android.car.permission.READ_CAR_DISPLAY_UNITS"
+         android:protectionLevel="normal"
+         android:label="@string/car_permission_label_read_car_display_units"
+         android:description="@string/car_permission_desc_read_car_display_units"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_DISPLAY_UNITS"
+         android:protectionLevel="normal"
+         android:label="@string/car_permission_label_control_car_display_units"
+         android:description="@string/car_permission_desc_control_car_display_units"/>
+    <permission android:name="android.car.permission.CAR_SPEED"
+         android:permissionGroup="android.permission-group.LOCATION"
+         android:protectionLevel="dangerous"
+         android:label="@string/car_permission_label_speed"
+         android:description="@string/car_permission_desc_speed"/>
+    <permission android:name="android.car.permission.CAR_ENERGY_PORTS"
+         android:protectionLevel="normal"
+         android:label="@string/car_permission_label_car_energy_ports"
+         android:description="@string/car_permission_desc_car_energy_ports"/>
+    <permission android:name="android.car.permission.CAR_ENGINE_DETAILED"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_engine_detailed"
+         android:description="@string/car_permission_desc_car_engine_detailed"/>
+    <permission android:name="android.car.permission.CAR_DYNAMICS_STATE"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_vehicle_dynamics_state"
+         android:description="@string/car_permission_desc_vehicle_dynamics_state"/>
+    <permission android:name="android.car.permission.CAR_VENDOR_EXTENSION"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_vendor_extension"
+         android:description="@string/car_permission_desc_vendor_extension"/>
+    <permission android:name="android.car.permission.CAR_PROJECTION"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_projection"
+         android:description="@string/car_permission_desc_projection"/>
+    <permission android:name="android.car.permission.ACCESS_CAR_PROJECTION_STATUS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_access_projection_status"
+         android:description="@string/car_permission_desc_access_projection_status"/>
+    <permission android:name="android.car.permission.BIND_PROJECTION_SERVICE"
+         android:protectionLevel="signature"
+         android:label="@string/car_permission_label_bind_projection_service"
+         android:description="@string/car_permission_desc_bind_projection_service"/>
+    <permission android:name="android.car.permission.CAR_MOCK_VEHICLE_HAL"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_mock_vehicle_hal"
+         android:description="@string/car_permission_desc_mock_vehicle_hal"/>
+    <permission android:name="android.car.permission.CAR_INFO"
+         android:protectionLevel="normal"
+         android:label="@string/car_permission_label_car_info"
+         android:description="@string/car_permission_desc_car_info"/>
+    <permission android:name="android.car.permission.CAR_EXTERIOR_ENVIRONMENT"
+         android:protectionLevel="normal"
+         android:label="@string/car_permission_label_car_exterior_environment"
+         android:description="@string/car_permission_desc_car_exterior_environment"/>
+    <permission android:name="android.car.permission.CAR_EXTERIOR_LIGHTS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_exterior_lights"
+         android:description="@string/car_permission_desc_car_exterior_lights"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_EXTERIOR_LIGHTS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_car_exterior_lights"
+         android:description="@string/car_permission_desc_control_car_exterior_lights"/>
+    <permission android:name="android.car.permission.READ_CAR_INTERIOR_LIGHTS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_interior_lights"
+         android:description="@string/car_permission_desc_car_interior_lights"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_INTERIOR_LIGHTS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_car_interior_lights"
+         android:description="@string/car_permission_desc_control_car_interior_lights"/>
+    <permission android:name="android.car.permission.CAR_POWER"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_car_power"
+         android:description="@string/car_permission_desc_car_power"/>
+    <permission android:name="android.car.permission.CAR_POWERTRAIN"
+         android:protectionLevel="normal"
+         android:label="@string/car_permission_label_car_powertrain"
+         android:description="@string/car_permission_desc_car_powertrain"/>
+    <permission android:name="android.car.permission.CAR_NAVIGATION_MANAGER"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_car_navigation_manager"
+         android:description="@string/car_permission_desc_car_navigation_manager"/>
+    <permission android:name="android.car.permission.CAR_DIAGNOSTICS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_diag_read"
+         android:description="@string/car_permission_desc_diag_read"/>
+    <permission android:name="android.car.permission.CLEAR_CAR_DIAGNOSTICS"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_diag_clear"
+         android:description="@string/car_permission_desc_diag_clear"/>
+    <permission android:name="android.car.permission.BIND_VMS_CLIENT"
+         android:protectionLevel="signature"
+         android:label="@string/car_permission_label_bind_vms_client"
+         android:description="@string/car_permission_desc_bind_vms_client"/>
+    <permission android:name="android.car.permission.VMS_PUBLISHER"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_vms_publisher"
+         android:description="@string/car_permission_desc_vms_publisher"/>
+    <permission android:name="android.car.permission.VMS_SUBSCRIBER"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_vms_subscriber"
+         android:description="@string/car_permission_desc_vms_subscriber"/>
+    <permission android:name="android.car.permission.CAR_DRIVING_STATE"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_driving_state"
+         android:description="@string/car_permission_desc_driving_state"/>
     <!--  may replace this with system permission if proper one is defined. -->
-    <permission
-        android:name="android.car.permission.CONTROL_APP_BLOCKING"
-        android:protectionLevel="system|signature"
-        android:label="@string/car_permission_label_control_app_blocking"
-        android:description="@string/car_permission_desc_control_app_blocking" />
+    <permission android:name="android.car.permission.CONTROL_APP_BLOCKING"
+         android:protectionLevel="system|signature"
+         android:label="@string/car_permission_label_control_app_blocking"
+         android:description="@string/car_permission_desc_control_app_blocking"/>
+    <permission android:name="android.car.permission.ADJUST_RANGE_REMAINING"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_adjust_range_remaining"
+         android:description="@string/car_permission_desc_adjust_range_remaining"/>
+    <permission android:name="android.car.permission.READ_CAR_OCCUPANT_AWARENESS_STATE"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_read_car_occupant_awareness_state"
+         android:description="@string/car_permission_desc_read_car_occupant_awareness_state"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_ENERGY_PORTS"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_control_car_energy_ports"
+         android:description="@string/car_permission_desc_control_car_energy_ports"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_OCCUPANT_AWARENESS_SYSTEM"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_control_car_occupant_awareness_system"
+         android:description="@string/car_permission_desc_control_car_occupant_awareness_system"/>
+    <permission android:name="android.car.permission.CONTROL_CAR_FEATURES"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_control_car_features"
+         android:description="@string/car_permission_desc_control_car_features"/>
+    <permission android:name="android.car.permission.USE_CAR_WATCHDOG"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_use_car_watchdog"
+         android:description="@string/car_permission_desc_use_car_watchdog"/>
+    <permission android:name="android.car.permission.READ_CAR_VENDOR_PERMISSION_INFO"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_vendor_permission_info"
+         android:description="@string/car_permission_desc_vendor_permission_info"/>
+    <!-- Permission for vendor properties -->
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_WINDOW"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_window"
+         android:description="@string/car_permission_desc_get_car_vendor_category_window"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_WINDOW"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_window"
+         android:description="@string/car_permission_desc_set_car_vendor_category_window"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_DOOR"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_door"
+         android:description="@string/car_permission_desc_get_car_vendor_category_door"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_DOOR"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_door"
+         android:description="@string/car_permission_desc_set_car_vendor_category_door"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_SEAT"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_seat"
+         android:description="@string/car_permission_desc_get_car_vendor_category_seat"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_SEAT"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_seat"
+         android:description="@string/car_permission_desc_set_car_vendor_category_seat"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_MIRROR"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_mirror"
+         android:description="@string/car_permission_desc_get_car_vendor_category_mirror"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_MIRROR"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_mirror"
+         android:description="@string/car_permission_desc_set_car_vendor_category_mirror"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_INFO"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_info"
+         android:description="@string/car_permission_desc_get_car_vendor_category_info"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_INFO"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_info"
+         android:description="@string/car_permission_desc_set_car_vendor_category_info"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_ENGINE"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_engine"
+         android:description="@string/car_permission_desc_get_car_vendor_category_engine"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_ENGINE"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_engine"
+         android:description="@string/car_permission_desc_set_car_vendor_category_engine"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_HVAC"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_hvac"
+         android:description="@string/car_permission_desc_get_car_vendor_category_hvac"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_HVAC"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_hvac"
+         android:description="@string/car_permission_desc_set_car_vendor_category_hvac"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_LIGHT"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_light"
+         android:description="@string/car_permission_desc_get_car_vendor_category_light"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_LIGHT"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_light"
+         android:description="@string/car_permission_desc_set_car_vendor_category_light"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_1"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_1"
+         android:description="@string/car_permission_desc_get_car_vendor_category_1"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_1"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_1"
+         android:description="@string/car_permission_desc_set_car_vendor_category_1"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_2"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_2"
+         android:description="@string/car_permission_desc_get_car_vendor_category_2"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_2"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_2"
+         android:description="@string/car_permission_desc_set_car_vendor_category_2"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_3"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_3"
+         android:description="@string/car_permission_desc_get_car_vendor_category_3"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_3"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_3"
+         android:description="@string/car_permission_desc_set_car_vendor_category_3"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_4"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_4"
+         android:description="@string/car_permission_desc_get_car_vendor_category_4"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_4"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_4"
+         android:description="@string/car_permission_desc_set_car_vendor_category_4"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_5"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_5"
+         android:description="@string/car_permission_desc_get_car_vendor_category_5"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_5"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_5"
+         android:description="@string/car_permission_desc_set_car_vendor_category_5"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_6"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_6"
+         android:description="@string/car_permission_desc_get_car_vendor_category_6"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_6"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_6"
+         android:description="@string/car_permission_desc_set_car_vendor_category_6"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_7"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_7"
+         android:description="@string/car_permission_desc_get_car_vendor_category_7"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_7"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_7"
+         android:description="@string/car_permission_desc_set_car_vendor_category_7"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_8"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_8"
+         android:description="@string/car_permission_desc_get_car_vendor_category_8"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_8"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_8"
+         android:description="@string/car_permission_desc_set_car_vendor_category_8"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_9"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_9"
+         android:description="@string/car_permission_desc_get_car_vendor_category_9"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_9"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_9"
+         android:description="@string/car_permission_desc_set_car_vendor_category_9"/>
+    <permission android:name="android.car.permission.GET_CAR_VENDOR_CATEGORY_10"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_get_car_vendor_category_10"
+         android:description="@string/car_permission_desc_get_car_vendor_category_10"/>
+    <permission android:name="android.car.permission.SET_CAR_VENDOR_CATEGORY_10"
+         android:protectionLevel="signature|privileged"
+         android:label="@string/car_permission_label_set_car_vendor_category_10"
+         android:description="@string/car_permission_desc_set_car_vendor_category_10"/>
 
     <permission
         android:name="android.car.permission.CAR_CONTROL_AUDIO_VOLUME"
diff --git a/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt b/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt
index 47c1323..f4f97f71 100644
--- a/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt
@@ -21,6 +21,11 @@
 import android.content.Context
 import android.content.Intent
 import android.content.pm.PackageManager
+import android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE
+import android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE
+import android.content.pm.PackageManager.MATCH_SYSTEM_ONLY
+import android.content.pm.ResolveInfo
+import android.content.res.Resources
 import android.provider.Settings
 import android.support.test.uiautomator.By
 import android.support.test.uiautomator.BySelector
@@ -52,6 +57,8 @@
     protected val uiAutomation: UiAutomation = instrumentation.uiAutomation
     protected val uiDevice: UiDevice = UiDevice.getInstance(instrumentation)
     protected val packageManager: PackageManager = context.packageManager
+    private val mPermissionControllerResources: Resources = context.createPackageContext(
+            getPermissionControllerPackageName(), 0).resources
 
     @get:Rule
     val activityRule = ActivityTestRule(StartForFutureActivity::class.java, false, false)
@@ -87,6 +94,27 @@
         pressHome()
     }
 
+    protected fun getPermissionControllerString(res: String): String =
+            mPermissionControllerResources.getString(mPermissionControllerResources
+                    .getIdentifier(res, "string", "com.android.permissioncontroller"))
+
+    private fun getPermissionControllerPackageName(): String {
+        val intent = Intent("android.intent.action.MANAGE_PERMISSIONS")
+        intent.addCategory(Intent.CATEGORY_DEFAULT)
+        val packageManager: PackageManager = context.getPackageManager()
+        val matches: List<ResolveInfo> = packageManager.queryIntentActivities(intent,
+                MATCH_SYSTEM_ONLY or MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE)
+        return if (matches.size == 1) {
+            val resolveInfo: ResolveInfo = matches[0]
+            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
+                throw RuntimeException("The permissions manager must be a privileged app")
+            }
+            matches[0].activityInfo.packageName
+        } else {
+            throw RuntimeException("There must be exactly one permissions manager; found $matches")
+        }
+    }
+
     protected fun installPackage(
         apkPath: String,
         reinstall: Boolean = false,
@@ -117,8 +145,8 @@
         return UiAutomatorUtils.waitFindObject(selector, timeoutMillis)
     }
 
-    protected fun click(selector: BySelector) {
-        waitFindObject(selector).click()
+    protected fun click(selector: BySelector, timeoutMillis: Long = 10_000) {
+        waitFindObject(selector, timeoutMillis).click()
         waitForIdle()
     }
 
diff --git a/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt b/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
index 1f074fc..25e8962 100644
--- a/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
@@ -68,6 +68,13 @@
         const val NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON =
                 "com.android.permissioncontroller:" +
                         "id/permission_no_upgrade_and_dont_ask_again_button"
+
+        const val ALLOW_BUTTON_TEXT = "grant_dialog_button_allow"
+        const val ALLOW_FOREGROUND_BUTTON_TEXT = "grant_dialog_button_allow_foreground"
+        const val DENY_BUTTON_TEXT = "grant_dialog_button_deny"
+        const val DENY_AND_DONT_ASK_AGAIN_BUTTON_TEXT =
+                "grant_dialog_button_deny_and_dont_ask_again"
+        const val NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON_TEXT = "grant_dialog_button_no_upgrade"
     }
 
     enum class PermissionState {
@@ -78,6 +85,7 @@
 
     protected val isTv = packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
     protected val isWatch = packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)
+    protected val isAutomotive = packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)
 
     private val platformResources = context.createPackageContext("android", 0).resources
     private val permissionToLabelResNameMap =
@@ -192,11 +200,21 @@
     protected fun clearTargetSdkWarning() =
         click(By.res("android:id/button1"))
 
-    protected fun clickPermissionReviewContinue() =
-        click(By.res("com.android.permissioncontroller:id/continue_button"))
+    protected fun clickPermissionReviewContinue() {
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString("review_button_continue")))
+        } else {
+            click(By.res("com.android.permissioncontroller:id/continue_button"))
+        }
+    }
 
-    protected fun clickPermissionReviewCancel() =
-        click(By.res("com.android.permissioncontroller:id/cancel_button"))
+    protected fun clickPermissionReviewCancel() {
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString("review_button_cancel")))
+        } else {
+            click(By.res("com.android.permissioncontroller:id/cancel_button"))
+        }
+    }
 
     protected fun approvePermissionReview() {
         startAppActivityAndAssertResultCode(Activity.RESULT_OK) {
@@ -300,30 +318,55 @@
         block
     )
 
-    protected fun clickPermissionRequestAllowButton() =
-        click(By.res(ALLOW_BUTTON))
+    protected fun clickPermissionRequestAllowButton() {
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString(ALLOW_BUTTON_TEXT)))
+        } else {
+            click(By.res(ALLOW_BUTTON))
+        }
+    }
 
     protected fun clickPermissionRequestSettingsLinkAndAllowAlways() {
+        clickPermissionRequestSettingsLink()
         eventually({
-            clickPermissionRequestSettingsLink()
             clickAllowAlwaysInSettings()
         }, TIMEOUT_MILLIS * 2)
         pressBack()
     }
 
     protected fun clickAllowAlwaysInSettings() {
-        click(By.res("com.android.permissioncontroller:id/allow_always_radio_button"))
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString("app_permission_button_allow_always")))
+        } else {
+            click(By.res("com.android.permissioncontroller:id/allow_always_radio_button"))
+        }
     }
 
-    protected fun clickPermissionRequestAllowForegroundButton() =
-        click(By.res(ALLOW_FOREGROUND_BUTTON))
+    protected fun clickPermissionRequestAllowForegroundButton(timeoutMillis: Long = 10_000) {
+        if (isAutomotive) {
+            click(By.text(
+                    getPermissionControllerString(ALLOW_FOREGROUND_BUTTON_TEXT)), timeoutMillis)
+        } else {
+            click(By.res(ALLOW_FOREGROUND_BUTTON), timeoutMillis)
+        }
+    }
 
-    protected fun clickPermissionRequestDenyButton() =
-        click(By.res(DENY_BUTTON))
+    protected fun clickPermissionRequestDenyButton() {
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString(DENY_BUTTON_TEXT)))
+        } else {
+            click(By.res(DENY_BUTTON))
+        }
+    }
 
     protected fun clickPermissionRequestSettingsLinkAndDeny() {
         clickPermissionRequestSettingsLink()
-        click(By.res("com.android.permissioncontroller:id/deny_radio_button"))
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString("app_permission_button_deny")))
+        } else {
+            click(By.res("com.android.permissioncontroller:id/deny_radio_button"))
+        }
+        waitForIdle()
         pressBack()
     }
 
@@ -331,9 +374,15 @@
         waitForIdle()
         eventually {
             // UiObject2 doesn't expose CharSequence.
-            val node = uiAutomation.rootInActiveWindow.findAccessibilityNodeInfosByViewId(
-                    "com.android.permissioncontroller:id/detail_message"
-            )[0]
+            val node = if (isAutomotive) {
+                uiAutomation.rootInActiveWindow.findAccessibilityNodeInfosByText(
+                        "Allow in settings."
+                )[0]
+            } else {
+                uiAutomation.rootInActiveWindow.findAccessibilityNodeInfosByViewId(
+                        "com.android.permissioncontroller:id/detail_message"
+                )[0]
+            }
             assertTrue(node.isVisibleToUser)
             val text = node.text as Spanned
             val clickableSpan = text.getSpans(0, text.length, ClickableSpan::class.java)[0]
@@ -343,20 +392,25 @@
         waitForIdle()
     }
 
-    protected fun clickPermissionRequestDenyAndDontAskAgainButton() =
-        click(
-            By.res(DENY_AND_DONT_ASK_AGAIN_BUTTON)
-        )
+    protected fun clickPermissionRequestDenyAndDontAskAgainButton() {
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString(DENY_AND_DONT_ASK_AGAIN_BUTTON_TEXT)))
+        } else {
+            click(By.res(DENY_AND_DONT_ASK_AGAIN_BUTTON))
+        }
+    }
 
+    // Only used in TV and Watch form factors
     protected fun clickPermissionRequestDontAskAgainButton() =
         click(By.res("com.android.permissioncontroller:id/permission_deny_dont_ask_again_button"))
 
-    protected fun clickPermissionRequestNoUpgradeButton() =
-        click(By.res(NO_UPGRADE_BUTTON))
-
-    protected fun clickPermissionRequestNoUpgradeAndDontAskAgainButton() = click(
-        By.res(NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON)
-    )
+    protected fun clickPermissionRequestNoUpgradeAndDontAskAgainButton() {
+        if (isAutomotive) {
+            click(By.text(getPermissionControllerString(NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON_TEXT)))
+        } else {
+            click(By.res(NO_UPGRADE_AND_DONT_ASK_AGAIN_BUTTON))
+        }
+    }
 
     protected fun grantAppPermissions(vararg permissions: String, targetSdk: Int = 30) {
         setAppPermissionState(*permissions, state = PermissionState.ALLOWED, isLegacyApp = false,
@@ -412,6 +466,10 @@
             }
             val wasGranted = if (isTv) {
                 false
+            } else if (isAutomotive) {
+                // Automotive doesn't support one time permissions, and thus
+                // won't show an "Ask every time" message
+                !waitFindObject(byTextRes(R.string.deny)).isChecked
             } else {
                 !(waitFindObject(byTextRes(R.string.deny)).isChecked ||
                     (!isLegacyApp && hasAskButton(permission) &&
@@ -423,24 +481,34 @@
             } else {
                 val button = waitFindObject(
                     byTextRes(
-                        when (state) {
-                            PermissionState.ALLOWED ->
-                                if (showsForegroundOnlyButton(permission)) {
-                                    R.string.allow_foreground
-                                } else if (isMediaStorageButton(permission, targetSdk)) {
-                                    R.string.allow_media_storage
-                                } else if (isAllStorageButton(permission, targetSdk)) {
-                                    R.string.allow_external_storage
-                                } else {
-                                    R.string.allow
-                                }
-                            PermissionState.DENIED ->
-                                if (!isLegacyApp && hasAskButton(permission)) {
-                                    R.string.ask
-                                } else {
-                                    R.string.deny
-                                }
-                            PermissionState.DENIED_WITH_PREJUDICE -> R.string.deny
+                        if (isAutomotive) {
+                            // Automotive doesn't support one time permissions, and thus
+                            // won't show an "Ask every time" message
+                            when (state) {
+                                PermissionState.ALLOWED -> R.string.allow
+                                PermissionState.DENIED -> R.string.deny
+                                PermissionState.DENIED_WITH_PREJUDICE -> R.string.deny
+                            }
+                        } else {
+                            when (state) {
+                                PermissionState.ALLOWED ->
+                                    if (showsForegroundOnlyButton(permission)) {
+                                        R.string.allow_foreground
+                                    } else if (isMediaStorageButton(permission, targetSdk)) {
+                                        R.string.allow_media_storage
+                                    } else if (isAllStorageButton(permission, targetSdk)) {
+                                        R.string.allow_external_storage
+                                    } else {
+                                        R.string.allow
+                                    }
+                                PermissionState.DENIED ->
+                                    if (!isLegacyApp && hasAskButton(permission)) {
+                                        R.string.ask
+                                    } else {
+                                        R.string.deny
+                                    }
+                                PermissionState.DENIED_WITH_PREJUDICE -> R.string.deny
+                            }
                         }
                     )
                 )
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt
index 01b4058..f2f2a10 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt
@@ -45,7 +45,7 @@
             SystemUtil.eventually({
                 if (packageManager.checkPermission(ACCESS_FINE_LOCATION, APP_PACKAGE_NAME) ==
                         PackageManager.PERMISSION_DENIED) {
-                    waitFindObject(By.res(ALLOW_FOREGROUND_BUTTON), 100).click()
+                    clickPermissionRequestAllowForegroundButton(100)
                 }
                 assertAppHasPermission(ACCESS_FINE_LOCATION, true)
             }, 10000)
@@ -54,6 +54,10 @@
         }
         // Permission should not be granted and dialog should still be showing
         assertAppHasPermission(ACCESS_FINE_LOCATION, false)
-        waitFindObject(By.res(ALLOW_FOREGROUND_BUTTON), 1000)
+
+        // On Automotive the dialog gets closed by the tapjacking activity popping up
+        if (!isAutomotive) {
+            clickPermissionRequestAllowForegroundButton()
+        }
     }
 }
\ No newline at end of file
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionTest29.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionTest29.kt
index e5a5ede..5d13748 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionTest29.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionTest29.kt
@@ -161,7 +161,11 @@
         clickPermissionRequestSettingsLink()
         eventually {
             pressBack()
-            waitFindObject(By.res("com.android.permissioncontroller:id/grant_dialog"), 100)
+            if (isAutomotive) {
+                waitFindObject(By.textContains("Allow in settings."), 100)
+            } else {
+                waitFindObject(By.res("com.android.permissioncontroller:id/grant_dialog"), 100)
+            }
         }
     }
 
@@ -181,8 +185,9 @@
             android.Manifest.permission.ACCESS_BACKGROUND_LOCATION
         ) {
             clickPermissionRequestSettingsLinkAndDeny()
+            waitForIdle()
+            pressBack()
         }
-        pressBack()
 
         assertAppHasPermission(android.Manifest.permission.ACCESS_FINE_LOCATION, false)
         assertAppHasPermission(android.Manifest.permission.ACCESS_BACKGROUND_LOCATION, false)
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionTest30.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionTest30.kt
index 0abae86..1272355 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionTest30.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionTest30.kt
@@ -49,6 +49,7 @@
 
         requestAppPermissionsAndAssertResult(ACCESS_BACKGROUND_LOCATION to true) {
             clickAllowAlwaysInSettings()
+            waitForIdle()
             pressBack()
         }
     }
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java
index 4f0bc3e..0c9a60c 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java
@@ -42,7 +42,9 @@
     @Before
     public void setup() {
         requireLandscapeModeSupport();
-        mTestUtils = new TestUtils();
+        mActivity = launchActivity(null);
+        mTestUtils = new TestUtils(mActivityRule);
+        mActivity.finish();
     }
 
     /**
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java
index 155b799..8500425 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java
@@ -41,7 +41,9 @@
     @Before
     public void setup() {
         requirePortraitModeSupport();
-        mTestUtils = new TestUtils();
+        mActivity = launchActivity(null);
+        mTestUtils = new TestUtils(mActivityRule);
+        mActivity.finish();
     }
 
     /**
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java
index e70a34b..ba6182a 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java
@@ -52,7 +52,7 @@
 
     @Before
     public void setup() {
-        mTestUtils = new TestUtils();
+        mTestUtils = new TestUtils(mActivityRule);
         mActivity = mActivityRule.getActivity();
     }
 
diff --git a/tests/tests/preference/src/android/preference/cts/TestUtils.java b/tests/tests/preference/src/android/preference/cts/TestUtils.java
index d15d99f..30bd9fc 100644
--- a/tests/tests/preference/src/android/preference/cts/TestUtils.java
+++ b/tests/tests/preference/src/android/preference/cts/TestUtils.java
@@ -22,6 +22,7 @@
 import android.content.Context;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
+import android.graphics.Rect;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject2;
@@ -29,8 +30,12 @@
 import android.support.test.uiautomator.UiScrollable;
 import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
+import android.util.DisplayMetrics;
+import android.view.Display;
+import android.view.Window;
 
 import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.rule.ActivityTestRule;
 
 /**
  * Collection of helper utils for testing preferences.
@@ -45,13 +50,17 @@
     private final UiAutomation mAutomation;
     private int mStatusBarHeight = -1;
     private int mNavigationBarHeight = -1;
+    private Display mDisplay;
+    private Window mWindow;
 
-    TestUtils() {
+    TestUtils(ActivityTestRule<?> rule) {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mContext = mInstrumentation.getTargetContext();
         mPackageName = mContext.getPackageName();
         mDevice = UiDevice.getInstance(mInstrumentation);
         mAutomation = mInstrumentation.getUiAutomation();
+        mDisplay = rule.getActivity().getDisplay();
+        mWindow = rule.getActivity().getWindow();
     }
 
     void waitForIdle() {
@@ -75,7 +84,7 @@
         int xToCut = isOnWatchUiMode() ? bt.getWidth() / 5 : bt.getWidth() / 20;
         int yToCut = statusBarHeight;
 
-        if (isLandscape()) {
+        if (hasVerticalNavBar()) {
             xToCut += navigationBarHeight;
         } else {
             yToCut += navigationBarHeight;
@@ -154,9 +163,12 @@
         return mNavigationBarHeight;
     }
 
-    private boolean isLandscape() {
-        return mInstrumentation.getTargetContext().getResources().getConfiguration().orientation
-            == Configuration.ORIENTATION_LANDSCAPE;
+    private boolean hasVerticalNavBar() {
+        Rect displayFrame = new Rect();
+        mWindow.getDecorView().getWindowVisibleDisplayFrame(displayFrame);
+        DisplayMetrics dm = new DisplayMetrics();
+        mDisplay.getRealMetrics(dm);
+        return dm.heightPixels == displayFrame.bottom;
     }
 
     private UiObject2 getTextObject(String text) {
diff --git a/tests/tests/provider/res/raw/moov-at-end-zero-len.mp4 b/tests/tests/provider/res/raw/moov-at-end-zero-len.mp4
new file mode 100644
index 0000000..5b307e2
--- /dev/null
+++ b/tests/tests/provider/res/raw/moov-at-end-zero-len.mp4
Binary files differ
diff --git a/tests/tests/provider/res/raw/moov-at-end.mp4 b/tests/tests/provider/res/raw/moov-at-end.mp4
new file mode 100644
index 0000000..cdf74b5
--- /dev/null
+++ b/tests/tests/provider/res/raw/moov-at-end.mp4
Binary files differ
diff --git a/tests/tests/provider/res/raw/testvideo_meta.mp4 b/tests/tests/provider/res/raw/testvideo_meta.mp4
index 8f04b40..e83c61d 100644
--- a/tests/tests/provider/res/raw/testvideo_meta.mp4
+++ b/tests/tests/provider/res/raw/testvideo_meta.mp4
Binary files differ
diff --git a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
index feeb87c..942d4f4 100644
--- a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
+++ b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
@@ -22,8 +22,10 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import android.app.AppOpsManager;
 import android.app.UiAutomation;
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
 import android.graphics.Bitmap;
@@ -35,6 +37,7 @@
 import android.os.Environment;
 import android.os.FileUtils;
 import android.os.ParcelFileDescriptor;
+import android.os.Process;
 import android.os.UserManager;
 import android.os.storage.StorageManager;
 import android.os.storage.StorageVolume;
@@ -252,11 +255,21 @@
         if (userManager.isSystemUser() &&
                     FileUtils.contains(Environment.getStorageDirectory(), file)) {
             executeShellCommand("mkdir -p " + file.getParent());
+            waitUntilExists(file.getParentFile());
             try (AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId)) {
                 final File source = ParcelFileDescriptor.getFile(afd.getFileDescriptor());
                 final long skip = afd.getStartOffset();
                 final long count = afd.getLength();
 
+                try {
+                    // Try to create the file as calling package so that calling package remains
+                    // as owner of the file.
+                    file.createNewFile();
+                } catch (IOException ignored) {
+                    // Apps can't create files in other app's private directories, but shell can. If
+                    // file creation fails, we ignore and let `dd` command create it instead.
+                }
+
                 executeShellCommand(String.format("dd bs=1 if=%s skip=%d count=%d of=%s",
                         source.getAbsolutePath(), skip, count, file.getAbsolutePath()));
 
@@ -471,4 +484,31 @@
             throw new IllegalArgumentException();
         }
     }
+
+    /** Revokes ACCESS_MEDIA_LOCATION from the test app */
+    public static void revokeMediaLocationPermission(Context context) throws Exception {
+        try {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .adoptShellPermissionIdentity("android.permission.MANAGE_APP_OPS_MODES",
+                            "android.permission.REVOKE_RUNTIME_PERMISSIONS");
+
+            // Revoking ACCESS_MEDIA_LOCATION permission will kill the test app.
+            // Deny access_media_permission App op to revoke this permission.
+            PackageManager packageManager = context.getPackageManager();
+            String packageName = context.getPackageName();
+            if (packageManager.checkPermission(android.Manifest.permission.ACCESS_MEDIA_LOCATION,
+                    packageName) == PackageManager.PERMISSION_GRANTED) {
+                context.getPackageManager().updatePermissionFlags(
+                        android.Manifest.permission.ACCESS_MEDIA_LOCATION, packageName,
+                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT,
+                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, context.getUser());
+                context.getSystemService(AppOpsManager.class).setUidMode(
+                        "android:access_media_location", Process.myUid(),
+                        AppOpsManager.MODE_IGNORED);
+            }
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation().
+                    dropShellPermissionIdentity();
+        }
+    }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java
index df47fac..1d18a8a 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java
@@ -25,12 +25,10 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.app.AppOpsManager;
 import android.content.ContentResolver;
 import android.content.ContentUris;
 import android.content.ContentValues;
 import android.content.Context;
-import android.content.pm.PackageManager;
 import android.database.Cursor;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
@@ -40,7 +38,6 @@
 import android.os.Environment;
 import android.os.FileUtils;
 import android.os.ParcelFileDescriptor;
-import android.os.Process;
 import android.os.storage.StorageManager;
 import android.provider.BaseColumns;
 import android.provider.MediaStore;
@@ -300,8 +297,6 @@
      */
     @Test
     public void testUpdateAndReplace() throws Exception {
-        Assume.assumeFalse(mVolumeName.equals(MediaStore.VOLUME_EXTERNAL));
-
         File dir = mContext.getSystemService(StorageManager.class)
                 .getStorageVolume(mExternalImages).getDirectory();
         File dcimDir = new File(dir, Environment.DIRECTORY_DCIM);
@@ -339,8 +334,6 @@
 
     @Test
     public void testUpsert() throws Exception {
-        Assume.assumeFalse(mVolumeName.equals(MediaStore.VOLUME_EXTERNAL));
-
         File dir = mContext.getSystemService(StorageManager.class)
                 .getStorageVolume(mExternalImages).getDirectory();
         File dcimDir = new File(dir, Environment.DIRECTORY_DCIM);
@@ -395,30 +388,12 @@
         assertNotNull(mContentResolver.loadThumbnail(uri, new Size(96, 96), null));
     }
 
-    /**
-     * This test doesn't hold
-     * {@link android.Manifest.permission#ACCESS_MEDIA_LOCATION}, so Exif
-     * location information should be redacted.
-     */
     @Test
     public void testLocationRedaction() throws Exception {
         // STOPSHIP: remove this once isolated storage is always enabled
         Assume.assumeTrue(StorageManager.hasIsolatedStorage());
-
-        final String displayName = "cts" + System.nanoTime();
-        final PendingParams params = new PendingParams(
-                mExternalImages, displayName, "image/jpeg");
-
-        final Uri pendingUri = MediaStoreUtils.createPending(mContext, params);
-        final Uri publishUri;
-        try (PendingSession session = MediaStoreUtils.openPending(mContext, pendingUri)) {
-            try (InputStream in = mContext.getResources().openRawResource(R.raw.lg_g4_iso_800_jpg);
-                 OutputStream out = session.openOutputStream()) {
-                android.os.FileUtils.copy(in, out);
-            }
-            publishUri = session.publish();
-        }
-
+        final Uri publishUri = ProviderTestUtils.stageMedia(R.raw.lg_g4_iso_800_jpg, mExternalImages,
+                "image/jpeg");
         final Uri originalUri = MediaStore.setRequireOriginal(publishUri);
 
         // Since we own the image, we should be able to see the Exif data that
@@ -439,32 +414,8 @@
         try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(originalUri, "r")) {
         }
 
-        // Remove ACCESS_MEDIA_LOCATION permission
-        try {
-            InstrumentationRegistry.getInstrumentation().getUiAutomation()
-                    .adoptShellPermissionIdentity("android.permission.MANAGE_APP_OPS_MODES",
-                            "android.permission.REVOKE_RUNTIME_PERMISSIONS");
-
-            // Revoking ACCESS_MEDIA_LOCATION permission will kill the test app.
-            // Deny access_media_permission App op to revoke this permission.
-            PackageManager packageManager = mContext.getPackageManager();
-            String packageName = mContext.getPackageName();
-            if (packageManager.checkPermission(android.Manifest.permission.ACCESS_MEDIA_LOCATION,
-                    packageName) == PackageManager.PERMISSION_GRANTED) {
-                mContext.getPackageManager().updatePermissionFlags(
-                        android.Manifest.permission.ACCESS_MEDIA_LOCATION, packageName,
-                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT,
-                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, mContext.getUser());
-                mContext.getSystemService(AppOpsManager.class).setUidMode(
-                        "android:access_media_location", Process.myUid(),
-                        AppOpsManager.MODE_IGNORED);
-            }
-        } finally {
-            InstrumentationRegistry.getInstrumentation().getUiAutomation().
-                    dropShellPermissionIdentity();
-        }
-
-        // Now remove ownership, which means that Exif/XMP location data should be redacted
+        // Revoke location access and remove ownership, which means that location should be redacted
+        ProviderTestUtils.revokeMediaLocationPermission(mContext);
         ProviderTestUtils.clearOwner(publishUri);
         try (InputStream is = mContentResolver.openInputStream(publishUri)) {
             final ExifInterface exif = new ExifInterface(is);
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
index dca7382..88295eb 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
@@ -27,19 +27,16 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.app.AppOpsManager;
 import android.content.ContentResolver;
 import android.content.ContentUris;
 import android.content.ContentValues;
 import android.content.Context;
-import android.content.pm.PackageManager;
 import android.database.Cursor;
 import android.media.MediaMetadataRetriever;
 import android.net.Uri;
 import android.os.Environment;
 import android.os.FileUtils;
 import android.os.ParcelFileDescriptor;
-import android.os.Process;
 import android.os.storage.StorageManager;
 import android.provider.MediaStore;
 import android.provider.MediaStore.Files.FileColumns;
@@ -203,41 +200,32 @@
         return context.getContentResolver().insert(mExternalVideo, values);
     }
 
-    /**
-     * This test doesn't hold
-     * {@link android.Manifest.permission#ACCESS_MEDIA_LOCATION}, so Exif and XMP
-     * location information should be redacted.
-     */
     @Test
-    public void testLocationRedaction() throws Exception {
-        // STOPSHIP: remove this once isolated storage is always enabled
-        Assume.assumeTrue(StorageManager.hasIsolatedStorage());
-
-        final String displayName = "cts" + System.nanoTime();
-        final PendingParams params = new PendingParams(
-                mExternalVideo, displayName, "video/mp4");
-
-        final Uri pendingUri = MediaStoreUtils.createPending(mContext, params);
-        final Uri publishUri;
-        try (PendingSession session = MediaStoreUtils.openPending(mContext, pendingUri)) {
-            try (InputStream in = mContext.getResources().openRawResource(R.raw.testvideo_meta);
-                 OutputStream out = session.openOutputStream()) {
-                FileUtils.copy(in, out);
-            }
-            publishUri = session.publish();
-        }
-
+    public void testOriginalAccess() throws Exception {
+        final Uri publishUri = ProviderTestUtils.stageMedia(R.raw.testvideo_meta, mExternalVideo,
+                "video/mp4");
         final Uri originalUri = MediaStore.setRequireOriginal(publishUri);
 
-        // Since we own the video, we should be able to see the location
-        // we ourselves contributed
-        try (ParcelFileDescriptor pfd = mContentResolver.openFile(publishUri, "r", null);
-                MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
-            mmr.setDataSource(pfd.getFileDescriptor());
-            assertEquals("+37.4217-122.0834/",
-                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
-            assertEquals("2", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+        // As owner, we should be able to request the original bytes
+        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(originalUri, "r")) {
         }
+
+        // Revoke location access and remove ownership, which means that location should be redacted
+        ProviderTestUtils.revokeMediaLocationPermission(mContext);
+        ProviderTestUtils.clearOwner(publishUri);
+
+        // We can't request original bytes unless we have permission
+        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(originalUri, "r")) {
+            fail("Able to read original content without ACCESS_MEDIA_LOCATION");
+        } catch (UnsupportedOperationException expected) {
+        }
+    }
+
+    @Test
+    public void testXmpLocationRedaction() throws Exception {
+        final Uri publishUri = ProviderTestUtils.stageMedia(R.raw.testvideo_meta, mExternalVideo,
+                "video/mp4");
+
         try (InputStream in = mContentResolver.openInputStream(publishUri);
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
             FileUtils.copy(in, out);
@@ -248,44 +236,11 @@
             assertTrue("Failed to read XMP latitude", xmp.contains("53,50.070500N"));
             assertTrue("Failed to read non-location XMP", xmp.contains("13166/7763"));
         }
-        // As owner, we should be able to request the original bytes
-        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(originalUri, "r")) {
-        }
 
-        // Remove ACCESS_MEDIA_LOCATION permission
-        try {
-            InstrumentationRegistry.getInstrumentation().getUiAutomation()
-                    .adoptShellPermissionIdentity("android.permission.MANAGE_APP_OPS_MODES",
-                            "android.permission.REVOKE_RUNTIME_PERMISSIONS");
-
-            // Revoking ACCESS_MEDIA_LOCATION permission will kill the test app.
-            // Deny access_media_permission App op to revoke this permission.
-            PackageManager packageManager = mContext.getPackageManager();
-            String packageName = mContext.getPackageName();
-            if (packageManager.checkPermission(android.Manifest.permission.ACCESS_MEDIA_LOCATION,
-                    packageName) == PackageManager.PERMISSION_GRANTED) {
-                mContext.getPackageManager().updatePermissionFlags(
-                        android.Manifest.permission.ACCESS_MEDIA_LOCATION, packageName,
-                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT,
-                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, mContext.getUser());
-                mContext.getSystemService(AppOpsManager.class).setUidMode(
-                        "android:access_media_location", Process.myUid(),
-                        AppOpsManager.MODE_IGNORED);
-            }
-        } finally {
-                InstrumentationRegistry.getInstrumentation().getUiAutomation().
-                        dropShellPermissionIdentity();
-        }
-
-        // Now remove ownership, which means that location should be redacted
+        // Revoke location access and remove ownership, which means that location should be redacted
+        ProviderTestUtils.revokeMediaLocationPermission(mContext);
         ProviderTestUtils.clearOwner(publishUri);
-        try (ParcelFileDescriptor pfd = mContentResolver.openFile(publishUri, "r", null);
-                MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
-            mmr.setDataSource(pfd.getFileDescriptor());
-            assertEquals(null,
-                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
-            assertEquals("2", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
-        }
+
         try (InputStream in = mContentResolver.openInputStream(publishUri);
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
             FileUtils.copy(in, out);
@@ -296,10 +251,52 @@
             assertFalse("Failed to redact XMP latitude", xmp.contains("53,50.070500N"));
             assertTrue("Redacted non-location XMP", xmp.contains("13166/7763"));
         }
-        // We can't request original bytes unless we have permission
-        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(originalUri, "r")) {
-            fail("Able to read original content without ACCESS_MEDIA_LOCATION");
-        } catch (UnsupportedOperationException expected) {
+    }
+
+    @Test
+    public void testIsoLocationRedaction() throws Exception {
+        // STOPSHIP: remove this once isolated storage is always enabled
+        Assume.assumeTrue(StorageManager.hasIsolatedStorage());
+
+        // These videos have all had their ISO location metadata (in the (c)xyz box) artificially
+        // modified to +58.0000+011.0000 (middle of Skagerrak).
+        int[] videoIds = new int[] {
+            R.raw.testvideo_meta,
+            R.raw.moov_at_end,
+            R.raw.moov_at_end_zero_len,
+        };
+        Uri[] uris = new Uri[videoIds.length];
+        for (int i = 0; i < videoIds.length; i++) {
+            uris[i] = ProviderTestUtils.stageMedia(videoIds[i], mExternalVideo, "video/mp4");
+        }
+
+        for (int i = 0; i < uris.length; i++) {
+            // Since we own the video, we should be able to see the location
+            // we ourselves contributed
+            try (ParcelFileDescriptor pfd = mContentResolver.openFile(uris[i], "r", null);
+                    MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
+                mmr.setDataSource(pfd.getFileDescriptor());
+                assertEquals("+58.0000+011.0000/",
+                        mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
+                assertEquals("2",
+                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+            }
+        }
+
+        // Revoke location access and remove ownership, which means that location should be redacted
+        ProviderTestUtils.revokeMediaLocationPermission(mContext);
+
+        for (int i = 0; i < uris.length; i++) {
+            ProviderTestUtils.clearOwner(uris[i]);
+
+            try (ParcelFileDescriptor pfd = mContentResolver.openFile(uris[i], "r", null);
+                    MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
+                mmr.setDataSource(pfd.getFileDescriptor());
+                assertEquals(null,
+                        mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
+                assertEquals("2",
+                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+            }
         }
     }
 
diff --git a/tests/tests/secure_element/omapi/apk/signed-CtsOmapiTestCases.apk b/tests/tests/secure_element/omapi/apk/signed-CtsOmapiTestCases.apk
index a6cbfd8..53275fd 100644
--- a/tests/tests/secure_element/omapi/apk/signed-CtsOmapiTestCases.apk
+++ b/tests/tests/secure_element/omapi/apk/signed-CtsOmapiTestCases.apk
Binary files differ
diff --git a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
index da99ff0..5d56ded 100644
--- a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
+++ b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
@@ -24,6 +24,7 @@
 
 import android.content.pm.PackageManager;
 import android.os.Build;
+import android.os.SystemProperties;
 import android.se.omapi.Channel;
 import android.se.omapi.Reader;
 import android.se.omapi.SEService;
@@ -154,7 +155,7 @@
 
     private boolean supportsHardware() {
         final PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();
-        boolean lowRamDevice = PropertyUtil.propertyEquals("ro.config.low_ram", "true");
+        boolean lowRamDevice = SystemProperties.getBoolean("ro.config.low_ram", false);
         return !lowRamDevice || pm.hasSystemFeature("android.hardware.type.watch")
                 || hasSecureElementPackage(pm);
     }
diff --git a/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java b/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java
index 8c2f870..f5ddc7c 100644
--- a/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java
+++ b/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java
@@ -314,7 +314,12 @@
      */
     public void showsExtraChooserTargets() {
         // Should show chooser targets but must limit them, can't test limit here
-        waitAndAssertTextContains(mExtraChooserTargetsLabelBase);
+        if (mActivityManager.isLowRamDevice()) {
+            // The direct share row and EXTRA_CHOOSER_TARGETS should be hidden on low-ram devices
+            waitAndAssertNoTextContains(mExtraChooserTargetsLabelBase);
+        } else {
+            waitAndAssertTextContains(mExtraChooserTargetsLabelBase);
+        }
     }
 
     /**
diff --git a/tests/tests/systemintents/src/android/systemintents/cts/TestSystemIntents.java b/tests/tests/systemintents/src/android/systemintents/cts/TestSystemIntents.java
index 9f2fbb8..f31dcf1 100644
--- a/tests/tests/systemintents/src/android/systemintents/cts/TestSystemIntents.java
+++ b/tests/tests/systemintents/src/android/systemintents/cts/TestSystemIntents.java
@@ -30,7 +30,10 @@
 import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.google.common.truth.Expect;
+
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -52,6 +55,8 @@
         }
     }
 
+    @Rule public final Expect mExpect = Expect.create();
+
     private Context mContext;
     private PackageManager mPackageManager;
 
@@ -68,7 +73,6 @@
     private final IntentEntry[] mTestIntents = {
             /* Settings-namespace intent actions */
             new IntentEntry(0, new Intent(Settings.ACTION_SETTINGS)),
-            new IntentEntry(0, new Intent(Settings.ACTION_WEBVIEW_SETTINGS)),
             new IntentEntry(0, new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)),
             new IntentEntry(0, new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)),
             new IntentEntry(0, new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
@@ -115,7 +119,8 @@
             if ((productFlags & e.flags) == 0) {
                 final ResolveInfo ri = mPackageManager.resolveActivity(e.intent,
                         PackageManager.MATCH_DEFAULT_ONLY);
-                assertTrue("API intent " + e.intent + " not implemented by any activity", ri != null);
+                mExpect.withMessage("API intent %s not implemented by any activity", e.intent)
+                        .that(ri).isNotNull();
             }
         }
     }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
index 7d82cee..d6e3d05 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
@@ -564,7 +564,8 @@
         }
 
         mTelephonyManager.getDefaultRespondViaMessageApplication();
-        mTelephonyManager.getAndUpdateDefaultRespondViaMessageApplication();
+        ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                TelephonyManager::getAndUpdateDefaultRespondViaMessageApplication);
     }
 
     /**
diff --git a/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp b/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp
index ab4ce58..fbf9f9a 100644
--- a/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp
+++ b/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp
@@ -408,16 +408,25 @@
     Callback* cb64 = new Callback("cb64");
     auto start = now();
 
+    auto vsyncPeriod = std::chrono::duration_cast<std::chrono::milliseconds>(
+                           NOMINAL_VSYNC_PERIOD)
+                           .count();
     auto delay = std::chrono::duration_cast<std::chrono::milliseconds>(DELAY_PERIOD).count();
     AChoreographer_postFrameCallbackDelayed(choreographer, frameCallback, cb1, delay);
     AChoreographer_postFrameCallbackDelayed64(choreographer, frameCallback64, cb64, delay);
 
     std::this_thread::sleep_for(DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 10);
-    ALooper_pollAll(16, nullptr, nullptr, nullptr);
+    // Ensure that callbacks are seen by the looper instance at approximately
+    // the same time, and provide enough time for the looper instance to process
+    // the delayed callback and the requested vsync signal if needed.
+    ALooper_pollAll(vsyncPeriod * 5, nullptr, nullptr, nullptr);
     verifyRefreshRateCallback(env, cb, 1);
-    verifyCallback(env, cb64, 1, start, DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 11);
+    verifyCallback(env, cb64, 1, start,
+                   DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 15);
     const auto delayToTestFor32Bit =
-            sizeof(long) == sizeof(int64_t) ? DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 11 : ZERO;
+        sizeof(long) == sizeof(int64_t)
+            ? DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 15
+            : ZERO;
     verifyCallback(env, cb1, 1, start, delayToTestFor32Bit);
     AChoreographer_unregisterRefreshRateCallback(choreographer, refreshRateCallback, cb);
 }
diff --git a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
index 66b1539..7ab5143 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
@@ -19,6 +19,7 @@
 import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
 import static android.opengl.GLES20.glClear;
 import static android.opengl.GLES20.glClearColor;
+import static android.opengl.GLES20.glFinish;
 
 import android.app.Activity;
 import android.content.pm.ActivityInfo;
@@ -258,6 +259,7 @@
         int surfaceUpdateCount = mSurfaceUpdatedCount;
         runOnGLThread(() -> {
             callback.drawFrame(mSurfaceWidth, mSurfaceHeight);
+            glFinish();
             if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                 throw new RuntimeException("Cannot swap buffers");
             }
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/ConcurrencyTest.java b/tests/tests/wifi/src/android/net/wifi/cts/ConcurrencyTest.java
index 76085fa..ced02b8 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/ConcurrencyTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/ConcurrencyTest.java
@@ -127,6 +127,8 @@
                     mMySync.pendingSync.set(MySync.NETWORK_INFO);
                     mMySync.expectedNetworkInfo = (NetworkInfo) intent.getExtra(
                             WifiP2pManager.EXTRA_NETWORK_INFO, null);
+                    Log.d(TAG, "Get WIFI_P2P_CONNECTION_CHANGED_ACTION: "
+                            + mMySync.expectedNetworkInfo);
                     mMySync.notify();
                 }
             }
@@ -520,6 +522,10 @@
         mWifiP2pManager.removeGroup(mWifiP2pChannel, mActionListener);
         assertTrue(waitForServiceResponse(mMyResponse));
         assertTrue(mMyResponse.success);
+        assertTrue(waitForBroadcasts(MySync.NETWORK_INFO));
+        assertNotNull(mMySync.expectedNetworkInfo);
+        assertEquals(NetworkInfo.DetailedState.DISCONNECTED,
+                mMySync.expectedNetworkInfo.getDetailedState());
     }
 
     private String getDeviceName() {
@@ -604,6 +610,10 @@
         mWifiP2pManager.removeGroup(mWifiP2pChannel, mActionListener);
         assertTrue(waitForServiceResponse(mMyResponse));
         assertTrue(mMyResponse.success);
+        assertTrue(waitForBroadcasts(MySync.NETWORK_INFO));
+        assertNotNull(mMySync.expectedNetworkInfo);
+        assertEquals(NetworkInfo.DetailedState.DISCONNECTED,
+                mMySync.expectedNetworkInfo.getDetailedState());
 
         WifiP2pGroupList persistentGroups = getPersistentGroups();
         assertNotNull(persistentGroups);
@@ -636,6 +646,10 @@
         mWifiP2pManager.removeGroup(mWifiP2pChannel, mActionListener);
         assertTrue(waitForServiceResponse(mMyResponse));
         assertTrue(mMyResponse.success);
+        assertTrue(waitForBroadcasts(MySync.NETWORK_INFO));
+        assertNotNull(mMySync.expectedNetworkInfo);
+        assertEquals(NetworkInfo.DetailedState.DISCONNECTED,
+                mMySync.expectedNetworkInfo.getDetailedState());
 
         resetResponse(mMyResponse);
         ShellIdentityUtils.invokeWithShellPermissions(() -> {
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/WifiFeature.java b/tests/tests/wifi/src/android/net/wifi/cts/WifiFeature.java
index 3e9fef4..4876ff0 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/WifiFeature.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/WifiFeature.java
@@ -29,4 +29,9 @@
         PackageManager packageManager = context.getPackageManager();
         return packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT);
     }
+
+    public static boolean isTelephonySupported(Context context) {
+        final PackageManager pm = context.getPackageManager();
+        return pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
+    }
 }
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 0b548fb..8ad29c7 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
@@ -632,10 +632,10 @@
         MacAddress lastBlockedClientMacAddress;
         int lastBlockedClientReason;
         boolean onStateChangedCalled = false;
-        boolean onSoftapInfoChangedCalled = false;
         boolean onSoftApCapabilityChangedCalled = false;
         boolean onConnectedClientCalled = false;
         boolean onBlockedClientConnectingCalled = false;
+        int onSoftapInfoChangedCalledCount = 0;
 
         TestSoftApCallback(Object lock) {
             softApLock = lock;
@@ -647,9 +647,9 @@
             }
         }
 
-        public boolean getOnSoftapInfoChangedCalled() {
+        public int getOnSoftapInfoChangedCalledCount() {
             synchronized(softApLock) {
-                return onSoftapInfoChangedCalled;
+                return onSoftapInfoChangedCalledCount;
             }
         }
 
@@ -734,7 +734,7 @@
         public void onInfoChanged(SoftApInfo softApInfo) {
             synchronized(softApLock) {
                 currentSoftApInfo = softApInfo;
-                onSoftapInfoChangedCalled = true;
+                onSoftapInfoChangedCalledCount++;
             }
         }
 
@@ -1472,7 +1472,7 @@
                     executor.runAll();
                     // Verify callback is run on the supplied executor and called
                     return callback.getOnStateChangedCalled() &&
-                            callback.getOnSoftapInfoChangedCalled() &&
+                            callback.getOnSoftapInfoChangedCalledCount() > 0 &&
                             callback.getOnSoftApCapabilityChangedCalled() &&
                             callback.getOnConnectedClientCalled();
                 });
@@ -1633,8 +1633,9 @@
                     "SoftAp channel and state mismatch!!!", 5_000,
                     () -> {
                         executor.runAll();
-                        return WifiManager.WIFI_AP_STATE_ENABLED == callback.getCurrentState() &&
-                                2462 == callback.getCurrentSoftApInfo().getFrequency();
+                        return WifiManager.WIFI_AP_STATE_ENABLED == callback.getCurrentState()
+                                && (callback.getOnSoftapInfoChangedCalledCount() > 1
+                                ? 2462 == callback.getCurrentSoftApInfo().getFrequency() : true);
                     });
 
             // stop tethering which used to verify stopSoftAp
@@ -2311,9 +2312,11 @@
         // assert that the country code is all uppercase
         assertEquals(wifiCountryCode.toUpperCase(Locale.US), wifiCountryCode);
 
-        String telephonyCountryCode = getContext().getSystemService(TelephonyManager.class)
-                .getNetworkCountryIso();
-        assertEquals(telephonyCountryCode, wifiCountryCode.toLowerCase(Locale.US));
+        if (WifiFeature.isTelephonySupported(getContext())) {
+            String telephonyCountryCode = getContext().getSystemService(TelephonyManager.class)
+                    .getNetworkCountryIso();
+            assertEquals(telephonyCountryCode, wifiCountryCode.toLowerCase(Locale.US));
+        }
     }
 
     /**
diff --git a/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java b/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java
index 07d5718..a721326 100644
--- a/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java
+++ b/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java
@@ -52,6 +52,9 @@
     // wait for Wi-Fi scan results to become available
     private static final int WAIT_FOR_SCAN_RESULTS_SECS = 20;
 
+    // wait for network selection and connection finish
+    private static final int WAIT_FOR_CONNECTION_FINISH_MS = 30_000;
+
     protected WifiRttManager mWifiRttManager;
     protected WifiManager mWifiManager;
     private LocationManager mLocationManager;
@@ -96,8 +99,10 @@
         mWifiLock.acquire();
         if (!mWifiManager.isWifiEnabled()) {
             SystemUtil.runShellCommand("svc wifi enable");
+            // Turn on Wi-Fi may trigger connection. Wait connection state stable.
+            scanAps();
+            Thread.sleep(WAIT_FOR_CONNECTION_FINISH_MS);
         }
-
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(WifiRttManager.ACTION_WIFI_RTT_STATE_CHANGED);
         WifiRttBroadcastReceiver receiver = new WifiRttBroadcastReceiver();
diff --git a/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java b/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java
index fad4230..458917d 100644
--- a/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java
@@ -49,7 +49,7 @@
     private static final int MAX_FAILURE_RATE_PERCENT = 10;
 
     // Maximum variation from the average measurement (measures consistency)
-    private static final int MAX_VARIATION_FROM_AVERAGE_DISTANCE_MM = 1000;
+    private static final int MAX_VARIATION_FROM_AVERAGE_DISTANCE_MM = 2000;
 
     // Minimum valid RSSI value
     private static final int MIN_VALID_RSSI = -100;
@@ -176,10 +176,12 @@
                         + ", AP SSID=" + testAp.SSID,
                 numFailures <= NUM_OF_RTT_ITERATIONS * MAX_FAILURE_RATE_PERCENT / 100);
         if (numFailures != NUM_OF_RTT_ITERATIONS) {
-            double distanceAvg = distanceSum / (NUM_OF_RTT_ITERATIONS - numFailures);
-            assertTrue("Wi-Fi RTT: Variation (max direction) exceeds threshold",
+            double distanceAvg = (double) distanceSum / (NUM_OF_RTT_ITERATIONS - numFailures);
+            assertTrue("Wi-Fi RTT: Variation (max direction) exceeds threshold, Variation ="
+                            + (distanceMax - distanceAvg),
                     (distanceMax - distanceAvg) <= MAX_VARIATION_FROM_AVERAGE_DISTANCE_MM);
-            assertTrue("Wi-Fi RTT: Variation (min direction) exceeds threshold",
+            assertTrue("Wi-Fi RTT: Variation (min direction) exceeds threshold, Variation ="
+                            + (distanceAvg - distanceMin),
                     (distanceAvg - distanceMin) <= MAX_VARIATION_FROM_AVERAGE_DISTANCE_MM);
             for (int i = 0; i < numGoodResults; ++i) {
                 assertNotSame("Number of attempted measurements is 0", 0, numAttempted[i]);