Merge "Verify that getAppStandbyBucket() can be called" into pi-dev
diff --git a/apps/CameraITS/tests/scene1/test_exposure.py b/apps/CameraITS/tests/scene1/test_exposure.py
index ed469a3..460fe7c 100644
--- a/apps/CameraITS/tests/scene1/test_exposure.py
+++ b/apps/CameraITS/tests/scene1/test_exposure.py
@@ -31,7 +31,9 @@
 THRESHOLD_MAX_LEVEL_DIFF = 0.045
 THRESHOLD_MAX_LEVEL_DIFF_WIDE_RANGE = 0.06
 THRESH_ROUND_DOWN_GAIN = 0.1
-THRESH_ROUND_DOWN_EXP = 0.05
+THRESH_ROUND_DOWN_EXP = 0.03
+THRESH_ROUND_DOWN_EXP0 = 1.00  # tol at 0ms exp; theoretical limit @ 4-line exp
+THRESH_EXP_KNEE = 1E6  # exposures less than 1ms have relaxed tol
 
 
 def get_raw_active_array_size(props):
@@ -94,12 +96,20 @@
             cap = cam.do_capture(req, fmt)
             s_res = cap['metadata']['android.sensor.sensitivity']
             e_res = cap['metadata']['android.sensor.exposureTime']
+            # determine exposure tolerance based on exposure time
+            if e_test >= THRESH_EXP_KNEE:
+                thresh_round_down_exp = THRESH_ROUND_DOWN_EXP
+            else:
+                thresh_round_down_exp = (
+                        THRESH_ROUND_DOWN_EXP +
+                        (THRESH_ROUND_DOWN_EXP0 - THRESH_ROUND_DOWN_EXP) *
+                        (THRESH_EXP_KNEE - e_test) / THRESH_EXP_KNEE)
             s_msg = 's_write: %d, s_read: %d, TOL=%.f%%' % (
                     s_test, s_res, THRESH_ROUND_DOWN_GAIN*100)
             e_msg = 'e_write: %.2fms, e_read: %.2fms, TOL=%.f%%' % (
-                    e_test/1.0E6, e_res/1.0E6, THRESH_ROUND_DOWN_EXP*100)
+                    e_test/1.0E6, e_res/1.0E6, thresh_round_down_exp*100)
             assert 0 <= s_test - s_res < s_test * THRESH_ROUND_DOWN_GAIN, s_msg
-            assert 0 <= e_test - e_res < e_test * THRESH_ROUND_DOWN_EXP, e_msg
+            assert 0 <= e_test - e_res < e_test * thresh_round_down_exp, e_msg
             s_e_product_res = s_res * e_res
             request_result_ratio = s_e_product / s_e_product_res
             print 'Capture result s:', s_test, 'e:', e_test
diff --git a/apps/CameraITS/tests/scene1/test_multi_camera_match.py b/apps/CameraITS/tests/scene1/test_multi_camera_match.py
index f78dac1..0eee74a 100644
--- a/apps/CameraITS/tests/scene1/test_multi_camera_match.py
+++ b/apps/CameraITS/tests/scene1/test_multi_camera_match.py
@@ -41,69 +41,52 @@
                              its.caps.raw16(props) and
                              its.caps.manual_sensor(props))
         ids = its.caps.logical_multi_camera_physical_ids(props)
-        s, e, _, _, f = cam.do_3a(get_results=True)
-        req = its.objects.manual_capture_request(s, e, f)
         max_raw_size = its.objects.get_available_output_sizes('raw', props)[0]
         for i in ids:
             physical_props = cam.get_camera_properties_by_id(i)
+            its.caps.skip_unless(not its.caps.mono_camera(physical_props))
             yuv_sizes[i] = its.objects.get_available_output_sizes(
                     'yuv', physical_props, match_ar_size=max_raw_size)
             if i == ids[0]:
                 yuv_match_sizes = yuv_sizes[i]
             else:
                 list(set(yuv_sizes[i]).intersection(yuv_match_sizes))
+
+        # find matched size for captures
         yuv_match_sizes.sort()
         w = yuv_match_sizes[-1][0]
         h = yuv_match_sizes[-1][1]
-        print 'RAW size: (%d, %d)' % (max_raw_size[0], max_raw_size[1])
-        print 'YUV size: (%d, %d)' % (w, h)
+        print 'Matched YUV size: (%d, %d)' % (w, h)
+
+        # do 3a and create requests
+        avail_fls = props['android.lens.info.availableFocalLengths']
+        cam.do_3a()
+        reqs = []
+        for i, fl in enumerate(avail_fls):
+            reqs.append(its.objects.auto_capture_request())
+            reqs[i]['android.lens.focalLength'] = fl
 
         # capture YUVs
-        out_surfaces = [{'format': 'raw'},
-                        {'format': 'yuv', 'width': w, 'height': h,
-                         'physicalCamera': ids[0]},
-                        {'format': 'yuv', 'width': w, 'height': h,
-                         'physicalCamera': ids[1]}]
-        cap_raw, cap_yuv1, cap_yuv2 = cam.do_capture(req, out_surfaces)
+        y_means = {}
+        msg = ''
+        fmt = [{'format': 'yuv', 'width': w, 'height': h}]
+        caps = cam.do_capture(reqs, fmt)
 
-        img_raw = its.image.convert_capture_to_rgb_image(cap_raw, props=props)
-        its.image.write_image(img_raw, '%s_raw.jpg' % NAME)
-        rgb_means_raw = its.image.compute_image_means(
-                its.image.get_image_patch(img_raw, PATCH_LOC, PATCH_LOC,
-                                          PATCH_SIZE, PATCH_SIZE))
-
-        img_yuv1 = its.image.convert_capture_to_rgb_image(
-                cap_yuv1, props=props)
-        its.image.write_image(img_yuv1, '%s_yuv1.jpg' % NAME)
-        y1, _, _ = its.image.convert_capture_to_planes(
-                cap_yuv1, props=props)
-        y1_mean = its.image.compute_image_means(
-                its.image.get_image_patch(y1, PATCH_LOC, PATCH_LOC,
-                                          PATCH_SIZE, PATCH_SIZE))[0]
-
-        img_yuv2 = its.image.convert_capture_to_rgb_image(
-                cap_yuv2, props=props)
-        its.image.write_image(img_yuv2, '%s_yuv2.jpg' % NAME)
-        y2, _, _ = its.image.convert_capture_to_planes(
-                cap_yuv2, props=props)
-        y2_mean = its.image.compute_image_means(
-                its.image.get_image_patch(y2, PATCH_LOC, PATCH_LOC,
-                                          PATCH_SIZE, PATCH_SIZE))[0]
-        print 'rgb_raw:', rgb_means_raw
-        print 'y1_mean:', y1_mean
-        print 'y2_mean:', y2_mean
-
-        # assert gain/exp values are near written values
-        s_yuv1 = cap_yuv1['metadata']['android.sensor.sensitivity']
-        e_yuv1 = cap_yuv1['metadata']['android.sensor.exposureTime']
-        msg = 'yuv_gain(write): %d, (read): %d' % (s, s_yuv1)
-        assert 0 <= s - s_yuv1 < s * THRESH_GAIN, msg
-        msg = 'yuv_exp(write): %.3fms, (read): %.3fms' % (e*1E6, e_yuv1*1E6)
-        assert 0 <= e - e_yuv1 < e * THRESH_EXP, msg
+        for i, fl in enumerate(avail_fls):
+            img = its.image.convert_capture_to_rgb_image(caps[i], props=props)
+            its.image.write_image(img, '%s_yuv_fl=%s.jpg' % (NAME, fl))
+            y, _, _ = its.image.convert_capture_to_planes(caps[i], props=props)
+            y_mean = its.image.compute_image_means(
+                    its.image.get_image_patch(y, PATCH_LOC, PATCH_LOC,
+                                              PATCH_SIZE, PATCH_SIZE))[0]
+            print 'y[%s]: %.3f' % (fl, y_mean)
+            msg += 'y[%s]: %.3f, ' % (fl, y_mean)
+            y_means[fl] = y_mean
 
         # compare YUVs
-        msg = 'y1: %.3f, y2: %.3f, TOL=%.5f' % (y1_mean, y2_mean, THRESH_DIFF)
-        assert np.isclose(y1_mean, y2_mean, rtol=THRESH_DIFF), msg
+        msg += 'TOL=%.5f' % THRESH_DIFF
+        assert np.isclose(max(y_means.values()), min(y_means.values()),
+                          rtol=THRESH_DIFF), msg
 
 
 if __name__ == '__main__':
diff --git a/apps/CameraITS/tests/scene3/test_3a_consistency.py b/apps/CameraITS/tests/scene3/test_3a_consistency.py
index 76b44ce..e86da42 100644
--- a/apps/CameraITS/tests/scene3/test_3a_consistency.py
+++ b/apps/CameraITS/tests/scene3/test_3a_consistency.py
@@ -20,8 +20,7 @@
 
 GGAIN_TOL = 0.1
 FD_TOL = 0.1
-SENS_TOL = 0.1
-EXP_TOL = 0.1
+ISO_EXP_TOL = 0.1
 NUM_TEST_ITERATIONS = 3
 
 
@@ -36,27 +35,24 @@
         its.caps.skip_unless(its.caps.read_3a(props))
         mono_camera = its.caps.mono_camera(props)
 
-        exps = []
-        senses = []
+        iso_exps = []
         g_gains = []
         fds = []
         for _ in range(NUM_TEST_ITERATIONS):
             try:
                 s, e, gains, xform, fd = cam.do_3a(get_results=True,
                                                    mono_camera=mono_camera)
-                print ' sensitivity', s, 'exposure', e
-                print ' gains', gains, 'transform', xform
+                print ' iso: %d, exposure: %d, iso*exp: %d' % (s, e, e*s)
+                print ' awb_gains', gains, 'awb_transform', xform
                 print ' fd', fd
                 print ''
-                exps.append(e)
-                senses.append(s)
+                iso_exps.append(e*s)
                 g_gains.append(gains[2])
                 fds.append(fd)
             except its.error.Error:
                 print ' FAIL\n'
-        assert len(exps) == NUM_TEST_ITERATIONS
-        assert np.isclose(np.amax(exps), np.amin(exps), EXP_TOL)
-        assert np.isclose(np.amax(senses), np.amin(senses), SENS_TOL)
+        assert len(iso_exps) == NUM_TEST_ITERATIONS
+        assert np.isclose(np.amax(iso_exps), np.amin(iso_exps), ISO_EXP_TOL)
         assert np.isclose(np.amax(g_gains), np.amin(g_gains), GGAIN_TOL)
         assert np.isclose(np.amax(fds), np.amin(fds), FD_TOL)
         for g in gains:
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index a1b188d..9de696a 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -1207,8 +1207,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST"/>
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_hardware"/>
-            <meta-data android:name="test_required_features" android:value="android.hardware.location.gps" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.wifi" />
+            <meta-data android:name="test_required_features"
+                       android:value="android.hardware.location.gps:android.hardware.wifi:android.hardware.telephony"/>
         </activity>
 
         <activity android:name=".location.EmergencyCallMessageTestsActivity"
@@ -1219,9 +1219,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST"/>
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_hardware"/>
-            <meta-data android:name="test_required_features" android:value="android.hardware.location.gps" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.wifi" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.telephony"/>
+            <meta-data android:name="test_required_features"
+                       android:value="android.hardware.location.gps:android.hardware.wifi:android.hardware.telephony"/>
         </activity>
 
         <activity android:name=".location.EmergencyCallGNSSTestsActivity"
@@ -1232,8 +1231,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST"/>
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_hardware"/>
-            <meta-data android:name="test_required_features" android:value="android.hardware.location.gps" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.wifi" />
+            <meta-data android:name="test_required_features"
+                       android:value="android.hardware.location.gps:android.hardware.wifi:android.hardware.telephony"/>
         </activity>
 
         <activity android:name=".location.GnssMeasurementWhenNoLocationTestsActivity"
@@ -2848,7 +2847,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_jobscheduler" />
             <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=".jobscheduler.ConnectivityConstraintTestActivity" android:label="@string/js_connectivity_test">
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/HidDeviceActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/HidDeviceActivity.java
index 465573c..24a097d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/HidDeviceActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/HidDeviceActivity.java
@@ -190,6 +190,11 @@
 
 
     private boolean getConnectedDevice() {
+        if (mBluetoothHidDevice == null) {
+            Log.w(TAG, "mBluetoothHidDevice is null");
+            return false;
+        }
+
         List<BluetoothDevice> connectedDevices = mBluetoothHidDevice.getConnectedDevices();
         if (connectedDevices.size() == 0) {
             return false;
@@ -199,6 +204,11 @@
     }
 
     private void testSendReport() {
+        if (mBluetoothHidDevice == null) {
+            Log.w(TAG, "mBluetoothHidDevice is null");
+            return;
+        }
+
         if (mHidHost == null) {
             if (mBluetoothHidDevice.getConnectedDevices().size() == 0) {
                 Log.w(TAG, "HID host not connected");
@@ -219,6 +229,11 @@
     }
 
     private void testReplyReport() {
+        if (mBluetoothHidDevice == null) {
+            Log.w(TAG, "mBluetoothHidDevice is null");
+            return;
+        }
+
         if (mHidHost == null) {
             if (mBluetoothHidDevice.getConnectedDevices().size() == 0) {
                 Log.w(TAG, "HID host not connected");
@@ -235,6 +250,11 @@
     }
 
     private void testReportError() {
+        if (mBluetoothHidDevice == null) {
+            Log.w(TAG, "mBluetoothHidDevice is null");
+            return;
+        }
+
         if (mHidHost == null) {
             if (mBluetoothHidDevice.getConnectedDevices().size() == 0) {
                 Log.w(TAG, "HID host not connected");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java
index 531b40b..e25f758 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java
@@ -57,11 +57,19 @@
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
+        // skip current test if device doesn't support cellular
+        if (!EmergencyCallUtil.isPhoneDevice(this)) {
+          String skipInfo = getResources().getString(R.string.emergency_call_skip_info);
+          TestResult.setPassedResult(this, super.getClass().getName(), skipInfo);
+          Toast toast = Toast.makeText(getApplicationContext(), skipInfo, Toast.LENGTH_LONG);
+          toast.show();
+          this.finish();
+          return;
+        }
         // override the test info
         mTextView.setText(R.string.location_emergency_call_test_info);
         EmergencyCallUtil.setDefaultDialer(this, this.getPackageName());
         setPassFailButtonClickListeners();
-
     }
 
     @Override
@@ -74,15 +82,7 @@
 
     @Override
     public void onClick(View target) {
-        // skip current test if device doesn't support cellular
-        if (!EmergencyCallUtil.isPhoneDevice(this)) {
-            String skipInfo = getResources().getString(R.string.emergency_call_skip_info);
-            TestResult.setPassedResult(this, super.getClass().getName(), skipInfo);
-            Toast toast = Toast.makeText(getApplicationContext(), skipInfo, Toast.LENGTH_LONG);
-            toast.show();
-            this.finish();
-            return;
-        }
+
         AlertDialog.Builder builder = new AlertDialog.Builder(this);
         final FrameLayout frameView = new FrameLayout(this);
         builder.setView(frameView);
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
index ebf881a..50ca741 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
@@ -83,11 +83,11 @@
     }
 
     /** Returns true if the device is a low ram device:
-     *  1. API level &gt;= O
+     *  1. API level &gt;= O_MR1
      *  2. device has feature LOW_RAM_FEATURE
      */
     public static boolean isLowRam() {
-        return ApiLevelUtil.isAtLeast(Build.VERSION_CODES.O) &&
+        return ApiLevelUtil.isAtLeast(Build.VERSION_CODES.O_MR1) &&
                 hasSystemFeature(LOW_RAM_FEATURE);
     }
 
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
index c41e0e9..08fe441 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
@@ -42,6 +42,7 @@
     private static final String BUILD_TYPE_PROPERTY = "ro.build.type";
     private static final String MANUFACTURER_PROPERTY = "ro.product.manufacturer";
     private static final String TAG_DEV_KEYS = "dev-keys";
+    private static final String VNDK_VERSION = "ro.vndk.version";
 
     public static final String GOOGLE_SETTINGS_QUERY =
             "content query --uri content://com.google.settings/partner";
@@ -81,6 +82,19 @@
     }
 
     /**
+     * Return whether the SDK version of the vendor partiton is newer than the given API level.
+     * If the property is set to non-integer value, this means the vendor partition is using
+     * current API level and true is returned.
+     */
+    public static boolean isVendorApiLevelNewerThan(int apiLevel) {
+        int vendorApiLevel = getPropertyInt(VNDK_VERSION);
+        if (vendorApiLevel == INT_VALUE_IF_UNSET) {
+            return true;
+        }
+        return vendorApiLevel > apiLevel;
+    }
+
+    /**
      * Return the manufacturer of this product. If unset, return null.
      */
     public static String getManufacturer() {
diff --git a/hostsidetests/incident/apps/graphicsstatsapp/src/com/android/server/cts/device/graphicsstats/SimpleDrawFrameTests.java b/hostsidetests/incident/apps/graphicsstatsapp/src/com/android/server/cts/device/graphicsstats/SimpleDrawFrameTests.java
index ff3e9eb..b2b8b7d 100644
--- a/hostsidetests/incident/apps/graphicsstatsapp/src/com/android/server/cts/device/graphicsstats/SimpleDrawFrameTests.java
+++ b/hostsidetests/incident/apps/graphicsstatsapp/src/com/android/server/cts/device/graphicsstats/SimpleDrawFrameTests.java
@@ -23,6 +23,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
 /**
  * Used by GraphicsStatsTest.
@@ -40,10 +41,11 @@
     public void testDrawTenFrames() throws Throwable {
         DrawFramesActivity activity = mActivityRule.getActivity();
         activity.waitForReady();
-        assertEquals(1, activity.getRenderedFramesCount());
+        int initialFrames = activity.getRenderedFramesCount();
+        assertTrue(initialFrames < 5);
         assertEquals(0, activity.getDroppedReportsCount());
         activity.drawFrames(10);
-        assertEquals(11, activity.getRenderedFramesCount());
+        assertEquals(initialFrames + 10, activity.getRenderedFramesCount());
         assertEquals(0, activity.getDroppedReportsCount());
     }
 
@@ -51,7 +53,8 @@
     public void testDrawJankyFrames() throws Throwable {
         DrawFramesActivity activity = mActivityRule.getActivity();
         activity.waitForReady();
-        assertEquals(1, activity.getRenderedFramesCount());
+        int initialFrames = activity.getRenderedFramesCount();
+        assertTrue(initialFrames < 5);
         assertEquals(0, activity.getDroppedReportsCount());
         int[] frames = new int[50];
         for (int i = 0; i < 10; i++) {
@@ -62,7 +65,7 @@
             frames[indx + 3] = DrawFramesActivity.FRAME_JANK_MISS_VSYNC;
         }
         activity.drawFrames(frames);
-        assertEquals(51, activity.getRenderedFramesCount());
+        assertEquals(initialFrames + 50, activity.getRenderedFramesCount());
         assertEquals(0, activity.getDroppedReportsCount());
     }
 
@@ -70,7 +73,8 @@
     public void testDrawDaveyFrames() throws Throwable {
         DrawFramesActivity activity = mActivityRule.getActivity();
         activity.waitForReady();
-        assertEquals(1, activity.getRenderedFramesCount());
+        int initialFrames = activity.getRenderedFramesCount();
+        assertTrue(initialFrames < 5);
         assertEquals(0, activity.getDroppedReportsCount());
         int[] frames = new int[40];
         for (int i = 0; i < 10; i++) {
@@ -79,7 +83,7 @@
             frames[indx + 2] = DrawFramesActivity.FRAME_JANK_DAVEY_JR;
         }
         activity.drawFrames(frames);
-        assertEquals(41, activity.getRenderedFramesCount());
+        assertEquals(initialFrames + 40, activity.getRenderedFramesCount());
         assertEquals(0, activity.getDroppedReportsCount());
     }
 }
diff --git a/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java b/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
index 368b574..e48aeb1 100644
--- a/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
@@ -57,7 +57,6 @@
         int level = dump.getLevel();
         assertTrue(level >= 0 && level <= scale);
         assertTrue(dump.getVoltage() > 0);
-        assertTrue(dump.getTemperature() > 0);
     }
 
     static boolean hasBattery(ITestDevice device) throws DeviceNotAvailableException {
diff --git a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
index 5237de9..1041638 100644
--- a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
@@ -65,7 +65,7 @@
         int frameDelta = summaryAfter.getTotalFrames() - summaryBefore.getTotalFrames();
         int jankyDelta = summaryAfter.getJankyFrames() - summaryBefore.getJankyFrames();
         // We expect 11 frames to have been drawn (first frame + the 10 more explicitly requested)
-        assertEquals(11, frameDelta);
+        assertTrue(frameDelta < 15);
         assertTrue(jankyDelta < 5);
         int veryJankyDelta = countFramesAbove(statsAfter, 40) - countFramesAbove(statsBefore, 40);
         // The 1st frame could be >40ms, but nothing after that should be
@@ -84,7 +84,7 @@
         int jankyDelta = summaryAfter.getJankyFrames() - summaryBefore.getJankyFrames();
         // Test draws 50 frames + 1 initial frame. We expect 40 of them to be janky,
         // 10 of each of ANIMATION, LAYOUT, RECORD_DRAW, and MISSED_VSYNC
-        assertEquals(51, frameDelta);
+        assertTrue(frameDelta < 55);
         assertTrue(jankyDelta >= 40);
         assertTrue(jankyDelta < 45);
 
@@ -114,7 +114,7 @@
         int jankyDelta = summaryAfter.getJankyFrames() - summaryBefore.getJankyFrames();
         // Test draws 40 frames + 1 initial frame. We expect 10 of them to be daveys,
         // 10 of them to be daveyjrs, and 20 to jank from missed vsync (from the davey/daveyjr prior to it)
-        assertEquals(41, frameDelta);
+        assertTrue(frameDelta < 45);
         assertTrue(jankyDelta >= 20);
         assertTrue(jankyDelta < 25);
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
index bc4ac7d..eb96b83 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
@@ -516,28 +516,6 @@
         }
     }
 
-    public void testModemActivityInfo() throws Exception {
-        if (statsdDisabled()) {
-            return;
-        }
-        if (!hasFeature(FEATURE_TELEPHONY, true)) return;
-        StatsdConfig.Builder config = getPulledConfig();
-        addGaugeAtom(config, Atom.MODEM_ACTIVITY_INFO_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> dataList = getGaugeMetricDataList();
-
-        for (Atom atom: dataList) {
-            assertTrue(atom.getModemActivityInfo().getTimestampMillis() > 0);
-            assertTrue(atom.getModemActivityInfo().getSleepTimeMillis() > 0);
-        }
-    }
-
     public void testWifiActivityInfo() throws Exception {
         if (statsdDisabled()) {
             return;
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index 01fd657..2dda663 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -69,6 +69,7 @@
     private static final String FEATURE_AUDIO_OUTPUT = "android.hardware.audio.output";
     private static final String FEATURE_WATCH = "android.hardware.type.watch";
     private static final String FEATURE_PICTURE_IN_PICTURE = "android.software.picture_in_picture";
+    private static final String FEATURE_PC = "android.hardware.type.pc";
 
     private static final boolean DAVEY_ENABLED = false;
 
@@ -565,6 +566,7 @@
             return;
         }
         if (!hasFeature(FEATURE_WIFI, true)) return;
+        if (!hasFeature(FEATURE_PC, false)) return;
 
         final int atomTag = Atom.WIFI_LOCK_STATE_CHANGED_FIELD_NUMBER;
         Set<Integer> lockOn = new HashSet<>(Arrays.asList(WifiLockStateChanged.State.ON_VALUE));
@@ -589,6 +591,7 @@
             return;
         }
         if (!hasFeature(FEATURE_WIFI, true)) return;
+        if (!hasFeature(FEATURE_PC, false)) return;
 
         final int atomTag = Atom.WIFI_MULTICAST_LOCK_STATE_CHANGED_FIELD_NUMBER;
         Set<Integer> lockOn = new HashSet<>(
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/BatteryConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/BatteryConstraintTest.java
index e03d4ae..35eb06f 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/BatteryConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/BatteryConstraintTest.java
@@ -246,7 +246,7 @@
      * the battery level is critical and not on power.
      */
     public void testBatteryNotLowConstraintFails_withoutPower() throws Exception {
-        setBatteryState(false, 15);
+        setBatteryState(false, 5);
         // setBatteryState() waited for the charging/not-charging state to formally settle,
         // but battery level reporting lags behind that.  wait a moment to let that happen
         // before proceeding.
@@ -281,8 +281,8 @@
                 kTestEnvironment.awaitExecution());
 
         // And check that the job is stopped if battery goes low again.
-        setBatteryState(false, 15);
-        setBatteryState(false, 14);
+        setBatteryState(false, 5);
+        setBatteryState(false, 4);
         waitFor(2_000);
         verifyChargingState(false);
         verifyBatteryNotLowState(false);
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java
index 6a60b82..10b84d6 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java
@@ -18,6 +18,7 @@
 
 import android.annotation.TargetApi;
 import android.app.job.JobInfo;
+import android.os.SystemClock;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.uiautomator.UiDevice;
 
@@ -58,12 +59,21 @@
         assertJobNotReady(STATE_JOB_ID);
     }
 
+    static void waitFor(long waitMillis) throws Exception {
+        final long deadline = SystemClock.uptimeMillis() + waitMillis;
+        do {
+             Thread.sleep(500L);
+        } while (SystemClock.uptimeMillis() < deadline);
+    }
+
     /**
      * Toggle device is dock idle or dock active.
      */
     private void toggleFakeDeviceDockState(final boolean idle) throws Exception {
         mUiDevice.executeShellCommand("cmd jobscheduler trigger-dock-state "
                 + (idle ? "idle" : "active"));
+        // Wait a moment to let that happen before proceeding.
+        waitFor(2_000);
     }
 
     /**
@@ -71,12 +81,12 @@
      */
     private void toggleScreenOn(final boolean screenon) throws Exception {
         if (screenon) {
-            mUiDevice.wakeUp();
+            mUiDevice.executeShellCommand("input keyevent KEYCODE_WAKEUP");
         } else {
-            mUiDevice.sleep();
+            mUiDevice.executeShellCommand("input keyevent KEYCODE_SLEEP");
         }
         // Since the screen on/off intent is ordered, they will not be sent right now.
-        Thread.sleep(3000);
+        waitFor(2_000);
     }
 
     /**
@@ -84,6 +94,8 @@
      */
     private void triggerIdleMaintenance() throws Exception {
         mUiDevice.executeShellCommand("cmd activity idle-maintenance");
+        // Wait a moment to let that happen before proceeding.
+        waitFor(2_000);
     }
 
     /**
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
index 25b7762..b0d7001 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
@@ -237,7 +237,7 @@
 
         dispatch(swipe(
                 mTapLocation,
-                add(mTapLocation, 31, 29)));
+                add(mTapLocation, 0, 29)));
         assertPropagated(ACTION_DOWN, ACTION_MOVE, ACTION_UP);
     }
 
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 1e4d9d9..3f61605 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -524,7 +524,7 @@
 
         int id = 1;
         final Notification notification =
-                new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+                new Notification.Builder(mContext, mId)
                         .setSmallIcon(R.drawable.black)
                         .setWhen(System.currentTimeMillis())
                         .setContentTitle("notify#" + id)
@@ -550,7 +550,7 @@
 
         int id = 1;
         final Notification notification =
-                new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+                new Notification.Builder(mContext, mId)
                         .setSmallIcon(R.drawable.black)
                         .setWhen(System.currentTimeMillis())
                         .setContentTitle("notify#" + id)
diff --git a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
index 5bf722c..651b8b6 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
@@ -306,8 +306,7 @@
     }
 
     public void testConstrainedHighSpeedRecording() throws Exception {
-        constrainedHighSpeedRecording(/*enableSessionParams*/ false);
-        constrainedHighSpeedRecording(/*enableSessionParams*/ true);
+        constrainedHighSpeedRecording();
     }
 
     public void testAbandonedHighSpeedRequest() throws Exception {
@@ -649,8 +648,7 @@
                     // Start recording
                     SimpleCaptureCallback resultListener = new SimpleCaptureCallback();
                     startSlowMotionRecording(/*useMediaRecorder*/true, videoFramerate, captureRate,
-                            fpsRange, resultListener, /*useHighSpeedSession*/false,
-                            /*enableHighSpeedParams*/ false);
+                            fpsRange, resultListener, /*useHighSpeedSession*/false);
 
                     // Record certain duration.
                     SystemClock.sleep(RECORDING_DURATION_MS);
@@ -672,7 +670,7 @@
         }
     }
 
-    private void constrainedHighSpeedRecording(boolean enableSessionParams) throws Exception {
+    private void constrainedHighSpeedRecording() throws Exception {
         for (String id : mCameraIds) {
             try {
                 Log.i(TAG, "Testing constrained high speed recording for camera " + id);
@@ -725,8 +723,7 @@
                         // Start recording
                         startSlowMotionRecording(/*useMediaRecorder*/true, VIDEO_FRAME_RATE,
                                 captureRate, fpsRange, resultListener,
-                                /*useHighSpeedSession*/true,
-                                /*enableHighSpeedParams*/ enableSessionParams);
+                                /*useHighSpeedSession*/true);
 
                         // Record certain duration.
                         SystemClock.sleep(RECORDING_DURATION_MS);
@@ -812,24 +809,25 @@
         assertTrue("Preview surface should be valid", mPreviewSurface.isValid());
         outputSurfaces.add(mPreviewSurface);
         mSessionListener = new BlockingSessionCallback();
-        mSession = configureCameraSession(mCamera, outputSurfaces, /*isHighSpeed*/ true,
-                mSessionListener, mHandler);
 
         List<CaptureRequest> slowMoRequests = null;
         CaptureRequest.Builder requestBuilder =
             mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
         requestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
         requestBuilder.addTarget(mPreviewSurface);
+        CaptureRequest initialRequest = requestBuilder.build();
+        mSession = buildConstrainedCameraSession(mCamera, outputSurfaces, mSessionListener,
+                mHandler, initialRequest);
         slowMoRequests = ((CameraConstrainedHighSpeedCaptureSession) mSession).
-            createHighSpeedRequestList(requestBuilder.build());
+            createHighSpeedRequestList(initialRequest);
 
         mSession.setRepeatingBurst(slowMoRequests, listener, mHandler);
     }
 
     private void startSlowMotionRecording(boolean useMediaRecorder, int videoFrameRate,
             int captureRate, Range<Integer> fpsRange,
-            CameraCaptureSession.CaptureCallback listener, boolean useHighSpeedSession,
-            boolean enableHighSpeedParams) throws Exception {
+            CameraCaptureSession.CaptureCallback listener, boolean useHighSpeedSession)
+            throws Exception {
         List<Surface> outputSurfaces = new ArrayList<Surface>(2);
         assertTrue("Both preview and recording surfaces should be valid",
                 mPreviewSurface.isValid() && mRecordingSurface.isValid());
@@ -840,13 +838,6 @@
             outputSurfaces.add(mReaderSurface);
         }
         mSessionListener = new BlockingSessionCallback();
-        if (useHighSpeedSession && enableHighSpeedParams) {
-            mSession = buildConstrainedCameraSession(mCamera, outputSurfaces, useHighSpeedSession,
-                    mSessionListener, mHandler);
-        } else {
-            mSession = configureCameraSession(mCamera, outputSurfaces, useHighSpeedSession,
-                    mSessionListener, mHandler);
-        }
 
         // Create slow motion request list
         List<CaptureRequest> slowMoRequests = null;
@@ -856,8 +847,11 @@
             requestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
             requestBuilder.addTarget(mPreviewSurface);
             requestBuilder.addTarget(mRecordingSurface);
+            CaptureRequest initialRequest = requestBuilder.build();
+            mSession = buildConstrainedCameraSession(mCamera, outputSurfaces, mSessionListener,
+                    mHandler, initialRequest);
             slowMoRequests = ((CameraConstrainedHighSpeedCaptureSession) mSession).
-                    createHighSpeedRequestList(requestBuilder.build());
+                    createHighSpeedRequestList(initialRequest);
         } else {
             CaptureRequest.Builder recordingRequestBuilder =
                     mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
@@ -881,8 +875,12 @@
             recordingOnlyBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
             recordingOnlyBuilder.addTarget(mRecordingSurface);
 
+            CaptureRequest initialRequest = recordingRequestBuilder.build();
+            mSession = configureCameraSessionWithParameters(mCamera, outputSurfaces,
+                    mSessionListener, mHandler, initialRequest);
+
             slowMoRequests = new ArrayList<CaptureRequest>();
-            slowMoRequests.add(recordingRequestBuilder.build());// Preview + recording.
+            slowMoRequests.add(initialRequest);// Preview + recording.
 
             for (int i = 0; i < slowMotionFactor - 1; i++) {
                 slowMoRequests.add(recordingOnlyBuilder.build()); // Recording only.
@@ -1510,7 +1508,6 @@
             outputSurfaces.add(mReaderSurface);
         }
         mSessionListener = new BlockingSessionCallback();
-        mSession = configureCameraSession(mCamera, outputSurfaces, mSessionListener, mHandler);
 
         CaptureRequest.Builder recordingRequestBuilder =
                 mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
@@ -1525,7 +1522,10 @@
         }
         recordingRequestBuilder.addTarget(mRecordingSurface);
         recordingRequestBuilder.addTarget(mPreviewSurface);
-        mSession.setRepeatingRequest(recordingRequestBuilder.build(), listener, mHandler);
+        CaptureRequest recordingRequest = recordingRequestBuilder.build();
+        mSession = configureCameraSessionWithParameters(mCamera, outputSurfaces, mSessionListener,
+                mHandler, recordingRequest);
+        mSession.setRepeatingRequest(recordingRequest, listener, mHandler);
 
         if (useMediaRecorder) {
             mMediaRecorder.start();
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index cce6171..47020ed 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -2010,15 +2010,20 @@
                     case RAW: {
                         Size targetSize = (numConfigs == 1) ? maxSizes.maxRawSize :
                                 overridePhysicalCameraSizes.get(j);
-                        ImageReader target = ImageReader.newInstance(
-                            targetSize.getWidth(), targetSize.getHeight(), RAW, numBuffers);
-                        target.setOnImageAvailableListener(imageDropperListener, mHandler);
-                        OutputConfiguration config = new OutputConfiguration(target.getSurface());
-                        if (numConfigs > 1) {
-                            config.setPhysicalCameraId(overridePhysicalCameraIds.get(j));
+                        // targetSize could be null in the logical camera case where only
+                        // physical camera supports RAW stream.
+                        if (targetSize != null) {
+                            ImageReader target = ImageReader.newInstance(
+                                targetSize.getWidth(), targetSize.getHeight(), RAW, numBuffers);
+                            target.setOnImageAvailableListener(imageDropperListener, mHandler);
+                            OutputConfiguration config =
+                                    new OutputConfiguration(target.getSurface());
+                            if (numConfigs > 1) {
+                                config.setPhysicalCameraId(overridePhysicalCameraIds.get(j));
+                            }
+                            outputConfigs.add(config);
+                            rawTargets.add(target);
                         }
-                        outputConfigs.add(config);
-                        rawTargets.add(target);
                         break;
                     }
                     default:
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 22db2e9..f0714e1 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -788,16 +788,13 @@
      * @param camera The CameraDevice to be configured.
      * @param outputSurfaces The surface list that used for camera output.
      * @param listener The callback CameraDevice will notify when capture results are available.
+     * @param initialRequest Initial request settings to use as session parameters.
      */
     public static CameraCaptureSession buildConstrainedCameraSession(CameraDevice camera,
-            List<Surface> outputSurfaces, boolean isHighSpeed,
-            CameraCaptureSession.StateCallback listener, Handler handler)
-            throws CameraAccessException {
+            List<Surface> outputSurfaces, CameraCaptureSession.StateCallback listener,
+            Handler handler, CaptureRequest initialRequest) throws CameraAccessException {
         BlockingSessionCallback sessionListener = new BlockingSessionCallback(listener);
 
-        CaptureRequest.Builder builder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
-        CaptureRequest recordSessionParams = builder.build();
-
         List<OutputConfiguration> outConfigurations = new ArrayList<>(outputSurfaces.size());
         for (Surface surface : outputSurfaces) {
             outConfigurations.add(new OutputConfiguration(surface));
@@ -805,7 +802,7 @@
         SessionConfiguration sessionConfig = new SessionConfiguration(
                 SessionConfiguration.SESSION_HIGH_SPEED, outConfigurations,
                 new HandlerExecutor(handler), sessionListener);
-        sessionConfig.setSessionParameters(recordSessionParams);
+        sessionConfig.setSessionParameters(initialRequest);
         camera.createCaptureSession(sessionConfig);
 
         CameraCaptureSession session =
@@ -867,6 +864,37 @@
         return session;
     }
 
+    /**
+     * Configure a new camera session with output surfaces and initial session parameters.
+     *
+     * @param camera The CameraDevice to be configured.
+     * @param outputSurfaces The surface list that used for camera output.
+     * @param listener The callback CameraDevice will notify when session is available.
+     * @param handler The handler used to notify callbacks.
+     * @param initialRequest Initial request settings to use as session parameters.
+     */
+    public static CameraCaptureSession configureCameraSessionWithParameters(CameraDevice camera,
+            List<Surface> outputSurfaces, BlockingSessionCallback listener,
+            Handler handler, CaptureRequest initialRequest) throws CameraAccessException {
+        List<OutputConfiguration> outConfigurations = new ArrayList<>(outputSurfaces.size());
+        for (Surface surface : outputSurfaces) {
+            outConfigurations.add(new OutputConfiguration(surface));
+        }
+        SessionConfiguration sessionConfig = new SessionConfiguration(
+                SessionConfiguration.SESSION_REGULAR, outConfigurations,
+                new HandlerExecutor(handler), listener);
+        sessionConfig.setSessionParameters(initialRequest);
+        camera.createCaptureSession(sessionConfig);
+
+        CameraCaptureSession session = listener.waitAndGetSession(SESSION_CONFIGURE_TIMEOUT_MS);
+        assertFalse("Camera session should not be a reprocessable session",
+                session.isReprocessable());
+        assertFalse("Capture session type must be regular",
+                CameraConstrainedHighSpeedCaptureSession.class.isAssignableFrom(
+                        session.getClass()));
+
+        return session;
+    }
 
     /**
      * Configure a new camera session with output surfaces.
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
index 1dcee00..15b20d6 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
@@ -1565,7 +1565,7 @@
     public void testCloseIdleConnection() throws Exception {
         mDatabase.close();
         SQLiteDatabase.OpenParams params = new SQLiteDatabase.OpenParams.Builder()
-                .setIdleConnectionTimeout(1000).build();
+                .setIdleConnectionTimeout(5000).build();
         mDatabase = SQLiteDatabase.openDatabase(mDatabaseFile, params);
         // Wait a bit and check that connection is still open
         Thread.sleep(600);
@@ -1574,9 +1574,9 @@
                 output.contains("Connection #0:"));
 
         // Now cause idle timeout and check that connection is closed
-        // We wait up to 5 seconds, which is longer than required 1 s to accommodate for delays in
+        // We wait up to 10 seconds, which is longer than required 1 s to accommodate for delays in
         // message processing when system is busy
-        boolean connectionWasClosed = waitForConnectionToClose(10, 500);
+        boolean connectionWasClosed = waitForConnectionToClose(20, 500);
         assertTrue("Connection #0 should be closed", connectionWasClosed);
     }
 
diff --git a/tests/tests/graphics/AndroidManifest.xml b/tests/tests/graphics/AndroidManifest.xml
index dd80315..76552a1 100644
--- a/tests/tests/graphics/AndroidManifest.xml
+++ b/tests/tests/graphics/AndroidManifest.xml
@@ -38,7 +38,6 @@
 
         <activity android:name="android.graphics.cts.VulkanPreTransformCtsActivity"
             android:label="VulkanPreTransformCtsActivity"
-            android:screenOrientation="landscape"
             android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
         </activity>
 
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
index bdcb7b3..7019ea4 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
@@ -290,6 +290,13 @@
           static_cast<uint32_t>(surfaceCapabilities.currentTransform),
           static_cast<uint32_t>(preTransform));
 
+    if ((preTransform &
+         (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
+          VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
+          VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR)) != 0) {
+        std::swap(mDisplaySize.width, mDisplaySize.height);
+    }
+
     const uint32_t queueFamilyIndex = mDeviceInfo->queueFamilyIndex();
     const VkSwapchainCreateInfoKHR swapchainCreateInfo = {
             .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
diff --git a/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp b/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
index 7d1a428..2a347b2 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
@@ -33,7 +33,6 @@
 
 namespace {
 
-
 jboolean validatePixelValues(JNIEnv* env, jboolean setPreTransform) {
     jclass clazz = env->FindClass("android/graphics/cts/VulkanPreTransformTest");
     jmethodID mid = env->GetStaticMethodID(clazz, "validatePixelValuesAfterRotation", "(Z)Z");
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
index 0d426d4..0194044 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
@@ -17,11 +17,15 @@
 package android.graphics.cts;
 
 import android.app.Activity;
+import android.content.Context;
+import android.content.pm.ActivityInfo;
 import android.content.res.AssetManager;
+import android.content.res.Configuration;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.Surface;
 import android.view.SurfaceView;
+import android.view.WindowManager;
 
 /**
  * Activity for VulkanPreTransformTest.
@@ -33,19 +37,50 @@
 
     private static final String TAG = "vulkan";
 
+    private static boolean sOrientationRequested = false;
+
     protected Surface mSurface;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         Log.d(TAG, "onCreate!");
+        setActivityOrientation();
         setContentView(R.layout.vulkan_pretransform_layout);
         SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
         mSurface = surfaceView.getHolder().getSurface();
     }
 
+    private void setActivityOrientation() {
+        if (sOrientationRequested) {
+            // it might be called again because changing the orientation kicks off onCreate again!.
+            return;
+        }
+
+        if (((WindowManager) getSystemService(Context.WINDOW_SERVICE))
+                        .getDefaultDisplay()
+                        .getRotation()
+                != Surface.ROTATION_0) {
+            throw new RuntimeException("Display not in natural orientation");
+        }
+
+        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
+            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+        } else {
+            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+        }
+        sOrientationRequested = true;
+    }
+
+    public int getRotation() {
+        return ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
+                .getDefaultDisplay()
+                .getRotation();
+    }
+
     public void testVulkanPreTransform(boolean setPreTransform) {
         nCreateNativeTest(getAssets(), mSurface, setPreTransform);
+        sOrientationRequested = false;
     }
 
     private static native void nCreateNativeTest(
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
index cc2259a..06f92d3 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
@@ -28,6 +28,7 @@
 import android.test.suitebuilder.annotation.LargeTest;
 import android.util.Log;
 import android.view.PixelCopy;
+import android.view.Surface;
 import android.view.SurfaceView;
 
 import com.android.compatibility.common.util.SynchronousPixelCopy;
@@ -38,25 +39,34 @@
 import org.junit.runner.RunWith;
 
 /*
- * This test case runs in landscape mode
- *
  * testVulkanPreTransformSetToMatchCurrentTransform()
  *
- *      Buffer          ExpectedScreen
- *      ---------       ---------------
- *      | R | G |       | GGGG | YYYY |
- *      ---------       ---------------
- *      | B | Y |       | RRRR | BBBB |
- *      ---------       ---------------
+ *   For devices rotating 90 degree CW when orientation changes.
+ *
+ *      Buffer          Screen
+ *      ---------       ---------
+ *      | R | G |       | G | Y |
+ *      ---------       ---------
+ *      | B | Y |       | R | B |
+ *      ---------       ---------
+ *
+ *   For devices rotating 90 degree CCW when orientation changes.
+ *
+ *      Buffer          Screen
+ *      ---------       ---------
+ *      | R | G |       | B | R |
+ *      ---------       ---------
+ *      | B | Y |       | Y | G |
+ *      ---------       ---------
  *
  * testVulkanPreTransformNotSetToMatchCurrentTransform()
  *
- *      Buffer          ExpectedScreen
- *      ---------       ---------------
- *      | R | G |       | RRRR | GGGG |
- *      ---------       ---------------
- *      | B | Y |       | BBBB | YYYY |
- *      ---------       ---------------
+ *      Buffer          Screen
+ *      ---------       ---------
+ *      | R | G |       | R | G |
+ *      ---------       ---------
+ *      | B | Y |       | B | Y |
+ *      ---------       ---------
  */
 
 @LargeTest
@@ -126,16 +136,23 @@
         int width = bitmap.getWidth();
         int height = bitmap.getHeight();
         int diff = 0;
-        if (setPreTransform) {
-            diff += pixelDiff(bitmap.getPixel(0, 0), 0, 255, 0);
-            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 255, 0);
-            diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 0, 0);
-            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 0, 255);
-        } else {
+        if (!setPreTransform) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 255, 0);
+        } else if (sActivity.getRotation() == Surface.ROTATION_270) {
+            // For devices rotating 90 degree CCW when orientation changes.
+            diff += pixelDiff(bitmap.getPixel(0, 0), 0, 0, 255);
+            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 0, 0);
+            diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 255, 0);
+        } else {
+            // For devices rotating 90 degree CW when orientation changes.
+            diff += pixelDiff(bitmap.getPixel(0, 0), 0, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 0, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 0, 255);
         }
 
         return diff < 10;
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 0342f08..3b28ad4 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -718,8 +718,8 @@
 
     @SuppressWarnings("unchecked")
     private void checkAttestationSecurityLevelDependentParams(Attestation attestation) {
-        assertThat("Attestation version must be 1 or 2", attestation.getAttestationVersion(),
-                either(is(1)).or(is(2)));
+        assertThat("Attestation version must be 1, 2, or 3", attestation.getAttestationVersion(),
+               either(is(1)).or(is(2)).or(is(3)));
 
         AuthorizationList teeEnforced = attestation.getTeeEnforced();
         AuthorizationList softwareEnforced = attestation.getSoftwareEnforced();
diff --git a/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java b/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java
index 2c549f2..151c94a 100755
--- a/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTestXheAac.java
@@ -95,116 +95,124 @@
         assertTrue("No AAC decoder found", sAacDecoderNames.size() > 0);
 
         for (String aacDecName : sAacDecoderNames) {
-            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a running for dec=" + aacDecName);
-            // test DRC effectTypeID 1 "NIGHT"
-            // L -3dB -> normalization factor = 1/(10^(-3/10)) = 0.5011f
-            // R +3dB -> normalization factor = 1/(10^( 3/10)) = 1.9952f
             try {
-                checkUsacDrcEffectType(1, 0.5011f, 1.9952f, "Night", 2, 0, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/2/0 failed for dec=" + aacDecName);
-                throw new RuntimeException(e);
+                runDecodeUsacDrcEffectTypeM4a(aacDecName);
+            } catch (Error err) {
+                throw new Error(err.getMessage() + " [dec=" + aacDecName + "]" , err);
             }
+        }
+    }
 
-            // test DRC effectTypeID 2 "NOISY"
-            // L +3dB -> normalization factor = 1/(10^( 3/10)) = 1.9952f
-            // R -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
-            try {
-                checkUsacDrcEffectType(2, 1.9952f, 0.2511f, "Noisy", 2, 0, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Noisy/2/0 failed for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
+    private void runDecodeUsacDrcEffectTypeM4a(String aacDecName) throws Exception {
+        Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a running for dec=" + aacDecName);
+        // test DRC effectTypeID 1 "NIGHT"
+        // L -3dB -> normalization factor = 1/(10^(-3/10)) = 0.5011f
+        // R +3dB -> normalization factor = 1/(10^( 3/10)) = 1.9952f
+        try {
+            checkUsacDrcEffectType(1, 0.5011f, 1.9952f, "Night", 2, 0, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/2/0 failed for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        } 
 
-            // test DRC effectTypeID 3 "LIMITED"
-            // L -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
-            // R +6dB -> normalization factor = 1/(10^( 6/10)) = 3.9810f
-            try {
-                checkUsacDrcEffectType(3, 0.2511f, 3.9810f, "Limited", 2, 0, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Limited/2/0 failed for dec="
-                        + aacDecName);
-                throw new RuntimeException(e);
-            }
+        // test DRC effectTypeID 2 "NOISY"
+        // L +3dB -> normalization factor = 1/(10^( 3/10)) = 1.9952f
+        // R -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
+        try {
+            checkUsacDrcEffectType(2, 1.9952f, 0.2511f, "Noisy", 2, 0, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Noisy/2/0 failed for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
 
-            // test DRC effectTypeID 6 "GENERAL"
-            // L +6dB -> normalization factor = 1/(10^( 6/10)) = 3.9810f
-            // R -3dB -> normalization factor = 1/(10^(-3/10)) = 0.5011f
-            try {
-                checkUsacDrcEffectType(6, 3.9810f, 0.5011f, "General", 2, 0, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a General/2/0 failed for dec="
-                        + aacDecName);
-                throw new RuntimeException(e);
-            }
+        // test DRC effectTypeID 3 "LIMITED"
+        // L -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
+        // R +6dB -> normalization factor = 1/(10^( 6/10)) = 3.9810f
+        try {
+            checkUsacDrcEffectType(3, 0.2511f, 3.9810f, "Limited", 2, 0, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Limited/2/0 failed for dec="
+                    + aacDecName);
+            throw new RuntimeException(e);
+        }
 
-            // test DRC effectTypeID 1 "NIGHT"
-            // L    -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
-            // R    +6dB -> normalization factor = 1/(10^( 6/10)) = 3.9810f
-            // mono -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
-            try {
-                checkUsacDrcEffectType(1, 0.2511f, 3.9810f, "Night", 2, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/2/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
-            try {
-                checkUsacDrcEffectType(1, 0.2511f, 0.0f, "Night", 1, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/1/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
+        // test DRC effectTypeID 6 "GENERAL"
+        // L +6dB -> normalization factor = 1/(10^( 6/10)) = 3.9810f
+        // R -3dB -> normalization factor = 1/(10^(-3/10)) = 0.5011f
+        try {
+            checkUsacDrcEffectType(6, 3.9810f, 0.5011f, "General", 2, 0, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a General/2/0 failed for dec="
+                    + aacDecName);
+            throw new RuntimeException(e);
+        }
 
-            // test DRC effectTypeID 2 "NOISY"
-            // L    +6dB -> normalization factor = 1/(10^( 6/10))   = 3.9810f
-            // R    -9dB -> normalization factor = 1/(10^(-9/10))  = 0.1258f
-            // mono +6dB -> normalization factor = 1/(10^( 6/10))   = 3.9810f
-            try {
-                checkUsacDrcEffectType(2, 3.9810f, 0.1258f, "Noisy", 2, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Noisy/2/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
-            try {
-                checkUsacDrcEffectType(2, 3.9810f, 0.0f, "Noisy", 1, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/2/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
+        // test DRC effectTypeID 1 "NIGHT"
+        // L    -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
+        // R    +6dB -> normalization factor = 1/(10^( 6/10)) = 3.9810f
+        // mono -6dB -> normalization factor = 1/(10^(-6/10)) = 0.2511f
+        try {
+            checkUsacDrcEffectType(1, 0.2511f, 3.9810f, "Night", 2, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/2/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
+        try {
+            checkUsacDrcEffectType(1, 0.2511f, 0.0f, "Night", 1, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/1/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
 
-            // test DRC effectTypeID 3 "LIMITED"
-            // L    -9dB -> normalization factor = 1/(10^(-9/10)) = 0.1258f
-            // R    +9dB -> normalization factor = 1/(10^( 9/10)) = 7.9432f
-            // mono -9dB -> normalization factor = 1/(10^(-9/10)) = 0.1258f
-            try {
-                checkUsacDrcEffectType(3, 0.1258f, 7.9432f, "Limited", 2, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Limited/2/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
-            try {
-                checkUsacDrcEffectType(3, 0.1258f, 0.0f, "Limited", 1, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Limited/1/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
+        // test DRC effectTypeID 2 "NOISY"
+        // L    +6dB -> normalization factor = 1/(10^( 6/10))   = 3.9810f
+        // R    -9dB -> normalization factor = 1/(10^(-9/10))  = 0.1258f
+        // mono +6dB -> normalization factor = 1/(10^( 6/10))   = 3.9810f
+        try {
+            checkUsacDrcEffectType(2, 3.9810f, 0.1258f, "Noisy", 2, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Noisy/2/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
+        try {
+            checkUsacDrcEffectType(2, 3.9810f, 0.0f, "Noisy", 1, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Night/2/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
 
-            // test DRC effectTypeID 6 "GENERAL"
-            // L    +9dB -> normalization factor = 1/(10^( 9/10)) = 7.9432f
-            // R    -6dB -> normalization factor = 1/(10^(-6/10))  = 0.2511f
-            // mono +9dB -> normalization factor = 1/(10^( 9/10)) = 7.9432f
-            try {
-                checkUsacDrcEffectType(6, 7.9432f, 0.2511f, "General", 2, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a General/2/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
-            try {
-                checkUsacDrcEffectType(6, 7.9432f, 0.0f, "General", 1, 1, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a General/1/1 for dec=" + aacDecName);
-                throw new RuntimeException(e);
-            }
+        // test DRC effectTypeID 3 "LIMITED"
+        // L    -9dB -> normalization factor = 1/(10^(-9/10)) = 0.1258f
+        // R    +9dB -> normalization factor = 1/(10^( 9/10)) = 7.9432f
+        // mono -9dB -> normalization factor = 1/(10^(-9/10)) = 0.1258f
+        try {
+            checkUsacDrcEffectType(3, 0.1258f, 7.9432f, "Limited", 2, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Limited/2/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
+        try {
+            checkUsacDrcEffectType(3, 0.1258f, 0.0f, "Limited", 1, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a Limited/1/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
+
+        // test DRC effectTypeID 6 "GENERAL"
+        // L    +9dB -> normalization factor = 1/(10^( 9/10)) = 7.9432f
+        // R    -6dB -> normalization factor = 1/(10^(-6/10))  = 0.2511f
+        // mono +9dB -> normalization factor = 1/(10^( 9/10)) = 7.9432f
+        try {
+            checkUsacDrcEffectType(6, 7.9432f, 0.2511f, "General", 2, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a General/2/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
+        }
+        try {
+            checkUsacDrcEffectType(6, 7.9432f, 0.0f, "General", 1, 1, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacDrcEffectTypeM4a General/1/1 for dec=" + aacDecName);
+            throw new RuntimeException(e);
         }
     }
 
@@ -218,52 +226,61 @@
         assertTrue("No AAC decoder found", sAacDecoderNames.size() > 0);
 
         for (String aacDecName : sAacDecoderNames) {
-            // Stereo
-            // switch between SBR ratios and stereo modes
             try {
-                checkUsacStreamSwitching(2.5459829E12f, 2,
-                        R.raw.noise_2ch_44_1khz_aot42_19_lufs_config_change_mp4, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 2ch sbr/stereo switch for "
-                        + aacDecName);
-                throw new RuntimeException(e);
-            }
-
-            // Mono
-            // switch between SBR ratios and stereo modes
-            try {
-                checkUsacStreamSwitching(2.24669126E12f, 1,
-                        R.raw.noise_1ch_38_4khz_aot42_19_lufs_config_change_mp4, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 1ch sbr/stereo switch for "
-                        + aacDecName);
-                throw new RuntimeException(e);
-            }
-
-            // Stereo
-            // switch between USAC modes
-            try {
-                checkUsacStreamSwitching(2.1E12f, 2,
-                        R.raw.noise_2ch_35_28khz_aot42_19_lufs_drc_config_change_mp4, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 2ch USAC mode switch for "
-                        + aacDecName);
-                throw new RuntimeException(e);
-            }
-
-            // Mono
-            // switch between USAC modes
-            try {
-                checkUsacStreamSwitching(1.7E12f, 1,
-                        R.raw.noise_1ch_29_4khz_aot42_19_lufs_drc_config_change_mp4, aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 1ch USAC mode switch for "
-                        + aacDecName);
-                throw new RuntimeException(e);
+                runDecodeUsacStreamSwitchingM4a(aacDecName);
+            } catch (Error err) {
+                throw new Error(err.getMessage() + " [dec=" + aacDecName + "]" , err);
             }
         }
     }
 
+    private void runDecodeUsacStreamSwitchingM4a(String aacDecName) throws Exception {
+        // Stereo
+        // switch between SBR ratios and stereo modes
+        try {
+            checkUsacStreamSwitching(2.5459829E12f, 2,
+                    R.raw.noise_2ch_44_1khz_aot42_19_lufs_config_change_mp4, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 2ch sbr/stereo switch for "
+                    + aacDecName);
+            throw new RuntimeException(e);
+        }
+
+        // Mono
+        // switch between SBR ratios and stereo modes
+        try {
+            checkUsacStreamSwitching(2.24669126E12f, 1,
+                    R.raw.noise_1ch_38_4khz_aot42_19_lufs_config_change_mp4, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 1ch sbr/stereo switch for "
+                    + aacDecName);
+            throw new RuntimeException(e);
+        }
+
+        // Stereo
+        // switch between USAC modes
+        try {
+            checkUsacStreamSwitching(2.1E12f, 2,
+                    R.raw.noise_2ch_35_28khz_aot42_19_lufs_drc_config_change_mp4, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 2ch USAC mode switch for "
+                    + aacDecName);
+            throw new RuntimeException(e);
+        }
+
+        // Mono
+        // switch between USAC modes
+        try {
+            checkUsacStreamSwitching(1.7E12f, 1,
+                    R.raw.noise_1ch_29_4khz_aot42_19_lufs_drc_config_change_mp4, aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacStreamSwitchingM4a failed 1ch USAC mode switch for "
+                    + aacDecName);
+            throw new RuntimeException(e);
+        }
+
+    }
+
     /**
      * Verify the correct decoding of USAC bitstreams with various sampling rates.
      */
@@ -275,20 +292,28 @@
 
         for (String aacDecName : sAacDecoderNames) {
             try {
-                checkUsacSamplingRate(R.raw.noise_2ch_08khz_aot42_19_lufs_mp4, aacDecName);
-                checkUsacSamplingRate(R.raw.noise_2ch_12khz_aot42_19_lufs_mp4, aacDecName);
-                checkUsacSamplingRate(R.raw.noise_2ch_22_05khz_aot42_19_lufs_mp4, aacDecName);
-                checkUsacSamplingRate(R.raw.noise_2ch_64khz_aot42_19_lufs_mp4, aacDecName);
-                checkUsacSamplingRate(R.raw.noise_2ch_88_2khz_aot42_19_lufs_mp4, aacDecName);
-                checkUsacSamplingRateWoLoudness(R.raw.noise_2ch_19_2khz_aot42_no_ludt_mp4,
-                        aacDecName);
-            } catch (Exception e) {
-                Log.v(TAG, "testDecodeUsacSamplingRatesM4a for decoder" + aacDecName);
-                throw new RuntimeException(e);
+                runDecodeUsacSamplingRatesM4a(aacDecName);
+            } catch (Error err) {
+                throw new Error(err.getMessage() + " [dec=" + aacDecName + "]" , err);
             }
         }
     }
 
+    private void runDecodeUsacSamplingRatesM4a(String aacDecName) throws Exception {
+        try {
+            checkUsacSamplingRate(R.raw.noise_2ch_08khz_aot42_19_lufs_mp4, aacDecName);
+            checkUsacSamplingRate(R.raw.noise_2ch_12khz_aot42_19_lufs_mp4, aacDecName);
+            checkUsacSamplingRate(R.raw.noise_2ch_22_05khz_aot42_19_lufs_mp4, aacDecName);
+            checkUsacSamplingRate(R.raw.noise_2ch_64khz_aot42_19_lufs_mp4, aacDecName);
+            checkUsacSamplingRate(R.raw.noise_2ch_88_2khz_aot42_19_lufs_mp4, aacDecName);
+            checkUsacSamplingRateWoLoudness(R.raw.noise_2ch_19_2khz_aot42_no_ludt_mp4,
+                    aacDecName);
+        } catch (Exception e) {
+            Log.v(TAG, "testDecodeUsacSamplingRatesM4a for decoder" + aacDecName);
+            throw new RuntimeException(e);
+        }
+    }
+
 
     /**
      *  Internal utilities
@@ -440,7 +465,7 @@
     }
 
     /**
-     * Same as {@link #checkEnergyUSAC(short[], AudioParameter, int, int)} but with DRC effec type
+     * Same as {@link #checkEnergyUSAC(short[], AudioParameter, int, int)} but with DRC effect type
      * @param decSamples
      * @param decParams
      * @param encNch
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecTest.java b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
index db8cd6a..a4e3a19 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
@@ -978,6 +978,9 @@
             // re-configure, this time without an input surface
             if (VERBOSE) Log.d(TAG, "reconfiguring");
             encoder.stop();
+            // Use non-opaque color format for byte buffer mode.
+            format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+                    MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
             encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
             encoder.start();
             if (VERBOSE) Log.d(TAG, "reconfigured");
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java b/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
index a21c1ce..91a6acf 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
@@ -156,6 +156,7 @@
         boolean playedSuccessfully = false;
         for (int i = 0; i < STREAM_RETRIES; i++) {
           try {
+            mMediaPlayer.reset();
             mMediaPlayer.setDataSource(path);
             playLoadedVideo(width, height, playTime);
             playedSuccessfully = true;
@@ -188,6 +189,7 @@
         boolean playedSuccessfully = false;
         for (int i = 0; i < STREAM_RETRIES; i++) {
             try {
+                mMediaPlayer.reset();
                 mMediaPlayer.setDataSource(getInstrumentation().getTargetContext(),
                         uri, headers, cookies);
                 playLoadedVideo(width, height, playTime);
diff --git a/tests/tests/os/src/android/os/cts/SecurityPatchTest.java b/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
index da72966..7afeaa9 100644
--- a/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
+++ b/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
@@ -30,21 +30,13 @@
 
     private static final String TAG = SecurityPatchTest.class.getSimpleName();
     private static final String SECURITY_PATCH_ERROR =
-            "security_patch should be in the format \"YYYY-MM-DD\". Found \"%s\"";
-    private static final String SECURITY_PATCH_DATE_ERROR =
-            "security_patch should be \"%d-%02d\" or later. Found \"%s\"";
-    private static final int SECURITY_PATCH_YEAR = 2016;
-    private static final int SECURITY_PATCH_MONTH = 12;
+            "ro.build.version.security_patch should be in the format \"YYYY-MM-DD\". Found \"%s\"";
 
     private boolean mSkipTests = false;
-    private String mVendorSecurityPatch;
-    private String mBuildSecurityPatch;
 
     @Override
     protected void setUp() {
         mSkipTests = (ApiLevelUtil.isBefore(Build.VERSION_CODES.M));
-        mVendorSecurityPatch = SystemProperties.get("ro.vendor.build.security_patch", "");
-        mBuildSecurityPatch = Build.VERSION.SECURITY_PATCH;
     }
 
     /** Security patch string must exist in M or higher **/
@@ -53,85 +45,32 @@
             Log.w(TAG, "Skipping M+ Test.");
             return;
         }
-        String error = String.format(SECURITY_PATCH_ERROR, mBuildSecurityPatch);
-        assertTrue(error, !mBuildSecurityPatch.isEmpty());
-    }
 
-    public void testVendorSecurityPatchFound() {
-        if (Build.VERSION.FIRST_SDK_INT <= Build.VERSION_CODES.O) {
-            Log.w(TAG, "Skipping P+ Test");
-            return;
-        }
-        assertTrue(!mVendorSecurityPatch.isEmpty());
-    }
-
-    public void testSecurityPatchesFormat() {
-        if (mSkipTests) {
-            Log.w(TAG, "Skipping M+ Test.");
-            return;
-        }
-        String error = String.format(SECURITY_PATCH_ERROR, mBuildSecurityPatch);
-        testSecurityPatchFormat(mBuildSecurityPatch, error);
-
-        if (Build.VERSION.FIRST_SDK_INT <= Build.VERSION_CODES.O) {
-            Log.w(TAG, "Skipping P+ Test");
-            return;
-        }
-        error = String.format(SECURITY_PATCH_ERROR, mVendorSecurityPatch);
-        testSecurityPatchFormat(mVendorSecurityPatch, error);
+        String buildSecurityPatch = Build.VERSION.SECURITY_PATCH;
+        String error = String.format(SECURITY_PATCH_ERROR, buildSecurityPatch);
+        assertTrue(error, !buildSecurityPatch.isEmpty());
     }
 
     /** Security patch should be of the form YYYY-MM-DD in M or higher */
-    private void testSecurityPatchFormat(String patch, String error) {
-        assertEquals(error, 10, patch.length());
-        assertTrue(error, Character.isDigit(patch.charAt(0)));
-        assertTrue(error, Character.isDigit(patch.charAt(1)));
-        assertTrue(error, Character.isDigit(patch.charAt(2)));
-        assertTrue(error, Character.isDigit(patch.charAt(3)));
-        assertEquals(error, '-', patch.charAt(4));
-        assertTrue(error, Character.isDigit(patch.charAt(5)));
-        assertTrue(error, Character.isDigit(patch.charAt(6)));
-        assertEquals(error, '-', patch.charAt(7));
-        assertTrue(error, Character.isDigit(patch.charAt(8)));
-        assertTrue(error, Character.isDigit(patch.charAt(9)));
-    }
-
-    public void testSecurityPatchDates() {
+    public void testSecurityPatchFormat() {
         if (mSkipTests) {
             Log.w(TAG, "Skipping M+ Test.");
             return;
         }
 
-        String error = String.format(SECURITY_PATCH_DATE_ERROR,
-                                     SECURITY_PATCH_YEAR,
-                                     SECURITY_PATCH_MONTH,
-                                     mBuildSecurityPatch);
-        testSecurityPatchDate(mBuildSecurityPatch, error);
+        String buildSecurityPatch = Build.VERSION.SECURITY_PATCH;
+        String error = String.format(SECURITY_PATCH_ERROR, buildSecurityPatch);
 
-        if (Build.VERSION.FIRST_SDK_INT <= Build.VERSION_CODES.O) {
-            Log.w(TAG, "Skipping P+ Test");
-            return;
-        }
-        error = String.format(SECURITY_PATCH_DATE_ERROR,
-                                     SECURITY_PATCH_YEAR,
-                                     SECURITY_PATCH_MONTH,
-                                     mVendorSecurityPatch);
-        testSecurityPatchDate(mVendorSecurityPatch, error);
-    }
-    /** Security patch should no older than the month this test was updated in M or higher **/
-    private void testSecurityPatchDate(String patch, String error) {
-        int declaredYear = 0;
-        int declaredMonth = 0;
-
-        try {
-            declaredYear = Integer.parseInt(patch.substring(0,4));
-            declaredMonth = Integer.parseInt(patch.substring(5,7));
-        } catch (Exception e) {
-            assertTrue(error, false);
-        }
-
-        assertTrue(error, declaredYear >= SECURITY_PATCH_YEAR);
-        assertTrue(error, (declaredYear > SECURITY_PATCH_YEAR) ||
-                          (declaredMonth >= SECURITY_PATCH_MONTH));
+        assertEquals(error, 10, buildSecurityPatch.length());
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(0)));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(1)));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(2)));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(3)));
+        assertEquals(error, '-', buildSecurityPatch.charAt(4));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(5)));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(6)));
+        assertEquals(error, '-', buildSecurityPatch.charAt(7));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(8)));
+        assertTrue(error, Character.isDigit(buildSecurityPatch.charAt(9)));
     }
 }
diff --git a/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowPortraitTest.java b/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowPortraitTest.java
index 1caed6f..6b484bd 100644
--- a/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowPortraitTest.java
+++ b/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowPortraitTest.java
@@ -16,7 +16,11 @@
 
 package android.preference2.cts;
 
+import static android.content.pm.PackageManager.FEATURE_LEANBACK;
+import static org.junit.Assume.assumeFalse;
+
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.LargeTest;
 import android.support.test.rule.ActivityTestRule;
@@ -40,6 +44,9 @@
 
     @Before
     public void setup() {
+        PackageManager pm = InstrumentationRegistry.getTargetContext().getPackageManager();
+        // Ignore this test on Leanback since Leanback doesn't support portrait orientation
+        assumeFalse(pm.hasSystemFeature(FEATURE_LEANBACK));
         mTestUtils = new TestUtils();
     }
 
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java b/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
index 0748bfb..b54a5e5 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
@@ -257,7 +257,7 @@
         documents.mkdirs();
         assertTrue(documents.isDirectory());
 
-        mFile = new File(documents, "test.txt");
+        mFile = new File(documents, "test.jpg");
         try (OutputStream os = new FileOutputStream(mFile)) {
             os.write(CONTENT.getBytes());
         }
@@ -266,7 +266,7 @@
         MediaScannerConnection.scanFile(
                 mActivity,
                 new String[]{ mFile.getAbsolutePath() },
-                new String[]{ "plain/text" },
+                new String[]{ "image/jpeg" },
                 (String path, Uri uri) -> onScanCompleted(uri, latch)
         );
         assertTrue(
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 34b6411..438857d 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
@@ -83,10 +83,10 @@
             {(byte) 0x80, 0x08, 0x00, 0x00, 0x00},
             {(byte) 0xA0, 0x08, 0x00, 0x00, 0x00},
             {(byte) 0x94, 0x08, 0x00, 0x00, 0x00},
-            {0x00, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
-            {(byte) 0x80, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
-            {(byte) 0xA0, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
-            {(byte) 0x94, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00}
+            {0x00, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
+            {(byte) 0x80, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
+            {(byte) 0xA0, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
+            {(byte) 0x94, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00}
     };
 
     private final static byte[] CHECK_SELECT_P2_APDU = new byte[]{0x00, (byte) 0xF4, 0x00, 0x00};
diff --git a/tests/tests/security/res/raw/bug_110435401.mid b/tests/tests/security/res/raw/bug_110435401.mid
new file mode 100644
index 0000000..184ab1f
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_110435401.mid
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_65484460.mp4 b/tests/tests/security/res/raw/bug_65484460.mp4
new file mode 100644
index 0000000..13b37e9
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_65484460.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_68664359.mid b/tests/tests/security/res/raw/bug_68664359.mid
new file mode 100644
index 0000000..f816d82
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_68664359.mid
@@ -0,0 +1 @@
+DK:@~kkkkk
\ No newline at end of file
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index 4e128bc..dfe55f5 100755
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -827,6 +827,16 @@
      ***********************************************************/
 
     @SecurityTest
+    public void testStagefright_bug_68664359() throws Exception {
+        doStagefrightTest(R.raw.bug_68664359, 60000);
+    }
+
+    @SecurityTest
+    public void testStagefright_bug_110435401() throws Exception {
+        doStagefrightTest(R.raw.bug_110435401, 60000);
+    }
+
+    @SecurityTest
     public void testStagefright_cve_2017_0474() throws Exception {
         doStagefrightTest(R.raw.cve_2017_0474, 120000);
     }
@@ -919,6 +929,11 @@
         doStagefrightTest(R.raw.cve_2016_6699);
     }
 
+    @SecurityTest
+    public void testStagefright_bug_65484460() throws Exception {
+        doStagefrightTest(R.raw.bug_65484460);
+    }
+
     private void doStagefrightTest(final int rid) throws Exception {
         doStagefrightTestMediaPlayer(rid);
         doStagefrightTestMediaCodec(rid);
diff --git a/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/AndroidManifest.xml b/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/AndroidManifest.xml
index d2cc04a..cd30602 100755
--- a/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/AndroidManifest.xml
+++ b/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/AndroidManifest.xml
@@ -23,6 +23,14 @@
 
         <activity android:name="Launcher" android:enabled="true" android:exported="false">
         </activity>
+
+        <activity-alias android:name="HomeActivity"
+            android:targetActivity="Launcher">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity-alias>
     </application>
 </manifest>
 
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
index 904f0cf..f2b9fc4 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
@@ -129,6 +129,8 @@
         assertExpectException(NullPointerException.class, "action must be set",
                 () -> new ShortcutInfo.Builder(getTestContext(), "id").setIntent(new Intent()));
 
+        setCurrentCaller(getTestContext());
+
         assertExpectException(
                 IllegalArgumentException.class, "Short label must be provided", () -> {
                     ShortcutInfo si = new ShortcutInfo.Builder(getTestContext(), "id")
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerFakingPublisherTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerFakingPublisherTest.java
new file mode 100644
index 0000000..baa47b0
--- /dev/null
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerFakingPublisherTest.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2018 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.content.pm.cts.shortcutmanager;
+
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertExpectException;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.list;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.runCommand;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ShortcutInfo;
+import android.platform.test.annotations.SecurityTest;
+import android.support.test.InstrumentationRegistry;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import org.junit.Assume;
+
+/**
+ * CTS for b/109824443.
+ */
+@SmallTest
+@SecurityTest
+public class ShortcutManagerFakingPublisherTest extends ShortcutManagerCtsTestsBase {
+    private static final String ANOTHER_PACKAGE =
+            "android.content.pm.cts.shortcutmanager.packages.package4";
+
+    private static final ComponentName ANOTHER_HOME_ACTIVITY = new ComponentName(
+            ANOTHER_PACKAGE, "android.content.pm.cts.shortcutmanager.packages.HomeActivity");
+
+    private static final String INVALID_ID =
+            "[ShortcutManagerFakingPublisherTest.shortcut_that_should_not_be_created]";
+
+    @Override
+    protected String getOverrideConfig() {
+        return "reset_interval_sec=999999,"
+                + "max_updates_per_interval=999999,"
+                + "max_shortcuts=10"
+                + "max_icon_dimension_dp=96,"
+                + "max_icon_dimension_dp_lowram=96,"
+                + "icon_format=PNG,"
+                + "icon_quality=100";
+    }
+
+    public void testSpoofingPublisher() {
+        final Context myContext = getTestContext();
+        final Context anotherContext;
+        try {
+            anotherContext = getTestContext().createPackageContext(ANOTHER_PACKAGE, 0);
+        } catch (NameNotFoundException e) {
+            fail("Unable to create package context for " + ANOTHER_PACKAGE);
+            return;
+        }
+        final ShortcutInfo invalid = new ShortcutInfo.Builder(anotherContext, INVALID_ID)
+                .setShortLabel(INVALID_ID)
+                .setIntent(new Intent(Intent.ACTION_VIEW))
+                .setActivity(ANOTHER_HOME_ACTIVITY)
+                .build();
+
+        // Check set.
+        runWithCaller(mPackageContext1, () -> {
+            getManager().removeAllDynamicShortcuts();
+
+            assertShortcutPackageMismatch("setDynamicShortcuts1", mPackageContext1, () -> {
+                getManager().setDynamicShortcuts(list(
+                        invalid));
+            });
+            assertInvalidShortcutNotCreated();
+            assertShortcutPackageMismatch("setDynamicShortcuts2A", mPackageContext1, () -> {
+                getManager().setDynamicShortcuts(list(
+                        invalid,
+                        makeShortcut("s1", "title1")));
+            });
+            assertInvalidShortcutNotCreated();
+            assertShortcutPackageMismatch("setDynamicShortcuts2B", mPackageContext1, () -> {
+                getManager().setDynamicShortcuts(list(
+                        makeShortcut("s1", "title1"),
+                        invalid));
+            });
+            assertInvalidShortcutNotCreated();
+        });
+
+        // Check add.
+        runWithCaller(mPackageContext1, () -> {
+            getManager().removeAllDynamicShortcuts();
+
+            assertShortcutPackageMismatch("addDynamicShortcuts1", mPackageContext1, () -> {
+                getManager().addDynamicShortcuts(list(
+                        invalid));
+            });
+            assertInvalidShortcutNotCreated();
+            assertShortcutPackageMismatch("addDynamicShortcuts2A", mPackageContext1, () -> {
+                getManager().addDynamicShortcuts(list(
+                        invalid,
+                        makeShortcut("s1", "title1")));
+            });
+            assertInvalidShortcutNotCreated();
+            assertShortcutPackageMismatch("addDynamicShortcuts2B", mPackageContext1, () -> {
+                getManager().addDynamicShortcuts(list(
+                        makeShortcut("s1", "title1"),
+                        invalid));
+            });
+            assertInvalidShortcutNotCreated();
+        });
+
+        // Check update.
+        runWithCaller(mPackageContext1, () -> {
+            getManager().removeAllDynamicShortcuts();
+
+            assertShortcutPackageMismatch("updateShortcuts1", mPackageContext1, () -> {
+                getManager().updateShortcuts(list(
+                        invalid));
+            });
+            assertInvalidShortcutNotCreated();
+            assertShortcutPackageMismatch("updateShortcuts2A", mPackageContext1, () -> {
+                getManager().updateShortcuts(list(
+                        invalid,
+                        makeShortcut("s1", "title1")));
+            });
+            assertInvalidShortcutNotCreated();
+            assertShortcutPackageMismatch("updateShortcuts2B", mPackageContext1, () -> {
+                getManager().updateShortcuts(list(
+                        makeShortcut("s1", "title1"),
+                        invalid));
+            });
+            assertInvalidShortcutNotCreated();
+        });
+
+        // requestPin (API26 and above)
+        runWithCaller(mPackageContext1, () -> {
+            getManager().removeAllDynamicShortcuts();
+
+            assertShortcutPackageMismatch("requestPinShortcut", mPackageContext1, () -> {
+                getManager().requestPinShortcut(invalid, null);
+            });
+            assertInvalidShortcutNotCreated();
+        });
+
+        // createShortcutResultIntent (API26 and above)
+        runWithCaller(mPackageContext1, () -> {
+            getManager().removeAllDynamicShortcuts();
+
+            assertShortcutPackageMismatch("createShortcutResultIntent", mPackageContext1, () -> {
+                getManager().createShortcutResultIntent(invalid);
+            });
+            assertInvalidShortcutNotCreated();
+        });
+    }
+
+    private void assertInvalidShortcutNotCreated() {
+        for (String s : runCommand(InstrumentationRegistry.getInstrumentation(),
+                "dumpsys shortcut")) {
+            assertFalse("dumpsys shortcut contained invalid ID", s.contains(INVALID_ID));
+        }
+    }
+
+    private void assertShortcutPackageMismatch(String method, Context callerContext, Runnable r) {
+        assertExpectException(
+                "Caller=" + callerContext.getPackageName() + ", method=" + method,
+                SecurityException.class, "Shortcut package name mismatch",
+                () -> runWithCaller(callerContext, () -> r.run())
+        );
+    }
+}
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java
index cdb14d1..be9f10d 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerStartShortcutTest.java
@@ -24,6 +24,7 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.graphics.Rect;
 import android.os.Bundle;
 import android.test.suitebuilder.annotation.SmallTest;
@@ -36,12 +37,15 @@
 @SmallTest
 public class ShortcutManagerStartShortcutTest extends ShortcutManagerCtsTestsBase {
     private ComponentName mLaunchedActivity;
+    private boolean mOnWatch;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
 
         mLaunchedActivity = new ComponentName(getTestContext(), ShortcutLaunchedActivity.class);
+        mOnWatch = getTestContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_WATCH);
     }
 
     private List<Intent> launchShortcutAndGetIntents(Context launcher, Context client,
@@ -118,6 +122,9 @@
      * Start multiple activities.
      */
     public void testStartMultiple() {
+        if (mOnWatch) {
+            return; // b/109678268
+        }
         setDefaultLauncher(getInstrumentation(), mLauncherContext1);
 
         Intent i1 = new Intent("a1")
@@ -180,6 +187,9 @@
     }
 
     public void testShortcutNoLongerExists() {
+        if (mOnWatch) {
+            return; // b/109678268
+        }
 
         // Let it publish a shortcut.
         testStartMultiple();
@@ -215,6 +225,9 @@
     }
 
     public void testPinnedShortcut_sameLauncher() {
+        if (mOnWatch) {
+            return; // b/109678268
+        }
 
         // Let it publish a shortcut.
         testStartSingle();
@@ -237,6 +250,9 @@
     }
 
     public void testPinnedShortcut_differentLauncher() {
+        if (mOnWatch) {
+            return; // b/109678268
+        }
 
         // Let it publish a shortcut.
         testStartSingle();
@@ -285,6 +301,9 @@
     }
 
     public void testStartMultipleWithOptions() {
+        if (mOnWatch) {
+            return; // b/109678268
+        }
         testStartMultiple();
 
         List<Intent> launched = launchShortcutAndGetIntents(mLauncherContext1, mPackageContext1,
@@ -302,6 +321,9 @@
     }
 
     public void testNonExistent() {
+        if (mOnWatch) {
+            return; // b/109678268
+        }
         setDefaultLauncher(getInstrumentation(), mLauncherContext1);
 
         Intent i = new Intent(Intent.ACTION_MAIN)
diff --git a/tests/tests/simpleperf/Android.mk b/tests/tests/simpleperf/Android.mk
index 164c14d..d611bd3 100644
--- a/tests/tests/simpleperf/Android.mk
+++ b/tests/tests/simpleperf/Android.mk
@@ -36,7 +36,6 @@
   libLLVMSupport \
   libprotobuf-cpp-lite \
   libevent \
-  libc \
 
 LOCAL_POST_LINK_CMD =  \
   TMP_FILE=`mktemp $(OUT_DIR)/simpleperf-post-link-XXXXXXXXXX` && \
@@ -47,7 +46,6 @@
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CTS_TEST_PACKAGE := android.simpleperf
-LOCAL_FORCE_STATIC_EXECUTABLE := true
 include $(LLVM_DEVICE_BUILD_MK)
 include $(BUILD_CTS_EXECUTABLE)
 
diff --git a/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java b/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
index 76df59c..e434eba 100644
--- a/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
@@ -326,13 +326,13 @@
 
     private void setRttMasterSwitch(boolean on) throws Exception {
         TestUtils.executeShellCommand(getInstrumentation(),
-                "settings put system rtt_calling_mode " + (on ? 1 : 0));
+                "settings put system secure rtt_calling_mode " + (on ? 1 : 0));
     }
 
     private boolean getRttMasterSwitch() throws Exception {
         try {
             return Integer.valueOf(TestUtils.executeShellCommand(
-                    getInstrumentation(), "settings get system rtt_calling_mode")) == 1;
+                    getInstrumentation(), "settings get secure rtt_calling_mode")) == 1;
         } catch (NumberFormatException e) {
             // If the setting hasn't been set yet, assume it's off
             return false;
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/ColorCountVerifier.java b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/ColorCountVerifier.java
index 1cf71c5..03f6412 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/ColorCountVerifier.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/ColorCountVerifier.java
@@ -15,15 +15,22 @@
  */
 package android.uirendering.cts.bitmapverifiers;
 
+import android.uirendering.cts.util.CompareUtils;
 import android.util.Log;
 
 public class ColorCountVerifier extends BitmapVerifier {
     private int mColor;
     private int mCount;
+    private int mThreshold;
 
-    public ColorCountVerifier(int color, int count) {
+    public ColorCountVerifier(int color, int count, int threshold) {
         mColor = color;
         mCount = count;
+        mThreshold = threshold;
+    }
+
+    public ColorCountVerifier(int color, int count) {
+        this(color, count, 0);
     }
 
     @Override
@@ -31,7 +38,8 @@
         int count = 0;
         for (int x = 0; x < width; x++) {
             for (int y = 0; y < height; y++) {
-                if (bitmap[indexFromXAndY(x, y, stride, offset)] == mColor) {
+                if (CompareUtils.verifyPixelWithThreshold(
+                        bitmap[indexFromXAndY(x, y, stride, offset)], mColor, mThreshold)) {
                     count++;
                 }
             }
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
index c9e0e42..b4c7798 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
@@ -227,7 +227,8 @@
 
         createTest()
                 .addLayout(R.layout.frame_layout, initializer, true)
-                .runWithAnimationVerifier(new ColorCountVerifier(Color.WHITE, 90 * 90 - 50 * 50));
+                .runWithAnimationVerifier(new ColorCountVerifier(
+                        Color.WHITE, 90 * 90 - 50 * 50, 10));
     }
 
     @Test
diff --git a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
index 01fcccd..f9103e6 100644
--- a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
@@ -34,6 +34,7 @@
 import android.content.pm.ActivityInfo;
 import android.content.res.Configuration;
 import android.graphics.Color;
+import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
@@ -56,6 +57,7 @@
 import android.view.View.OnTouchListener;
 import android.view.ViewGroup;
 import android.view.ViewGroup.LayoutParams;
+import android.view.WindowInsets;
 import android.view.WindowManager;
 import android.widget.ImageView;
 import android.widget.PopupWindow;
@@ -630,7 +632,6 @@
     public void testShowAtLocation() throws Throwable {
         int[] popupContentViewInWindowXY = new int[2];
         int[] popupContentViewOnScreenXY = new int[2];
-        Rect containingRect = new Rect();
 
         mPopupWindow = createPopupWindow(createPopupContent(CONTENT_SIZE_DP, CONTENT_SIZE_DP));
         // Do not attach within the decor; we will be measuring location
@@ -639,9 +640,9 @@
         assertFalse(mPopupWindow.isAttachedInDecor());
 
         final View upperAnchor = mActivity.findViewById(R.id.anchor_upper);
-
-        final int xOff = 10;
-        final int yOff = 21;
+        final WindowInsets windowInsets = upperAnchor.getRootWindowInsets();
+        final int xOff = windowInsets.getSystemWindowInsetLeft() + 10;
+        final int yOff = windowInsets.getSystemWindowInsetTop() + 21;
         assertFalse(mPopupWindow.isShowing());
         mPopupWindow.getContentView().getLocationInWindow(popupContentViewInWindowXY);
         assertEquals(0, popupContentViewInWindowXY[0]);
@@ -654,14 +655,11 @@
         assertTrue(mPopupWindow.isShowing());
         mPopupWindow.getContentView().getLocationInWindow(popupContentViewInWindowXY);
         mPopupWindow.getContentView().getLocationOnScreen(popupContentViewOnScreenXY);
-        upperAnchor.getWindowDisplayFrame(containingRect);
 
         assertTrue(popupContentViewInWindowXY[0] >= 0);
         assertTrue(popupContentViewInWindowXY[1] >= 0);
-        assertEquals(containingRect.left + popupContentViewInWindowXY[0] + xOff,
-                popupContentViewOnScreenXY[0]);
-        assertEquals(containingRect.top + popupContentViewInWindowXY[1] + yOff,
-                popupContentViewOnScreenXY[1]);
+        assertEquals(popupContentViewInWindowXY[0] + xOff, popupContentViewOnScreenXY[0]);
+        assertEquals(popupContentViewInWindowXY[1] + yOff, popupContentViewOnScreenXY[1]);
 
         dismissPopup();
     }
@@ -942,7 +940,7 @@
         int[] fstXY = new int[2];
         int[] sndXY = new int[2];
         int[] viewInWindowXY = new int[2];
-        Rect containingRect = new Rect();
+        final Point popupPos = new Point();
 
         mActivityRule.runOnUiThread(() -> {
             mPopupWindow = createPopupWindow(createPopupContent(CONTENT_SIZE_DP, CONTENT_SIZE_DP));
@@ -961,7 +959,6 @@
         showPopup();
         mPopupWindow.getContentView().getLocationInWindow(viewInWindowXY);
         final View containerView = mActivity.findViewById(R.id.main_container);
-        containerView.getWindowDisplayFrame(containingRect);
 
         // update if it is not shown
         mActivityRule.runOnUiThread(() -> mPopupWindow.update(80, 80));
@@ -971,8 +968,11 @@
         assertEquals(80, mPopupWindow.getWidth());
         assertEquals(80, mPopupWindow.getHeight());
 
+        final WindowInsets windowInsets = containerView.getRootWindowInsets();
+        popupPos.set(windowInsets.getStableInsetLeft() + 20, windowInsets.getStableInsetTop() + 50);
+
         // update if it is not shown
-        mActivityRule.runOnUiThread(() -> mPopupWindow.update(20, 50, 50, 50));
+        mActivityRule.runOnUiThread(() -> mPopupWindow.update(popupPos.x, popupPos.y, 50, 50));
 
         mInstrumentation.waitForIdleSync();
         assertTrue(mPopupWindow.isShowing());
@@ -980,11 +980,14 @@
         assertEquals(50, mPopupWindow.getHeight());
 
         mPopupWindow.getContentView().getLocationOnScreen(fstXY);
-        assertEquals(containingRect.left + viewInWindowXY[0] + 20, fstXY[0]);
-        assertEquals(containingRect.top + viewInWindowXY[1] + 50, fstXY[1]);
+        assertEquals(popupPos.x + viewInWindowXY[0], fstXY[0]);
+        assertEquals(popupPos.y + viewInWindowXY[1], fstXY[1]);
+
+        popupPos.set(windowInsets.getStableInsetLeft() + 4, windowInsets.getStableInsetTop());
 
         // ignore if width or height is -1
-        mActivityRule.runOnUiThread(() -> mPopupWindow.update(4, 0, -1, -1, true));
+        mActivityRule.runOnUiThread(
+                () -> mPopupWindow.update(popupPos.x, popupPos.y, -1, -1, true));
         mInstrumentation.waitForIdleSync();
 
         assertTrue(mPopupWindow.isShowing());
@@ -992,8 +995,8 @@
         assertEquals(50, mPopupWindow.getHeight());
 
         mPopupWindow.getContentView().getLocationOnScreen(sndXY);
-        assertEquals(containingRect.left + viewInWindowXY[0] + 4, sndXY[0]);
-        assertEquals(containingRect.top + viewInWindowXY[1], sndXY[1]);
+        assertEquals(popupPos.x + viewInWindowXY[0], sndXY[0]);
+        assertEquals(popupPos.y + viewInWindowXY[1], sndXY[1]);
 
         dismissPopup();
     }