Merge "Fix testConfigTtl CTS case" into rvc-dev
diff --git a/apps/CameraITS/build/scripts/gpylint_rcfile b/apps/CameraITS/build/scripts/gpylint_rcfile
index f92c613..b9c16f4 100644
--- a/apps/CameraITS/build/scripts/gpylint_rcfile
+++ b/apps/CameraITS/build/scripts/gpylint_rcfile
@@ -318,7 +318,7 @@
 
 [MASTER]
 
-# Add files or directories to the blacklist. They should be base names, not
+# Add files or directories to the ignorelist. They should be base names, not
 # paths.
 ignore=CVS
 
diff --git a/apps/CameraITS/tests/scene3/test_flip_mirror.py b/apps/CameraITS/tests/scene3/test_flip_mirror.py
index b4677c7..0a90712 100644
--- a/apps/CameraITS/tests/scene3/test_flip_mirror.py
+++ b/apps/CameraITS/tests/scene3/test_flip_mirror.py
@@ -64,7 +64,7 @@
     patch = 255 * its.cv2image.gray_scale_img(patch)
     patch = its.cv2image.scale_img(patch.astype(np.uint8), chart.scale)
 
-    # sanity check on image
+    # validity check on image
     assert np.max(patch)-np.min(patch) > 255/8
 
     # save full images if in debug
diff --git a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
index e54fdb5..14e381c 100644
--- a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
+++ b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
@@ -319,7 +319,7 @@
         # 3. Child"s width > 0.1*Image width
         # 4. Child"s height > 0.1*Image height
         # 5. 0.25*Parent"s area < Child"s area < 0.45*Parent"s area
-        # 6. Child is a black, and Parent is white
+        # 6. Child == 0, and Parent == 255
         # 7. Center of Child and center of parent should overlap
         if (prt_shape["width"] * 0.56 < child_shape["width"]
                     < prt_shape["width"] * 0.76
diff --git a/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py b/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
index 649fc2a..2d08267 100644
--- a/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
+++ b/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
@@ -282,7 +282,7 @@
         # 3. Child's width > 0.1*Image width
         # 4. Child's height > 0.1*Image height
         # 5. 0.25*Parent's area < Child's area < 0.45*Parent's area
-        # 6. Child is a black, and Parent is white
+        # 6. Child == 0, and Parent == 255
         # 7. Center of Child and center of parent should overlap
         if (prt_shape['width'] * 0.56 < child_shape['width']
                     < prt_shape['width'] * 0.76
@@ -360,7 +360,7 @@
     world coordinates.
 
     Reproject the world coordinates back to pixel coordinates and compare
-    against originals as a sanity check.
+    against originals as a validity check.
 
     Compare the circle sizes if the focal lengths of the cameras are
     different using
@@ -583,7 +583,7 @@
                     circle[i]['x'], circle[i]['y'], r[i], t[i], k[i],
                     chart_distance)
 
-        # Back convert to image coordinates for sanity check
+        # Back convert to image coordinates for round-trip check
         x_p = {}
         y_p = {}
         x_p[i_2nd], y_p[i_2nd] = convert_to_image_coordinates(
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index 9292f6a3..f1b1d36 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -128,7 +128,7 @@
     else:
         events, frames, _, h = load_data()
 
-    # Sanity check camera timestamps are enclosed by sensor timestamps
+    # Check that camera timestamps are enclosed by sensor timestamps
     # This will catch bugs where camera and gyro timestamps go completely out
     # of sync
     cam_times = get_cam_times(events["cam"])
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index b6579a8..36e6b71 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -30,7 +30,7 @@
 import its.image
 import rotation_rig as rot
 
-# For sanity checking the installed APK's target SDK version
+# For checking the installed APK's target SDK version
 MIN_SUPPORTED_SDK_VERSION = 28  # P
 
 CHART_DELAY = 1  # seconds
@@ -429,7 +429,7 @@
     device_id_arg = "device=" + device_id
     print "Testing device " + device_id
 
-    # Sanity check CtsVerifier SDK level
+    # Check CtsVerifier SDK level
     # Here we only do warning as there is no guarantee on pm dump output formt not changed
     # Also sometimes it's intentional to run mismatched versions
     cmd = "adb -s %s shell pm dump com.android.cts.verifier" % (device_id)
@@ -473,7 +473,7 @@
     with ItsSession() as cam:
         cam.check_its_version_compatible()
 
-    # Sanity Check for devices
+    # Correctness check for devices
     device_bfp = its.device.get_device_fingerprint(device_id)
     assert device_bfp is not None
 
diff --git a/hostsidetests/apex/src/android/apex/cts/ApexTest.java b/hostsidetests/apex/src/android/apex/cts/ApexTest.java
index 081da9b..c2ca8bc 100644
--- a/hostsidetests/apex/src/android/apex/cts/ApexTest.java
+++ b/hostsidetests/apex/src/android/apex/cts/ApexTest.java
@@ -41,7 +41,9 @@
       || systemProduct.equals("aosp_arm_ab") // _ab for Legacy GSI
       || systemProduct.equals("aosp_arm64_ab")
       || systemProduct.equals("aosp_x86_ab")
-      || systemProduct.equals("aosp_x86_64_ab");
+      || systemProduct.equals("aosp_x86_64_ab")
+      || systemProduct.equals("aosp_tv_arm")
+      || systemProduct.equals("aosp_tv_arm64");
   }
 
   /**
diff --git a/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java b/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java
index 3e7c1da..2f4164f 100644
--- a/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/MultiUserBackupStateTest.java
@@ -23,6 +23,8 @@
 import com.android.compatibility.common.util.CommonTestUtils;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
+import com.android.tradefed.log.LogUtil.CLog;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -40,6 +42,12 @@
 
     private Optional<Integer> mProfileUserId = Optional.empty();
 
+    /**
+     * User ID for the system user.
+     * The value is from the UserHandle class.
+     */
+    protected static final int USER_SYSTEM = 0;
+
     /** Create the profile and start it. */
     @Before
     @Override
@@ -79,11 +87,21 @@
 
         assertTrue(mBackupUtils.isBackupActivatedForUser(profileUserId));
 
-        assertTrue(getDevice().removeUser(profileUserId));
+        removeUser(profileUserId);
         mProfileUserId = Optional.empty();
 
         CommonTestUtils.waitUntil("wait for backup to be deactivated for removed user",
                 BACKUP_DEACTIVATION_TIMEOUT_SECONDS,
                 () -> !mBackupUtils.isBackupActivatedForUser(profileUserId));
     }
+
+    private void removeUser(int userId) throws Exception  {
+        if (getDevice().listUsers().contains(userId) && userId != USER_SYSTEM) {
+            // Don't log output, as tests sometimes set no debug user restriction, which
+            // causes this to fail, we should still continue and remove the user.
+            CLog.d("Stopping and removing user " + userId);
+            getDevice().stopUser(userId, true, true);
+            assertTrue("Couldn't remove user", getDevice().removeUser(userId));
+        }
+    }
 }
diff --git a/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java b/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java
index 2144def..8dfe7b7 100644
--- a/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java
+++ b/hostsidetests/scopedstorage/ScopedStorageTestHelper/src/android/scopedstorage/cts/ScopedStorageTestHelper.java
@@ -29,11 +29,10 @@
 import static android.scopedstorage.cts.lib.TestUtils.READDIR_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.SETATTR_QUERY;
 import static android.scopedstorage.cts.lib.TestUtils.canOpen;
-import static android.scopedstorage.cts.lib.TestUtils.getMediaContentUri;
+import static android.scopedstorage.cts.lib.TestUtils.getImageContentUri;
 
 import android.app.Activity;
 import android.content.Intent;
-import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.os.Bundle;
 import android.provider.MediaStore;
@@ -146,7 +145,7 @@
             values.put(MediaStore.Images.Media.RELATIVE_PATH, relativePath);
             values.put(MediaStore.Images.Media.DISPLAY_NAME, name);
 
-            getContentResolver().insert(getMediaContentUri(), values);
+            getContentResolver().insert(getImageContentUri(), values);
 
             final Intent intent = new Intent(queryType);
             intent.putExtra(queryType, true);
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
index cfb30a3..8729f9b 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
@@ -194,4 +194,9 @@
     public void testLegacyAppUpdatingOwnershipOfExistingEntry() throws Exception {
         runDeviceTest("testLegacyAppUpdatingOwnershipOfExistingEntry");
     }
+
+    @Test
+    public void testInsertWithUnsupportedMimeType() throws Exception {
+        runDeviceTest("testInsertWithUnsupportedMimeType");
+    }
 }
diff --git a/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java b/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
index f700391..2422f3b 100644
--- a/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
+++ b/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
@@ -33,9 +33,11 @@
 import static android.scopedstorage.cts.lib.TestUtils.getContentResolver;
 import static android.scopedstorage.cts.lib.TestUtils.getFileOwnerPackageFromDatabase;
 import static android.scopedstorage.cts.lib.TestUtils.getFileRowIdFromDatabase;
+import static android.scopedstorage.cts.lib.TestUtils.getImageContentUri;
 import static android.scopedstorage.cts.lib.TestUtils.installApp;
 import static android.scopedstorage.cts.lib.TestUtils.listAs;
 import static android.scopedstorage.cts.lib.TestUtils.openFileAs;
+import static android.scopedstorage.cts.lib.TestUtils.openWithMediaProvider;
 import static android.scopedstorage.cts.lib.TestUtils.pollForExternalStorageState;
 import static android.scopedstorage.cts.lib.TestUtils.pollForPermission;
 import static android.scopedstorage.cts.lib.TestUtils.setupDefaultDirectories;
@@ -55,11 +57,15 @@
 import android.content.ContentValues;
 import android.database.Cursor;
 import android.net.Uri;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.ParcelFileDescriptor;
 import android.provider.MediaStore;
 import android.scopedstorage.cts.lib.TestUtils;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.OsConstants;
+import android.text.TextUtils;
 import android.util.Log;
 
 import androidx.test.InstrumentationRegistry;
@@ -78,6 +84,7 @@
 import java.io.FileDescriptor;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
 
@@ -700,6 +707,57 @@
         }
     }
 
+    /**
+     * b/156717256,b/156336269: Test that MediaProvider doesn't throw error on usage of unsupported
+     * or empty/null MIME type.
+     */
+    @Test
+    public void testInsertWithUnsupportedMimeType() throws Exception {
+        pollForPermission(Manifest.permission.READ_EXTERNAL_STORAGE, /*granted*/ true);
+        pollForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, /*granted*/ true);
+
+        final String IMAGE_FILE_DISPLAY_NAME = "LegacyStorageTest_file_" + NONCE;
+        final File imageFile = new File(TestUtils.getDcimDir(), IMAGE_FILE_DISPLAY_NAME + ".jpg");
+
+        for (String mimeType : new String[] {
+            "image/*", "", null, "foo/bar"
+        }) {
+            Uri uri = null;
+            try {
+                ContentValues values = new ContentValues();
+                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
+                if (TextUtils.isEmpty(mimeType)) {
+                    values.put(MediaStore.MediaColumns.DISPLAY_NAME, imageFile.getName());
+                } else {
+                    values.put(MediaStore.MediaColumns.DISPLAY_NAME, IMAGE_FILE_DISPLAY_NAME);
+                }
+                values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
+
+                uri = getContentResolver().insert(getImageContentUri(), values, Bundle.EMPTY);
+                assertNotNull(uri);
+
+                try (final OutputStream fos = getContentResolver().openOutputStream(uri, "rw")) {
+                    fos.write(BYTES_DATA1);
+                }
+
+                // Closing the file should trigger a scan, we still scan again to ensure MIME type
+                // is extracted from file extension
+                assertNotNull(MediaStore.scanFile(getContentResolver(), imageFile));
+
+                final String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME,
+                        MediaStore.MediaColumns.MIME_TYPE};
+                try (Cursor c = getContentResolver().query(uri, projection, null, null, null)) {
+                    assertTrue(c.moveToFirst());
+                    assertEquals(c.getCount(), 1);
+                    assertEquals(c.getString(0), imageFile.getName());
+                    assertTrue("image/jpeg".equalsIgnoreCase(c.getString(1)));
+                }
+            } finally {
+                deleteWithMediaProviderNoThrow(uri);
+            }
+        }
+    }
+
     private static void assertCanCreateFile(File file) throws IOException {
         if (file.exists()) {
             file.delete();
diff --git a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
index f17cbbe..34fbe79 100644
--- a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
+++ b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
@@ -374,7 +374,7 @@
     /**
      * Returns the content URI for images based on the current storage volume.
      */
-    public static Uri getMediaContentUri() {
+    public static Uri getImageContentUri() {
         return MediaStore.Images.Media.getContentUri(sStorageVolumeName);
     }
 
diff --git a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
index a7922db..93064e6 100644
--- a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
@@ -331,6 +331,15 @@
     }
 
     @Test
+    public void testStageAnotherSessionImmediatelyAfterAbandonMultiPackage() throws Exception {
+        assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+        int sessionId = stageMultipleApks(TestApp.Apex2, TestApp.A1, TestApp.B1)
+                .assertSuccessful().getSessionId();
+        abandonSession(sessionId);
+        stageSingleApk(TestApp.Apex2).assertSuccessful();
+    }
+
+    @Test
     public void testNoSessionUpdatedBroadcastSentForStagedSessionAbandon() throws Exception {
         assertThat(getInstalledVersion(TestApp.A)).isEqualTo(-1);
         assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(1);
diff --git a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
index 3345f62..427dbcc 100644
--- a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
@@ -138,6 +138,12 @@
     }
 
     @Test
+    public void testStageAnotherSessionImmediatelyAfterAbandonMultiPackage() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+        runPhase("testStageAnotherSessionImmediatelyAfterAbandonMultiPackage");
+    }
+
+    @Test
     public void testNoSessionUpdatedBroadcastSentForStagedSessionAbandon() throws Exception {
         assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
         runPhase("testNoSessionUpdatedBroadcastSentForStagedSessionAbandon");
diff --git a/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java b/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
index c478bf2..3826a4d 100644
--- a/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
+++ b/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
@@ -85,12 +85,16 @@
 
     private static final long TIMEOUT_BIND_SERVICE_SEC = 2;
 
+    private static final long TIMEOUT_WAIT_FOR_IDLE_MS = 2_000;
+
     // TODO: Make it a @TestApi or move the test using this to a different location.
     // Copy of DeviceConfig.NAMESPACE_BLOBSTORE constant
     private static final String NAMESPACE_BLOBSTORE = "blobstore";
     private static final String KEY_SESSION_EXPIRY_TIMEOUT_MS = "session_expiry_timeout_ms";
     private static final String KEY_LEASE_ACQUISITION_WAIT_DURATION_MS =
             "lease_acquisition_wait_time_ms";
+    private static final String KEY_DELETE_ON_LAST_LEASE_DELAY_MS =
+            "delete_on_last_lease_delay_ms";
     private static final String KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR =
             "total_bytes_per_app_limit_floor";
     public static final String KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION =
@@ -875,7 +879,7 @@
     }
 
     @Test
-    public void testAcquireRelease_deleteImmediately() throws Exception {
+    public void testAcquireRelease_deleteAfterDelay() throws Exception {
         final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
         blobData.prepare();
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(1);
@@ -892,6 +896,10 @@
                 releaseLease(mContext, blobData.getBlobHandle());
                 assertNoLeasedBlobs(mBlobStoreManager);
 
+                SystemClock.sleep(waitDurationMs);
+                SystemUtil.runWithShellPermissionIdentity(() ->
+                        mBlobStoreManager.waitForIdle(TIMEOUT_WAIT_FOR_IDLE_MS));
+
                 assertThrows(SecurityException.class, () -> mBlobStoreManager.acquireLease(
                         blobData.getBlobHandle(), R.string.test_desc,
                         blobData.getExpiryTimeMillis()));
@@ -899,7 +907,8 @@
             } finally {
                 blobData.delete();
             }
-        }, Pair.create(KEY_LEASE_ACQUISITION_WAIT_DURATION_MS, String.valueOf(waitDurationMs)));
+        }, Pair.create(KEY_LEASE_ACQUISITION_WAIT_DURATION_MS, String.valueOf(waitDurationMs)),
+                Pair.create(KEY_DELETE_ON_LAST_LEASE_DELAY_MS, String.valueOf(waitDurationMs)));
     }
 
     @Test
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java
index 3551205..e75d109 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/IdleConstraintTest.java
@@ -168,7 +168,8 @@
     private boolean isCarModeSupported() {
         // TVs don't support car mode.
         return !getContext().getPackageManager().hasSystemFeature(
-                PackageManager.FEATURE_LEANBACK_ONLY);
+                PackageManager.FEATURE_LEANBACK_ONLY)
+                && !getContext().getSystemService(UiModeManager.class).isUiModeLocked();
     }
 
     /**
@@ -305,7 +306,6 @@
         if (!isCarModeSupported()) {
             return;
         }
-
         runIdleJobStartsOnlyWhenIdle();
 
         setCarMode(true);
@@ -314,6 +314,9 @@
     }
 
     public void testIdleJobStartsOnlyWhenIdle_screenEndsIdle() throws Exception {
+        if (!isCarModeSupported()) {
+            return;
+        }
         runIdleJobStartsOnlyWhenIdle();
 
         toggleScreenOn(true);
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
index c065b1e..e013454 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
@@ -24,6 +24,7 @@
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import android.app.AppOpsManager;
@@ -102,6 +103,7 @@
     private boolean mInitialAirplaneModeState;
     private String mInitialJobSchedulerConstants;
     private String mInitialDisplayTimeout;
+    private boolean mAutomotiveDevice;
 
     private TestAppInterface mTestAppInterface;
 
@@ -162,6 +164,15 @@
         mInitialDisplayTimeout =
                 Settings.System.getString(mContext.getContentResolver(), SCREEN_OFF_TIMEOUT);
         Settings.System.putString(mContext.getContentResolver(), SCREEN_OFF_TIMEOUT, "300000");
+
+        // In automotive device, always-on screen and endless battery charging are assumed.
+        mAutomotiveDevice =
+                mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
+        if (mAutomotiveDevice) {
+            setScreenState(true);
+            // TODO(b/159176758): make sure that initial power supply is on.
+            BatteryUtils.runDumpsysBatterySetPluggedIn(true);
+        }
     }
 
     @Test
@@ -281,6 +292,7 @@
     @Test
     public void testJobsInRestrictedBucket_ParoleSession() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
 
         // Disable coalescing
         Settings.Global.putString(mContext.getContentResolver(),
@@ -304,6 +316,7 @@
     @Test
     public void testJobsInRestrictedBucket_NoRequiredNetwork() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
 
         // Disable coalescing and the parole session
         Settings.Global.putString(mContext.getContentResolver(),
@@ -339,6 +352,7 @@
     @Test
     public void testJobsInRestrictedBucket_WithRequiredNetwork() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         assumeTrue(mHasWifi);
         ensureSavedWifiNetwork(mWifiManager);
 
@@ -386,6 +400,7 @@
     @Test
     public void testJobsInNeverApp() throws Exception {
         assumeTrue("app standby not enabled", mAppStandbyEnabled);
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
 
         BatteryUtils.runDumpsysBatteryUnplug();
         setTestPackageStandbyBucket(Bucket.NEVER);
@@ -396,6 +411,8 @@
 
     @Test
     public void testUidActiveBypassesStandby() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
+
         BatteryUtils.runDumpsysBatteryUnplug();
         setTestPackageStandbyBucket(Bucket.NEVER);
         tempWhitelistTestApp(6_000);
@@ -407,6 +424,7 @@
 
     @Test
     public void testBatterySaverOff() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         BatteryUtils.runDumpsysBatteryUnplug();
@@ -418,6 +436,7 @@
 
     @Test
     public void testBatterySaverOn() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         BatteryUtils.runDumpsysBatteryUnplug();
@@ -429,6 +448,7 @@
 
     @Test
     public void testUidActiveBypassesBatterySaverOn() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         BatteryUtils.runDumpsysBatteryUnplug();
@@ -441,6 +461,7 @@
 
     @Test
     public void testBatterySaverOnThenUidActive() throws Exception {
+        assumeFalse("not testable in automotive device", mAutomotiveDevice);
         BatteryUtils.assumeBatterySaverFeature();
 
         // Enable battery saver, and schedule a job. It shouldn't run.
diff --git a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
index 776879d..a3e6256 100644
--- a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
@@ -431,7 +431,7 @@
         int width = size.getWidth();
         int height = size.getHeight();
         /**
-         * Check the input allocation is sane.
+         * Check the input allocation is valid.
          * - Byte size matches what we expect.
          * - The input is not all zeroes.
          */
diff --git a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
index 4a4aa0d..90a7dcd 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
@@ -2361,7 +2361,7 @@
                         result.get(CaptureResult.TONEMAP_PRESET_CURVE));
             }
 
-            // Tonemap curve result availability and basic sanity check for all modes.
+            // Tonemap curve result availability and basic validity check for all modes.
             mCollector.expectValuesInRange("Tonemap curve red values are out of range",
                     CameraTestUtils.toObject(mapRed), /*min*/ZERO, /*max*/ONE);
             mCollector.expectInRange("Tonemap curve red length is out of range",
@@ -2999,8 +2999,9 @@
      */
     private void changeExposure(CaptureRequest.Builder requestBuilder,
             long expTime, int sensitivity) {
-        // Check if the max analog sensitivity is available and no larger than max sensitivity.
-        // The max analog sensitivity is not actually used here. This is only an extra sanity check.
+        // Check if the max analog sensitivity is available and no larger than max sensitivity.  The
+        // max analog sensitivity is not actually used here. This is only an extra correctness
+        // check.
         mStaticInfo.getMaxAnalogSensitivityChecked();
 
         expTime = mStaticInfo.getExposureClampToRange(expTime);
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index 07155ff..7bf1f4c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -2084,7 +2084,7 @@
     }
 
     /**
-     * Sanity check of optical black regions.
+     * Correctness check of optical black regions.
      */
     @Test
     public void testOpticalBlackRegions() {
diff --git a/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java b/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
index 99c6b33..6cfa435 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
@@ -187,7 +187,7 @@
         texture.setDefaultBufferSize(640, 480);
         Surface surface = new Surface(texture);
 
-        // Make sure that the default newInstance is still sane.
+        // Make sure that the default newInstance is still valid.
         ImageWriter defaultWriter = ImageWriter.newInstance(surface, MAX_NUM_IMAGES);
         Image defaultImage = defaultWriter.dequeueInputImage();
         defaultWriter.close();
diff --git a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
index 067104c..bf42ab7 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
@@ -2046,7 +2046,7 @@
     }
 
     /**
-     * Validate video snapshot capture image object sanity and test.
+     * Validate video snapshot capture image object validity and test.
      *
      * <p> Check for size, format and jpeg decoding</p>
      *
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index 80a2fe95..0a24671 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -1829,7 +1829,7 @@
                 { LEGACY_COMBINATIONS, LIMITED_COMBINATIONS, BURST_COMBINATIONS, FULL_COMBINATIONS,
                   RAW_COMBINATIONS, LEVEL_3_COMBINATIONS };
 
-        sanityCheckConfigurationTables(TABLES);
+        validityCheckConfigurationTables(TABLES);
 
         for (String id : mCameraIdsUnderTest) {
             openDevice(id);
@@ -1965,7 +1965,7 @@
         final int[][][] TABLES =
                 { LIMITED_COMBINATIONS, FULL_COMBINATIONS, RAW_COMBINATIONS, LEVEL_3_COMBINATIONS };
 
-        sanityCheckConfigurationTables(TABLES);
+        validityCheckConfigurationTables(TABLES);
 
         for (String id : mCameraIdsUnderTest) {
             openDevice(id);
@@ -2091,9 +2091,9 @@
     }
 
     /**
-     * Sanity check the configuration tables.
+     * Verify correctness of the configuration tables.
      */
-    private void sanityCheckConfigurationTables(final int[][][] tables) throws Exception {
+    private void validityCheckConfigurationTables(final int[][][] tables) throws Exception {
         int tableIdx = 0;
         for (int[][] table : tables) {
             int rowIdx = 0;
diff --git a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
index 991649e..5f2f961 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -1564,9 +1564,9 @@
     }
 
     /**
-     * Validate JPEG capture image object sanity and test.
+     * Validate JPEG capture image object correctness and test.
      * <p>
-     * In addition to image object sanity, this function also does the decoding
+     * In addition to image object correctness, this function also does the decoding
      * test, which is slower.
      * </p>
      *
diff --git a/tests/camera/src/android/hardware/cts/CameraTest.java b/tests/camera/src/android/hardware/cts/CameraTest.java
index e7b36f0..c2645ad 100644
--- a/tests/camera/src/android/hardware/cts/CameraTest.java
+++ b/tests/camera/src/android/hardware/cts/CameraTest.java
@@ -1045,9 +1045,9 @@
     }
 
     /**
-     * Sanity check of some extra exif tags.
+     * Correctness check of some extra exif tags.
      * <p>
-     * Sanity check some extra exif tags without asserting the check failures
+     * Check some extra exif tags without asserting the check failures
      * immediately. When a failure is detected, the failure cause is logged,
      * the rest of the tests are still executed. The caller can assert with the
      * failure cause based on the returned test status.
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
index 9561eb0..ad0ed57 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -395,7 +395,7 @@
                 image = reader.acquireNextImage();
             } finally {
                 if (image != null) {
-                    // Should only do some quick sanity check in callback, as the ImageReader
+                    // Should only do some quick validity checks in callback, as the ImageReader
                     // could be closed asynchronously, which will close all images acquired from
                     // this ImageReader.
                     checkImage(image, mSize.getWidth(), mSize.getHeight(), mFormat);
@@ -2443,7 +2443,7 @@
     /**
      * Simple validation of JPEG image size and format.
      * <p>
-     * Only validate the image object sanity. It is fast, but doesn't actually
+     * Only validate the image object basic correctness. It is fast, but doesn't actually
      * check the buffer data. Assert is used here as it make no sense to
      * continue the test if the jpeg image captured has some serious failures.
      * </p>
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java
index cb9e522..bef3e26 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/Preconditions.java
@@ -22,7 +22,7 @@
 /**
  * Helper set of methods to perform precondition checks before starting method execution.
  *
- * <p>Typically used to sanity check arguments or the current object state.</p>
+ * <p>Typically used to validity check arguments or the current object state.</p>
  */
 public final class Preconditions {
 
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 332964c..a05af2a 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -518,7 +518,7 @@
     }
 
     /**
-     * Get max AE regions and do sanity check.
+     * Get max AE regions and do validity check.
      *
      * @return AE max regions supported by the camera device
      */
@@ -531,7 +531,7 @@
     }
 
     /**
-     * Get max AWB regions and do sanity check.
+     * Get max AWB regions and do validity check.
      *
      * @return AWB max regions supported by the camera device
      */
@@ -544,7 +544,7 @@
     }
 
     /**
-     * Get max AF regions and do sanity check.
+     * Get max AF regions and do validity check.
      *
      * @return AF max regions supported by the camera device
      */
@@ -628,7 +628,7 @@
     }
 
     /**
-     * Get available thumbnail sizes and do the sanity check.
+     * Get available thumbnail sizes and do the validity check.
      *
      * @return The array of available thumbnail sizes
      */
@@ -656,7 +656,7 @@
     }
 
     /**
-     * Get available focal lengths and do the sanity check.
+     * Get available focal lengths and do the validity check.
      *
      * @return The array of available focal lengths
      */
@@ -677,7 +677,7 @@
     }
 
     /**
-     * Get available apertures and do the sanity check.
+     * Get available apertures and do the validity check.
      *
      * @return The non-null array of available apertures
      */
@@ -992,7 +992,7 @@
     }
 
     /**
-     * Get hyperfocalDistance and do the sanity check.
+     * Get hyperfocalDistance and do the validity check.
      * <p>
      * Note that, this tag is optional, will return -1 if this tag is not
      * available.
@@ -1151,7 +1151,7 @@
     }
 
     /**
-     * get android.control.availableModes and do the sanity check.
+     * get android.control.availableModes and do the validity check.
      *
      * @return available control modes.
      */
@@ -1207,7 +1207,7 @@
     }
 
     /**
-     * Get aeAvailableModes and do the sanity check.
+     * Get aeAvailableModes and do the validity check.
      *
      * <p>Depending on the check level this class has, for WAR or COLLECT levels,
      * If the aeMode list is invalid, return an empty mode array. The the caller doesn't
@@ -1277,7 +1277,7 @@
     }
 
     /**
-     * Get available AWB modes and do the sanity check.
+     * Get available AWB modes and do the validity check.
      *
      * @return array that contains available AWB modes, empty array if awbAvailableModes is
      * unavailable.
@@ -1303,7 +1303,7 @@
     }
 
     /**
-     * Get available AF modes and do the sanity check.
+     * Get available AF modes and do the validity check.
      *
      * @return array that contains available AF modes, empty array if afAvailableModes is
      * unavailable.
@@ -1691,7 +1691,7 @@
     }
 
     /**
-     * Get value of key android.control.aeCompensationStep and do the sanity check.
+     * Get value of key android.control.aeCompensationStep and do the validity check.
      *
      * @return default value if the value is null.
      */
@@ -1716,7 +1716,7 @@
     }
 
     /**
-     * Get value of key android.control.aeCompensationRange and do the sanity check.
+     * Get value of key android.control.aeCompensationRange and do the validity check.
      *
      * @return default value if the value is null or malformed.
      */
@@ -1746,7 +1746,7 @@
     }
 
     /**
-     * Get availableVideoStabilizationModes and do the sanity check.
+     * Get availableVideoStabilizationModes and do the validity check.
      *
      * @return available video stabilization modes, empty array if it is unavailable.
      */
@@ -1777,7 +1777,7 @@
     }
 
     /**
-     * Get availableOpticalStabilization and do the sanity check.
+     * Get availableOpticalStabilization and do the validity check.
      *
      * @return available optical stabilization modes, empty array if it is unavailable.
      */
@@ -1967,7 +1967,7 @@
     }
 
     /**
-     * Get max pipeline depth and do the sanity check.
+     * Get max pipeline depth and do the validity check.
      *
      * @return max pipeline depth, default value if it is not available.
      */
@@ -2033,7 +2033,7 @@
 
 
     /**
-     * Get available capabilities and do the sanity check.
+     * Get available capabilities and do the validity check.
      *
      * @return reported available capabilities list, empty list if the value is unavailable.
      */
@@ -2299,7 +2299,7 @@
     }
 
     /**
-     * Get max number of output raw streams and do the basic sanity check.
+     * Get max number of output raw streams and do the basic validity check.
      *
      * @return reported max number of raw output stream
      */
@@ -2312,7 +2312,7 @@
     }
 
     /**
-     * Get max number of output processed streams and do the basic sanity check.
+     * Get max number of output processed streams and do the basic validity check.
      *
      * @return reported max number of processed output stream
      */
@@ -2325,7 +2325,7 @@
     }
 
     /**
-     * Get max number of output stalling processed streams and do the basic sanity check.
+     * Get max number of output stalling processed streams and do the basic validity check.
      *
      * @return reported max number of stalling processed output stream
      */
@@ -2338,7 +2338,7 @@
     }
 
     /**
-     * Get lens facing and do the sanity check
+     * Get lens facing and do the validity check
      * @return lens facing, return default value (BACK) if value is unavailable.
      */
     public int getLensFacingChecked() {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
index e005059..859eb29 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
@@ -64,12 +64,10 @@
 import android.hardware.display.DisplayManager;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
-import android.provider.Settings;
 import android.server.wm.CommandSession.ActivitySession;
 import android.server.wm.CommandSession.ConfigInfo;
 import android.server.wm.CommandSession.SizeInfo;
 import android.server.wm.TestJournalProvider.TestJournalContainer;
-import android.server.wm.settings.SettingsSession;
 import android.view.Display;
 
 import org.junit.Test;
@@ -452,10 +450,9 @@
     public void testRotatedInfoWithFixedRotationTransform() {
         assumeTrue("Skipping test: no rotation support", supportsRotation());
 
-        // TODO(b/143053092): Remove the settings if it becomes stable.
-        mObjectTracker.manage(new SettingsSession<>(
-                Settings.Global.getUriFor("fixed_rotation_transform"),
-                Settings.Global::getInt, Settings.Global::putInt)).set(1);
+        // Start a portrait activity first to ensure that the orientation will change.
+        launchActivity(PORTRAIT_ORIENTATION_ACTIVITY);
+        mWmState.waitForLastOrientation(SCREEN_ORIENTATION_PORTRAIT);
 
         getLaunchActivityBuilder()
                 .setUseInstrumentation()
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
index 0f89ea2..267bec9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
@@ -25,7 +25,7 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.server.wm.WindowManagerState.STATE_RESUMED;
 import static android.server.wm.ComponentNameUtils.getActivityName;
-import static android.server.wm.UiDeviceUtils.pressBackButton;
+import static android.server.wm.UiDeviceUtils.pressHomeButton;
 import static android.server.wm.app.Components.ANIMATION_TEST_ACTIVITY;
 import static android.server.wm.app.Components.ASSISTANT_ACTIVITY;
 import static android.server.wm.app.Components.ASSISTANT_VOICE_INTERACTION_SERVICE;
@@ -172,11 +172,22 @@
                     TEST_ACTIVITY, ACTIVITY_TYPE_STANDARD, expectedWindowingMode);
         }
 
-        mWmState.assertFocusedActivity("TestActivity should be resumed", TEST_ACTIVITY);
-        mWmState.assertFrontStack("Fullscreen stack should be on top.",
-                expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
-        mWmState.assertFocusedStack("Fullscreen stack should be focused.",
-                expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
+        if (isAssistantOnTop()) {
+            // If the assistant is configured to be always-on-top, then the new task should have
+            // been started behind it and the assistant stack should still be on top.
+            mWmState.assertFocusedActivity(
+                    "AssistantActivity should be focused", ASSISTANT_ACTIVITY);
+            mWmState.assertFrontStackActivityType(
+                    "Assistant stack should be on top.", ACTIVITY_TYPE_ASSISTANT);
+            mWmState.assertFocusedStack("Assistant stack should be focused.",
+                    WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT);
+        } else {
+            mWmState.assertFocusedActivity("TestActivity should be resumed", TEST_ACTIVITY);
+            mWmState.assertFrontStack("Fullscreen stack should be on top.",
+                    expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
+            mWmState.assertFocusedStack("Fullscreen stack should be focused.",
+                    expectedWindowingMode, ACTIVITY_TYPE_STANDARD);
+        }
 
         // Now, tell it to finish itself and ensure that the assistant stack is brought back forward
         mBroadcastActionTrigger.doAction(TEST_ACTIVITY_ACTION_FINISH_SELF);
@@ -189,6 +200,13 @@
 
     @Test
     public void testAssistantStackFinishToPreviousApp() throws Exception {
+        // If the Assistant is configured to be always-on-top, then the assistant activity
+        // started in setUp() will not allow any other activities to start. Therefore we should
+        // remove it before launching a fullscreen activity.
+        if (isAssistantOnTop()) {
+            removeStacksWithActivityTypes(ACTIVITY_TYPE_ASSISTANT);
+        }
+
         // Launch an assistant activity on top of an existing fullscreen activity, and ensure that
         // the fullscreen activity is still visible and on top after the assistant activity finishes
         launchActivityOnDisplay(TEST_ACTIVITY, mAssistantDisplayId);
@@ -232,7 +250,8 @@
             // Go home, launch the assistant and check to see that home is visible
             removeStacksInWindowingModes(WINDOWING_MODE_FULLSCREEN,
                     WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
-            launchHomeActivity();
+            pressHomeButton();
+            resumeAppSwitches();
             launchActivityNoWait(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_ASSISTANT_IS_TRANSLUCENT, "true");
             waitForValidStateWithActivityType(
@@ -257,7 +276,8 @@
             // Go home, launch assistant, launch app into fullscreen with activity present, and go
             // back.Ensure home is visible.
             removeStacksWithActivityTypes(ACTIVITY_TYPE_ASSISTANT);
-            launchHomeActivity();
+            pressHomeButton();
+            resumeAppSwitches();
             launchActivityNoWait(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_ASSISTANT_IS_TRANSLUCENT, "true",
                     EXTRA_ASSISTANT_LAUNCH_NEW_TASK, getActivityName(TEST_ACTIVITY));
@@ -266,7 +286,7 @@
 
             final ComponentName homeActivity = mWmState.getHomeActivityName();
             mWmState.waitAndAssertVisibilityGone(homeActivity);
-            pressBackButton();
+            mBroadcastActionTrigger.doAction(TEST_ACTIVITY_ACTION_FINISH_SELF);
             mWmState.waitForFocusedStack(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT);
             assertAssistantStackExists();
             mWmState.waitForHomeActivityVisible();
@@ -319,7 +339,7 @@
             launchActivityOnDisplay(ANIMATION_TEST_ACTIVITY, mAssistantDisplayId);
             // Wait for animation finished.
             mWmState.waitForActivityState(ANIMATION_TEST_ACTIVITY, STATE_RESUMED);
-            mWmState.assertVisibility(ASSISTANT_ACTIVITY, false);
+            mWmState.assertVisibility(ASSISTANT_ACTIVITY, isAssistantOnTop());
 
             // Launch the assistant again and ensure that it goes into the same task
             launchActivityOnDisplayNoWait(LAUNCH_ASSISTANT_ACTIVITY_FROM_SESSION,
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
index 042eb48..72ce477 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
@@ -1004,6 +1004,8 @@
     @Test
     @FlakyTest(bugId=156314330)
     public void testFinishPipActivityWithTaskOverlay() throws Exception {
+        // Trigger PiP menu activity to properly lose focuse when going home
+        launchActivity(TEST_ACTIVITY);
         // Launch PiP activity
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
         waitForEnterPip(PIP_ACTIVITY);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
index 00fc83b..e3566b9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
@@ -178,18 +178,23 @@
      */
     @Test
     public void testReparentOff() throws Throwable {
+        final SurfaceControl sc = buildDefaultRedSurface(null);
         verifyTest(
                 new SurfaceControlTestCase.ParentSurfaceConsumer () {
                     @Override
                     public void addChildren(SurfaceControl parent) {
-                        final SurfaceControl sc = buildDefaultRedSurface(parent);
-
+                        new SurfaceControl.Transaction().reparent(sc, parent).apply();
                         new SurfaceControl.Transaction().reparent(sc, null).apply();
-
-                        sc.release();
                     }
                 },
                 new RectChecker(new Rect(0, 0, 100, 100), PixelColor.WHITE));
+      // Since the SurfaceControl is parented off-screen, if we release our reference
+      // it may completely die. If this occurs while the render thread is still rendering
+      // the RED background we could trigger a crash. For this test defer destroying the
+      // Surface until we have collected our test results.
+      if (sc != null) {
+        sc.release();
+      }
     }
 
     /**
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java
index 32255d2..187ed91 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationImeTests.java
@@ -56,11 +56,13 @@
 @Presubmit
 public class WindowInsetsAnimationImeTests extends WindowInsetsAnimationTestBase {
 
+    private static final int KEYBOARD_HEIGHT = 400;
+
     @Rule
     public final MockImeSessionRule mMockImeSessionRule = new MockImeSessionRule(
             InstrumentationRegistry.getInstrumentation().getContext(),
             InstrumentationRegistry.getInstrumentation().getUiAutomation(),
-            new ImeSettings.Builder()
+            new ImeSettings.Builder().setInputViewHeight(KEYBOARD_HEIGHT).setDrawsBehindNavBar(true)
     );
 
     @Before
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index 77391b9..7ddc020 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -215,6 +215,7 @@
     private static Boolean sHasHomeScreen = null;
     private static Boolean sSupportsSystemDecorsOnSecondaryDisplays = null;
     private static Boolean sSupportsInsecureLockScreen = null;
+    private static Boolean sIsAssistantOnTop = null;
     private static boolean sStackTaskLeakFound;
 
     protected static final int INVALID_DEVICE_ROTATION = -1;
@@ -1092,6 +1093,14 @@
         return sSupportsInsecureLockScreen;
     }
 
+    protected boolean isAssistantOnTop() {
+        if (sIsAssistantOnTop == null) {
+            sIsAssistantOnTop = mContext.getResources().getBoolean(
+                    android.R.bool.config_assistantOnTopOfDream);
+        }
+        return sIsAssistantOnTop;
+    }
+
     /**
      * Rotation support is indicated by explicitly having both landscape and portrait
      * features or not listing either at all.
diff --git a/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt b/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt
index 222059f..3dd5c21 100644
--- a/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt
+++ b/tests/tests/appop/AppThatUsesAppOps/src/android/app/appops/cts/appthatusesappops/AutoClosingActivity.kt
@@ -21,6 +21,8 @@
 
 class AutoClosingActivity : Activity() {
     override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+
         finish()
     }
 }
diff --git a/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt b/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
index 1d14a77..9f785b8 100644
--- a/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
@@ -29,7 +29,6 @@
 private const val APK_PATH = "/data/local/tmp/cts/appops/"
 
 private const val APP_PKG = "android.app.appops.cts.apptocollect"
-private const val MESSAGE = "Stack trace message"
 
 @AppModeFull(reason = "Test relies on seeing other apps. Instant apps can't see other apps")
 class RuntimeMessageCollectionTest {
@@ -58,7 +57,7 @@
             val start = System.currentTimeMillis()
             runWithShellPermissionIdentity {
                 appOpsManager.noteOp(AppOpsManager.OPSTR_READ_CONTACTS, appUid, APP_PKG,
-                        TEST_ATTRIBUTION_TAG, MESSAGE)
+                        TEST_ATTRIBUTION_TAG, null)
             }
             while (System.currentTimeMillis() - start < TIMEOUT_MILLIS) {
                 sleep(200)
@@ -71,7 +70,7 @@
                         assertThat(message.op).isEqualTo(AppOpsManager.OPSTR_READ_CONTACTS)
                         assertThat(message.uid).isEqualTo(appUid)
                         assertThat(message.attributionTag).isEqualTo(TEST_ATTRIBUTION_TAG)
-                        assertThat(message.message).isEqualTo(MESSAGE)
+                        assertThat(message.message).isNotNull()
                         return
                     }
                 }
diff --git a/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java b/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java
index ec02cd3..75f7cc4 100644
--- a/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/PackageManagerShellCommandIncrementalTest.java
@@ -38,7 +38,6 @@
 import org.junit.After;
 import org.junit.Assume;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -234,7 +233,6 @@
 
     @LargeTest
     @Test
-    @Ignore("Flaky, b/159368388 to reenable.")
     public void testInstallSysTrace() throws Exception {
         // Async atrace dump uses less resources but requires periodic pulls.
         // Overall timeout of 30secs in 100ms intervals should be enough.
@@ -270,8 +268,11 @@
         });
         readFromProcess.start();
 
-        installPackage(TEST_APK);
-        assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+        for (int i = 0; i < 3; ++i) {
+            installPackage(TEST_APK);
+            assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+            uninstallPackageSilently(TEST_APP_PACKAGE);
+        }
 
         readFromProcess.join();
         assertNotEquals(0, result.size());
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
index d17e702..cb6985f 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
@@ -772,8 +772,13 @@
             type.equalsIgnoreCase(MediaFormat.MIMETYPE_VIDEO_VP9      ));
     }
 
+    private boolean isLowRamDevice() {
+        return ((ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE)).
+            isLowRamDevice();
+    }
+
     public void testGetMaxSupportedInstances() {
-        final int MAX_INSTANCES = 32;
+        final int MAX_INSTANCES = isLowRamDevice() ? 16 : 32;
         StringBuilder xmlOverrides = new StringBuilder();
         MediaCodecList allCodecs = new MediaCodecList(MediaCodecList.ALL_CODECS);
         for (MediaCodecInfo info : allCodecs.getCodecInfos()) {
diff --git a/tests/tests/media/src/android/media/cts/MediaRouter2Test.java b/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
index 238da0b..3f6e690 100644
--- a/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
+++ b/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
@@ -17,6 +17,7 @@
 package android.media.cts;
 
 import static android.content.Context.AUDIO_SERVICE;
+import static android.media.MediaRoute2Info.FEATURE_LIVE_AUDIO;
 import static android.media.MediaRoute2Info.PLAYBACK_VOLUME_VARIABLE;
 import static android.media.cts.StubMediaRoute2ProviderService.FEATURES_SPECIAL;
 import static android.media.cts.StubMediaRoute2ProviderService.FEATURE_SAMPLE;
@@ -90,6 +91,9 @@
     private static final String TEST_VALUE = "test_value";
     private static final RouteDiscoveryPreference EMPTY_DISCOVERY_PREFERENCE =
             new RouteDiscoveryPreference.Builder(Collections.emptyList(), false).build();
+    private static final RouteDiscoveryPreference LIVE_AUDIO_DISCOVERY_PREFERENCE =
+            new RouteDiscoveryPreference.Builder(
+                    Collections.singletonList(FEATURE_LIVE_AUDIO), false).build();
 
     @Before
     public void setUp() throws Exception {
@@ -124,10 +128,16 @@
 
     @Test
     public void testGetRoutesAfterCreation() {
-        List<MediaRoute2Info> initialRoutes = mRouter2.getRoutes();
-        assertFalse(initialRoutes.isEmpty());
-        for (MediaRoute2Info route : initialRoutes) {
-            assertTrue(route.isSystemRoute());
+        RouteCallback routeCallback = new RouteCallback() {};
+        mRouter2.registerRouteCallback(mExecutor, routeCallback, LIVE_AUDIO_DISCOVERY_PREFERENCE);
+        try {
+            List<MediaRoute2Info> initialRoutes = mRouter2.getRoutes();
+            assertFalse(initialRoutes.isEmpty());
+            for (MediaRoute2Info route : initialRoutes) {
+                assertTrue(route.getFeatures().contains(FEATURE_LIVE_AUDIO));
+            }
+        } finally {
+            mRouter2.unregisterRouteCallback(routeCallback);
         }
     }
 
@@ -138,18 +148,13 @@
     public void testGetRoutes() throws Exception {
         Map<String, MediaRoute2Info> routes = waitAndGetRoutes(FEATURES_SPECIAL);
 
-        int systemRouteCount = 0;
         int remoteRouteCount = 0;
         for (MediaRoute2Info route : routes.values()) {
-            if (route.isSystemRoute()) {
-                systemRouteCount++;
-            } else {
+            if (!route.isSystemRoute()) {
                 remoteRouteCount++;
             }
         }
 
-        // Can be greater than 1 if BT devices are connected.
-        assertTrue(systemRouteCount > 0);
         assertEquals(1, remoteRouteCount);
         assertNotNull(routes.get(ROUTE_ID_SPECIAL_FEATURE));
     }
@@ -996,8 +1001,7 @@
             }
         };
 
-        mRouter2.registerRouteCallback(mExecutor, routeCallback,
-                new RouteDiscoveryPreference.Builder(new ArrayList<>(), true).build());
+        mRouter2.registerRouteCallback(mExecutor, routeCallback, LIVE_AUDIO_DISCOVERY_PREFERENCE);
 
         try {
             mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, targetVolume, 0);
diff --git a/tests/tests/net/Android.bp b/tests/tests/net/Android.bp
index 2b99a40..112799b 100644
--- a/tests/tests/net/Android.bp
+++ b/tests/tests/net/Android.bp
@@ -36,19 +36,20 @@
         "src/**/*.java",
         "src/**/*.kt",
     ],
-
+    jarjar_rules: "jarjar-rules-shared.txt",
     static_libs: [
         "FrameworksNetCommonTests",
         "TestNetworkStackLib",
-        "core-tests-support",
         "compatibility-device-util-axt",
+        "core-tests-support",
         "cts-net-utils",
         "ctstestrunner-axt",
         "ctstestserver",
-        "mockwebserver",
         "junit",
         "junit-params",
         "libnanohttpd",
+        "mockwebserver",
+        "net-utils-framework-common",
         "truth-prebuilt",
     ],
 
diff --git a/tests/tests/net/jarjar-rules-shared.txt b/tests/tests/net/jarjar-rules-shared.txt
new file mode 100644
index 0000000..11dba74
--- /dev/null
+++ b/tests/tests/net/jarjar-rules-shared.txt
@@ -0,0 +1,2 @@
+# Module library in frameworks/libs/net
+rule com.android.net.module.util.** android.net.cts.util.@1
\ No newline at end of file
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java
index d17d8e5..a19ba64 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java
@@ -16,6 +16,7 @@
 
 package android.net.cts;
 
+import static android.content.pm.PackageManager.FEATURE_TELEPHONY;
 import static android.net.ConnectivityDiagnosticsManager.ConnectivityDiagnosticsCallback;
 import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
 import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
@@ -31,9 +32,11 @@
 import static android.net.ConnectivityDiagnosticsManager.persistableBundleEquals;
 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
 import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED;
+import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
 import static android.net.NetworkCapabilities.TRANSPORT_TEST;
 import static android.net.cts.util.CtsNetUtils.TestNetworkCallback;
 
+import static com.android.compatibility.common.util.SystemUtil.callWithShellPermissionIdentity;
 import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
 
 import static org.junit.Assert.assertEquals;
@@ -41,9 +44,15 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 
 import android.annotation.NonNull;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
 import android.net.ConnectivityDiagnosticsManager;
 import android.net.ConnectivityManager;
 import android.net.LinkAddress;
@@ -55,13 +64,19 @@
 import android.os.Binder;
 import android.os.Build;
 import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.os.Process;
 import android.platform.test.annotations.AppModeFull;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
 import android.util.Pair;
 
 import androidx.test.InstrumentationRegistry;
 
+import com.android.internal.telephony.uicc.IccUtils;
+import com.android.internal.util.ArrayUtils;
 import com.android.testutils.ArrayTrackRecord;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
 import com.android.testutils.DevSdkIgnoreRunner;
@@ -71,7 +86,12 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
 
 @RunWith(DevSdkIgnoreRunner.class)
 @IgnoreUpTo(Build.VERSION_CODES.Q) // ConnectivityDiagnosticsManager did not exist in Q
@@ -85,6 +105,7 @@
     private static final int FAIL_RATE_PERCENTAGE = 100;
     private static final int UNKNOWN_DETECTION_METHOD = 4;
     private static final int FILTERED_UNKNOWN_DETECTION_METHOD = 0;
+    private static final int CARRIER_CONFIG_CHANGED_BROADCAST_TIMEOUT = 5000;
 
     private static final Executor INLINE_EXECUTOR = x -> x.run();
 
@@ -95,44 +116,71 @@
                     .removeCapability(NET_CAPABILITY_NOT_VPN)
                     .build();
 
-    // Callback used to keep TestNetworks up when there are no other outstanding NetworkRequests
-    // for it.
-    private static final TestNetworkCallback TEST_NETWORK_CALLBACK = new TestNetworkCallback();
+    private static final String SHA_256 = "SHA-256";
+
+    private static final NetworkRequest CELLULAR_NETWORK_REQUEST =
+            new NetworkRequest.Builder().addTransportType(TRANSPORT_CELLULAR).build();
 
     private static final IBinder BINDER = new Binder();
 
     private Context mContext;
     private ConnectivityManager mConnectivityManager;
     private ConnectivityDiagnosticsManager mCdm;
+    private CarrierConfigManager mCarrierConfigManager;
+    private PackageManager mPackageManager;
+    private TelephonyManager mTelephonyManager;
+
+    // Callback used to keep TestNetworks up when there are no other outstanding NetworkRequests
+    // for it.
+    private TestNetworkCallback mTestNetworkCallback;
     private Network mTestNetwork;
+    private ParcelFileDescriptor mTestNetworkFD;
+
+    private List<TestConnectivityDiagnosticsCallback> mRegisteredCallbacks;
 
     @Before
     public void setUp() throws Exception {
         mContext = InstrumentationRegistry.getContext();
         mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
         mCdm = mContext.getSystemService(ConnectivityDiagnosticsManager.class);
+        mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
+        mPackageManager = mContext.getPackageManager();
+        mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
 
-        mConnectivityManager.requestNetwork(TEST_NETWORK_REQUEST, TEST_NETWORK_CALLBACK);
+        mTestNetworkCallback = new TestNetworkCallback();
+        mConnectivityManager.requestNetwork(TEST_NETWORK_REQUEST, mTestNetworkCallback);
+
+        mRegisteredCallbacks = new ArrayList<>();
     }
 
     @After
     public void tearDown() throws Exception {
-        mConnectivityManager.unregisterNetworkCallback(TEST_NETWORK_CALLBACK);
-
+        mConnectivityManager.unregisterNetworkCallback(mTestNetworkCallback);
         if (mTestNetwork != null) {
             runWithShellPermissionIdentity(() -> {
                 final TestNetworkManager tnm = mContext.getSystemService(TestNetworkManager.class);
                 tnm.teardownTestNetwork(mTestNetwork);
             });
+            mTestNetwork = null;
+        }
+
+        if (mTestNetworkFD != null) {
+            mTestNetworkFD.close();
+            mTestNetworkFD = null;
+        }
+
+        for (TestConnectivityDiagnosticsCallback cb : mRegisteredCallbacks) {
+            mCdm.unregisterConnectivityDiagnosticsCallback(cb);
         }
     }
 
     @Test
     public void testRegisterConnectivityDiagnosticsCallback() throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         final String interfaceName =
                 mConnectivityManager.getLinkProperties(mTestNetwork).getInterfaceName();
@@ -142,9 +190,98 @@
     }
 
     @Test
+    public void testRegisterCallbackWithCarrierPrivileges() throws Exception {
+        assumeTrue(mPackageManager.hasSystemFeature(FEATURE_TELEPHONY));
+
+        final int subId = SubscriptionManager.getDefaultSubscriptionId();
+        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+            fail("Need an active subscription. Please ensure that the device has working mobile"
+                    + " data.");
+        }
+
+        final CarrierConfigReceiver carrierConfigReceiver = new CarrierConfigReceiver(subId);
+        mContext.registerReceiver(
+                carrierConfigReceiver,
+                new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
+
+        final TestNetworkCallback testNetworkCallback = new TestNetworkCallback();
+
+        try {
+            doBroadcastCarrierConfigsAndVerifyOnConnectivityReportAvailable(
+                    subId, carrierConfigReceiver, testNetworkCallback);
+        } finally {
+            runWithShellPermissionIdentity(
+                    () -> mCarrierConfigManager.overrideConfig(subId, null),
+                    android.Manifest.permission.MODIFY_PHONE_STATE);
+            mConnectivityManager.unregisterNetworkCallback(testNetworkCallback);
+            mContext.unregisterReceiver(carrierConfigReceiver);
+        }
+    }
+
+    private String getCertHashForThisPackage() throws Exception {
+        final PackageInfo pkgInfo =
+                mPackageManager.getPackageInfo(
+                        mContext.getOpPackageName(), PackageManager.GET_SIGNATURES);
+        final MessageDigest md = MessageDigest.getInstance(SHA_256);
+        final byte[] certHash = md.digest(pkgInfo.signatures[0].toByteArray());
+        return IccUtils.bytesToHexString(certHash);
+    }
+
+    private void doBroadcastCarrierConfigsAndVerifyOnConnectivityReportAvailable(
+            int subId,
+            @NonNull CarrierConfigReceiver carrierConfigReceiver,
+            @NonNull TestNetworkCallback testNetworkCallback)
+            throws Exception {
+        final PersistableBundle carrierConfigs = new PersistableBundle();
+        carrierConfigs.putStringArray(
+                CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY,
+                new String[] {getCertHashForThisPackage()});
+
+        runWithShellPermissionIdentity(
+                () -> {
+                    mCarrierConfigManager.overrideConfig(subId, carrierConfigs);
+                    mCarrierConfigManager.notifyConfigChangedForSubId(subId);
+                },
+                android.Manifest.permission.MODIFY_PHONE_STATE);
+
+        // TODO(b/157779832): This should use android.permission.CHANGE_NETWORK_STATE. However, the
+        // shell does not have CHANGE_NETWORK_STATE, so use CONNECTIVITY_INTERNAL until the shell
+        // permissions are updated.
+        runWithShellPermissionIdentity(
+                () -> mConnectivityManager.requestNetwork(
+                        CELLULAR_NETWORK_REQUEST, testNetworkCallback),
+                android.Manifest.permission.CONNECTIVITY_INTERNAL);
+
+        final Network network = testNetworkCallback.waitForAvailable();
+        assertNotNull(network);
+
+        assertTrue("Didn't receive broadcast for ACTION_CARRIER_CONFIG_CHANGED for subId=" + subId,
+                carrierConfigReceiver.waitForCarrierConfigChanged());
+        assertTrue("Don't have Carrier Privileges after adding cert for this package",
+                mTelephonyManager.createForSubscriptionId(subId).hasCarrierPrivileges());
+
+        // Wait for CarrierPrivilegesTracker to receive the ACTION_CARRIER_CONFIG_CHANGED
+        // broadcast. CPT then needs to update the corresponding DataConnection, which then
+        // updates ConnectivityService. Unfortunately, this update to the NetworkCapabilities in
+        // CS does not trigger NetworkCallback#onCapabilitiesChanged as changing the
+        // administratorUids is not a publicly visible change. In lieu of a better signal to
+        // detministically wait for, use Thread#sleep here.
+        Thread.sleep(500);
+
+        final TestConnectivityDiagnosticsCallback connDiagsCallback =
+                createAndRegisterConnectivityDiagnosticsCallback(CELLULAR_NETWORK_REQUEST);
+
+        final String interfaceName =
+                mConnectivityManager.getLinkProperties(network).getInterfaceName();
+        connDiagsCallback.expectOnConnectivityReportAvailable(
+                network, interfaceName, TRANSPORT_CELLULAR);
+        connDiagsCallback.assertNoCallback();
+    }
+
+    @Test
     public void testRegisterDuplicateConnectivityDiagnosticsCallback() {
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         try {
             mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
@@ -168,10 +305,11 @@
 
     @Test
     public void testOnConnectivityReportAvailable() throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
         final String interfaceName =
                 mConnectivityManager.getLinkProperties(mTestNetwork).getInterfaceName();
@@ -219,10 +357,11 @@
             long timestampMillis,
             @NonNull PersistableBundle extras)
             throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         final String interfaceName =
                 mConnectivityManager.getLinkProperties(mTestNetwork).getInterfaceName();
@@ -250,10 +389,11 @@
     }
 
     private void verifyOnNetworkConnectivityReported(boolean hasConnectivity) throws Exception {
-        mTestNetwork = setUpTestNetwork();
+        mTestNetworkFD = setUpTestNetwork().getFileDescriptor();
+        mTestNetwork = mTestNetworkCallback.waitForAvailable();
 
-        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
-        mCdm.registerConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST, INLINE_EXECUTOR, cb);
+        final TestConnectivityDiagnosticsCallback cb =
+                createAndRegisterConnectivityDiagnosticsCallback(TEST_NETWORK_REQUEST);
 
         // onConnectivityReportAvailable always invoked when the test network is established
         final String interfaceName =
@@ -274,17 +414,12 @@
         cb.assertNoCallback();
     }
 
-    @NonNull
-    private Network waitForConnectivityServiceIdleAndGetNetwork() throws InterruptedException {
-        // Get a new Network. This requires going through the ConnectivityService thread. Once it
-        // completes, all previously enqueued messages on the ConnectivityService main Handler have
-        // completed.
-        final TestNetworkCallback callback = new TestNetworkCallback();
-        mConnectivityManager.requestNetwork(TEST_NETWORK_REQUEST, callback);
-        final Network network = callback.waitForAvailable();
-        mConnectivityManager.unregisterNetworkCallback(callback);
-        assertNotNull(network);
-        return network;
+    private TestConnectivityDiagnosticsCallback createAndRegisterConnectivityDiagnosticsCallback(
+            NetworkRequest request) {
+        final TestConnectivityDiagnosticsCallback cb = new TestConnectivityDiagnosticsCallback();
+        mCdm.registerConnectivityDiagnosticsCallback(request, INLINE_EXECUTOR, cb);
+        mRegisteredCallbacks.add(cb);
+        return cb;
     }
 
     /**
@@ -292,16 +427,16 @@
      * to the Network being validated.
      */
     @NonNull
-    private Network setUpTestNetwork() throws Exception {
+    private TestNetworkInterface setUpTestNetwork() throws Exception {
         final int[] administratorUids = new int[] {Process.myUid()};
-        runWithShellPermissionIdentity(
+        return callWithShellPermissionIdentity(
                 () -> {
                     final TestNetworkManager tnm =
                             mContext.getSystemService(TestNetworkManager.class);
                     final TestNetworkInterface tni = tnm.createTunInterface(new LinkAddress[0]);
                     tnm.setupTestNetwork(tni.getInterfaceName(), administratorUids, BINDER);
+                    return tni;
                 });
-        return waitForConnectivityServiceIdleAndGetNetwork();
     }
 
     private static class TestConnectivityDiagnosticsCallback
@@ -326,13 +461,18 @@
 
         public void expectOnConnectivityReportAvailable(
                 @NonNull Network network, @NonNull String interfaceName) {
+            expectOnConnectivityReportAvailable(network, interfaceName, TRANSPORT_TEST);
+        }
+
+        public void expectOnConnectivityReportAvailable(
+                @NonNull Network network, @NonNull String interfaceName, int transportType) {
             final ConnectivityReport result =
                     (ConnectivityReport) mHistory.poll(CALLBACK_TIMEOUT_MILLIS, x -> true);
             assertEquals(network, result.getNetwork());
 
             final NetworkCapabilities nc = result.getNetworkCapabilities();
             assertNotNull(nc);
-            assertTrue(nc.hasTransport(TRANSPORT_TEST));
+            assertTrue(nc.hasTransport(transportType));
             assertNotNull(result.getLinkProperties());
             assertEquals(interfaceName, result.getLinkProperties().getInterfaceName());
 
@@ -386,4 +526,43 @@
                     mHistory.poll(NO_CALLBACK_INVOKED_TIMEOUT, x -> true));
         }
     }
+
+    private class CarrierConfigReceiver extends BroadcastReceiver {
+        private final CountDownLatch mLatch = new CountDownLatch(1);
+        private final int mSubId;
+
+        CarrierConfigReceiver(int subId) {
+            mSubId = subId;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (!CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
+                return;
+            }
+
+            final int subId =
+                    intent.getIntExtra(
+                            CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX,
+                            SubscriptionManager.INVALID_SUBSCRIPTION_ID);
+            if (mSubId != subId) return;
+
+            final PersistableBundle carrierConfigs = mCarrierConfigManager.getConfigForSubId(subId);
+            if (!CarrierConfigManager.isConfigForIdentifiedCarrier(carrierConfigs)) return;
+
+            final String[] certs =
+                    carrierConfigs.getStringArray(
+                            CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY);
+            try {
+                if (ArrayUtils.contains(certs, getCertHashForThisPackage())) {
+                    mLatch.countDown();
+                }
+            } catch (Exception e) {
+            }
+        }
+
+        boolean waitForCarrierConfigChanged() throws Exception {
+            return mLatch.await(CARRIER_CONFIG_CHANGED_BROADCAST_TIMEOUT, TimeUnit.MILLISECONDS);
+        }
+    }
 }
diff --git a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
index 2c74ac8..835f541 100644
--- a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
+++ b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
@@ -291,6 +291,7 @@
                 .setData(Uri.fromParts("package", packageName, null))
                 .addFlags(FLAG_ACTIVITY_NEW_TASK))
 
+        waitForIdle()
         click("Permissions")
     }
 
diff --git a/tests/tests/provider/res/raw/moov-at-end-zero-len.mp4 b/tests/tests/provider/res/raw/moov-at-end-zero-len.mp4
new file mode 100644
index 0000000..5b307e2
--- /dev/null
+++ b/tests/tests/provider/res/raw/moov-at-end-zero-len.mp4
Binary files differ
diff --git a/tests/tests/provider/res/raw/moov-at-end.mp4 b/tests/tests/provider/res/raw/moov-at-end.mp4
new file mode 100644
index 0000000..cdf74b5
--- /dev/null
+++ b/tests/tests/provider/res/raw/moov-at-end.mp4
Binary files differ
diff --git a/tests/tests/provider/res/raw/testvideo_meta.mp4 b/tests/tests/provider/res/raw/testvideo_meta.mp4
index 8f04b40..e83c61d 100644
--- a/tests/tests/provider/res/raw/testvideo_meta.mp4
+++ b/tests/tests/provider/res/raw/testvideo_meta.mp4
Binary files differ
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
index 0fa99ca..88295eb 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
@@ -258,29 +258,45 @@
         // STOPSHIP: remove this once isolated storage is always enabled
         Assume.assumeTrue(StorageManager.hasIsolatedStorage());
 
-        final Uri publishUri = ProviderTestUtils.stageMedia(R.raw.testvideo_meta, mExternalVideo,
-                "video/mp4");
+        // These videos have all had their ISO location metadata (in the (c)xyz box) artificially
+        // modified to +58.0000+011.0000 (middle of Skagerrak).
+        int[] videoIds = new int[] {
+            R.raw.testvideo_meta,
+            R.raw.moov_at_end,
+            R.raw.moov_at_end_zero_len,
+        };
+        Uri[] uris = new Uri[videoIds.length];
+        for (int i = 0; i < videoIds.length; i++) {
+            uris[i] = ProviderTestUtils.stageMedia(videoIds[i], mExternalVideo, "video/mp4");
+        }
 
-        // Since we own the video, we should be able to see the location
-        // we ourselves contributed
-        try (ParcelFileDescriptor pfd = mContentResolver.openFile(publishUri, "r", null);
-                MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
-            mmr.setDataSource(pfd.getFileDescriptor());
-            assertEquals("+37.4217-122.0834/",
-                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
-            assertEquals("2", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+        for (int i = 0; i < uris.length; i++) {
+            // Since we own the video, we should be able to see the location
+            // we ourselves contributed
+            try (ParcelFileDescriptor pfd = mContentResolver.openFile(uris[i], "r", null);
+                    MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
+                mmr.setDataSource(pfd.getFileDescriptor());
+                assertEquals("+58.0000+011.0000/",
+                        mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
+                assertEquals("2",
+                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+            }
         }
 
         // Revoke location access and remove ownership, which means that location should be redacted
         ProviderTestUtils.revokeMediaLocationPermission(mContext);
-        ProviderTestUtils.clearOwner(publishUri);
 
-        try (ParcelFileDescriptor pfd = mContentResolver.openFile(publishUri, "r", null);
-                MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
-            mmr.setDataSource(pfd.getFileDescriptor());
-            assertEquals(null,
-                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
-            assertEquals("2", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+        for (int i = 0; i < uris.length; i++) {
+            ProviderTestUtils.clearOwner(uris[i]);
+
+            try (ParcelFileDescriptor pfd = mContentResolver.openFile(uris[i], "r", null);
+                    MediaMetadataRetriever mmr = new MediaMetadataRetriever()) {
+                mmr.setDataSource(pfd.getFileDescriptor());
+                assertEquals(null,
+                        mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
+                assertEquals("2",
+                    mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+            }
         }
     }
 
diff --git a/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp b/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp
index ab4ce58..fbf9f9a 100644
--- a/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp
+++ b/tests/tests/view/jni/android_view_cts_ChoreographerNativeTest.cpp
@@ -408,16 +408,25 @@
     Callback* cb64 = new Callback("cb64");
     auto start = now();
 
+    auto vsyncPeriod = std::chrono::duration_cast<std::chrono::milliseconds>(
+                           NOMINAL_VSYNC_PERIOD)
+                           .count();
     auto delay = std::chrono::duration_cast<std::chrono::milliseconds>(DELAY_PERIOD).count();
     AChoreographer_postFrameCallbackDelayed(choreographer, frameCallback, cb1, delay);
     AChoreographer_postFrameCallbackDelayed64(choreographer, frameCallback64, cb64, delay);
 
     std::this_thread::sleep_for(DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 10);
-    ALooper_pollAll(16, nullptr, nullptr, nullptr);
+    // Ensure that callbacks are seen by the looper instance at approximately
+    // the same time, and provide enough time for the looper instance to process
+    // the delayed callback and the requested vsync signal if needed.
+    ALooper_pollAll(vsyncPeriod * 5, nullptr, nullptr, nullptr);
     verifyRefreshRateCallback(env, cb, 1);
-    verifyCallback(env, cb64, 1, start, DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 11);
+    verifyCallback(env, cb64, 1, start,
+                   DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 15);
     const auto delayToTestFor32Bit =
-            sizeof(long) == sizeof(int64_t) ? DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 11 : ZERO;
+        sizeof(long) == sizeof(int64_t)
+            ? DELAY_PERIOD + NOMINAL_VSYNC_PERIOD * 15
+            : ZERO;
     verifyCallback(env, cb1, 1, start, delayToTestFor32Bit);
     AChoreographer_unregisterRefreshRateCallback(choreographer, refreshRateCallback, cb);
 }
diff --git a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
index 66b1539..7ab5143 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
@@ -19,6 +19,7 @@
 import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
 import static android.opengl.GLES20.glClear;
 import static android.opengl.GLES20.glClearColor;
+import static android.opengl.GLES20.glFinish;
 
 import android.app.Activity;
 import android.content.pm.ActivityInfo;
@@ -258,6 +259,7 @@
         int surfaceUpdateCount = mSurfaceUpdatedCount;
         runOnGLThread(() -> {
             callback.drawFrame(mSurfaceWidth, mSurfaceHeight);
+            glFinish();
             if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                 throw new RuntimeException("Cannot swap buffers");
             }