Merge "Remove IncrementalTestAppRule." into rvc-dev
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java
index c9b4de1..ddcb4a1 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java
@@ -166,7 +166,10 @@
                     .withMessage("Display.getMode()")
                     .about(MODE_SUBJECT_FACTORY)
                     .that(display.getMode())
-                    .isEquivalentTo(new Mode(3840, 2160, 60f), REFRESH_RATE_PRECISION);
+                    .isEquivalentToAnyOf(
+                            REFRESH_RATE_PRECISION,
+                            new Mode(3840, 2160, 60f),
+                            new Mode(3840, 2160, 50f));
 
              Mode[] expected2160pSupportedModes = new Mode[]{
                     new Mode(720, 480, 60f),
@@ -225,7 +228,10 @@
                     .withMessage("Display.getMode()")
                     .about(MODE_SUBJECT_FACTORY)
                     .that(display.getMode())
-                    .isEquivalentTo(new Mode(1920, 1080, 60f), REFRESH_RATE_PRECISION);
+                    .isEquivalentToAnyOf(
+                            REFRESH_RATE_PRECISION,
+                            new Mode(1920, 1080, 60f),
+                            new Mode(1920, 1080, 50f));
 
             final Mode[] expected1080pSupportedModes = new Mode[]{
                     new Mode(720, 480, 60f),
@@ -278,9 +284,12 @@
             super(failureMetadata, subject);
         }
 
-        public void isEquivalentTo(Mode mode, float refreshRatePrecision) {
-            if (!mode.isEquivalent(actual(), refreshRatePrecision)) {
-                failWithActual("expected", mode);
+        public void isEquivalentToAnyOf(final float refreshRatePrecision, Mode... modes) {
+            boolean found =
+                    Arrays.stream(modes)
+                            .anyMatch(mode -> mode.isEquivalent(actual(), refreshRatePrecision));
+            if (!found) {
+                failWithActual("expected any of", Arrays.toString(modes));
             }
         }
     }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/OWNERS b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/OWNERS
new file mode 100644
index 0000000..5627ff5
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/OWNERS
@@ -0,0 +1,2 @@
+blindahl@google.com
+shalamanov@google.com
diff --git a/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256-por_1_2-default-caps b/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256-por_1_2-default-caps
new file mode 100644
index 0000000..509ea3b
--- /dev/null
+++ b/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256-por_1_2-default-caps
Binary files differ
diff --git a/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256_2.pk8 b/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256_2.pk8
new file mode 100644
index 0000000..5e73f27
--- /dev/null
+++ b/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256_2.pk8
Binary files differ
diff --git a/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256_2.x509.pem b/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256_2.x509.pem
new file mode 100644
index 0000000..f8e5e65
--- /dev/null
+++ b/hostsidetests/appsecurity/certs/pkgsigverify/ec-p256_2.x509.pem
@@ -0,0 +1,10 @@
+-----BEGIN CERTIFICATE-----
+MIIBbTCCAROgAwIBAgIJAIhVvR3SsrIlMAoGCCqGSM49BAMCMBIxEDAOBgNVBAMM
+B2VjLXAyNTYwHhcNMTgwNzEzMTc0MTUxWhcNMjgwNzEwMTc0MTUxWjAUMRIwEAYD
+VQQDDAllYy1wMjU2XzIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQdTMoEcq2X
+7jzs7w2pPWK0UMZ4gzOzbnVTzen3SrXfALu6a6lQ5oRh1wu8JxtiFR2tLeK/YgPN
+IHaAHHqdRCLho1AwTjAdBgNVHQ4EFgQUeZHZKwII/ESL9QbU78n/9CjLXl8wHwYD
+VR0jBBgwFoAU1BM1aLlbMBWLMiBx6oxD/1sFzMgwDAYDVR0TBAUwAwEB/zAKBggq
+hkjOPQQDAgNIADBFAiAnaauxtJ/C9TR5xK6SpmMdq/1SLJrLC7orQ+vrmcYwEQIh
+ANJg+x0fF2z5t/pgCYv9JDGfSQWj5f2hAKb+Giqxn/Ce
+-----END CERTIFICATE-----
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
index 372b77e..7717623 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
@@ -152,7 +152,7 @@
             Assert.assertNotNull("Failed to find APK for ABI " + abi, apk);
 
             // Install simple app on internal
-            new InstallMultiple().useNaturalAbi().addApk(APK).addApk(apk).run();
+            new InstallMultiple().useNaturalAbi().addFile(APK).addFile(apk).run();
             runDeviceTests(PKG, CLASS, "testDataInternal");
             runDeviceTests(PKG, CLASS, "testDataWrite");
             runDeviceTests(PKG, CLASS, "testDataRead");
@@ -165,6 +165,7 @@
             // Move app and verify
             assertSuccess(getDevice().executeShellCommand(
                     "pm move-package " + PKG + " " + vol.uuid));
+            waitForBroadcastsIdle();
             runDeviceTests(PKG, CLASS, "testDataNotInternal");
             runDeviceTests(PKG, CLASS, "testDataRead");
             runDeviceTests(PKG, CLASS, "testNative");
@@ -181,6 +182,7 @@
 
             // Move app back and verify
             assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " internal"));
+            waitForBroadcastsIdle();
             runDeviceTests(PKG, CLASS, "testDataInternal");
             runDeviceTests(PKG, CLASS, "testDataRead");
             runDeviceTests(PKG, CLASS, "testNative");
@@ -228,7 +230,7 @@
 
     private void verifyPrimaryInternal(String diskId) throws Exception {
         // Write some data to shared storage
-        new InstallMultiple().addApk(APK).run();
+        new InstallMultiple().addFile(APK).run();
         runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume");
         runDeviceTests(PKG, CLASS, "testPrimaryInternal");
         runDeviceTests(PKG, CLASS, "testPrimaryDataWrite");
@@ -243,6 +245,7 @@
         getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid, out, 2,
                 TimeUnit.HOURS, 1);
         assertSuccess(out.getOutput());
+        waitForBroadcastsIdle();
         runDeviceTests(PKG, CLASS, "testPrimaryAdopted");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
 
@@ -258,9 +261,10 @@
 
         // Move app and verify backing storage volume is same
         assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " " + vol.uuid));
+        waitForBroadcastsIdle();
+
         runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
-
         // And move back to internal
         out = new CollectingOutputReceiver();
         getDevice().executeShellCommand("pm move-primary-storage internal", out, 2,
@@ -271,13 +275,15 @@
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
 
         assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " internal"));
+        waitForBroadcastsIdle();
+
         runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
     }
 
     private void verifyPrimaryPhysical(String diskId) throws Exception {
         // Write some data to shared storage
-        new InstallMultiple().addApk(APK).run();
+        new InstallMultiple().addFile(APK).run();
         runDeviceTests(PKG, CLASS, "testPrimaryPhysical");
         runDeviceTests(PKG, CLASS, "testPrimaryDataWrite");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
@@ -324,13 +330,13 @@
 
             // Install directly onto adopted volume
             new InstallMultiple().locationAuto().forceUuid(vol.uuid)
-                    .addApk(APK).addApk(APK_mdpi).run();
+                    .addFile(APK).addFile(APK_mdpi).run();
             runDeviceTests(PKG, CLASS, "testDataNotInternal");
             runDeviceTests(PKG, CLASS, "testDensityBest1");
 
             // Now splice in an additional split which offers better resources
             new InstallMultiple().locationAuto().inheritFrom(PKG)
-                    .addApk(APK_xxhdpi).run();
+                    .addFile(APK_xxhdpi).run();
             runDeviceTests(PKG, CLASS, "testDataNotInternal");
             runDeviceTests(PKG, CLASS, "testDensityBest2");
 
@@ -352,7 +358,7 @@
             final LocalVolumeInfo vol = getAdoptionVolume();
 
             // Install directly onto adopted volume, and write data there
-            new InstallMultiple().locationAuto().forceUuid(vol.uuid).addApk(APK).run();
+            new InstallMultiple().locationAuto().forceUuid(vol.uuid).addFile(APK).run();
             runDeviceTests(PKG, CLASS, "testDataNotInternal");
             runDeviceTests(PKG, CLASS, "testDataWrite");
             runDeviceTests(PKG, CLASS, "testDataRead");
@@ -363,7 +369,7 @@
             getDevice().uninstallPackage(PKG);
 
             // Install second copy on internal, but don't write anything
-            new InstallMultiple().locationInternalOnly().addApk(APK).run();
+            new InstallMultiple().locationInternalOnly().addFile(APK).run();
             runDeviceTests(PKG, CLASS, "testDataInternal");
 
             // Kick through a remount cycle, which should purge the adopted app
@@ -443,7 +449,7 @@
     private LocalVolumeInfo waitForVolumeReady(LocalVolumeInfo vol) throws Exception {
         int attempt = 0;
         while (attempt++ < 15) {
-            if (getDevice().executeShellCommand("dumpsys package").contains(vol.volId)) {
+            if (getDevice().executeShellCommand("dumpsys package volumes").contains(vol.volId)) {
                 return vol;
             }
             Thread.sleep(1000);
@@ -451,6 +457,10 @@
         throw new AssertionError("Volume not ready " + vol.volId);
     }
 
+    private void waitForBroadcastsIdle() throws Exception {
+        getDevice().executeShellCommand("am wait-for-broadcast-idle");
+    }
+
     private void waitForInstrumentationReady() throws Exception {
         // Wait for volume ready first
         getAdoptionVolume();
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java
index 450caa5..b1c450d 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java
@@ -113,7 +113,7 @@
     @Test
     public void testAppAbleToAccessItsDataAfterForceStop() throws Exception {
         // Install AppA and verify no data stored
-        new InstallMultiple().addApk(APPA_APK).run();
+        new InstallMultiple().addFile(APPA_APK).run();
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_CE_DATA_DOES_NOT_EXIST);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_DE_DATA_DOES_NOT_EXIST);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_EXTERNAL_DIRS_DO_NOT_EXIST);
@@ -144,7 +144,7 @@
     @Test
     public void testAppAbleToAccessItsDataAfterReboot() throws Exception {
         // Install AppA and verify no data stored
-        new InstallMultiple().addApk(APPA_APK).run();
+        new InstallMultiple().addFile(APPA_APK).run();
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_CE_DATA_DOES_NOT_EXIST);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_DE_DATA_DOES_NOT_EXIST);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_EXTERNAL_DIRS_DO_NOT_EXIST);
@@ -185,8 +185,8 @@
     @Test
     public void testDirectBootModeWorks() throws Exception {
         // Install AppA and verify no data stored
-        new InstallMultiple().addApk(APP_DIRECT_BOOT_A_APK).run();
-        new InstallMultiple().addApk(APPB_APK).run();
+        new InstallMultiple().addFile(APP_DIRECT_BOOT_A_APK).run();
+        new InstallMultiple().addFile(APPB_APK).run();
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_CE_DATA_DOES_NOT_EXIST);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_DE_DATA_DOES_NOT_EXIST);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_EXTERNAL_DIRS_DO_NOT_EXIST);
@@ -272,13 +272,13 @@
     @Test
     public void testAppNotAbleToAccessItsDataAfterReinstall() throws Exception {
         // Install AppA create CE DE data
-        new InstallMultiple().addApk(APPA_APK).run();
+        new InstallMultiple().addFile(APPA_APK).run();
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CREATE_CE_DE_DATA);
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CREATE_EXTERNAL_DIRS);
 
         // Reinstall AppA
         getDevice().uninstallPackage(APPA_PKG);
-        new InstallMultiple().addApk(APPA_APK).run();
+        new InstallMultiple().addFile(APPA_APK).run();
 
         // Verify CE, DE and external data are removed
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CHECK_CE_DATA_DOES_NOT_EXIST);
@@ -288,16 +288,16 @@
 
     @Test
     public void testNormalProcessCannotAccessOtherAppDataDir() throws Exception {
-        new InstallMultiple().addApk(APPA_APK).run();
-        new InstallMultiple().addApk(APPB_APK).run();
+        new InstallMultiple().addFile(APPA_APK).run();
+        new InstallMultiple().addFile(APPB_APK).run();
 
         runDeviceTests(APPB_PKG, APPB_CLASS, APPB_METHOD_CAN_NOT_ACCESS_APPA_DIR);
     }
 
     @Test
     public void testSharedAppAbleToAccessOtherAppDataDir() throws Exception {
-        new InstallMultiple().addApk(APP_SHARED_A_APK).run();
-        new InstallMultiple().addApk(APP_SHARED_B_APK).run();
+        new InstallMultiple().addFile(APP_SHARED_A_APK).run();
+        new InstallMultiple().addFile(APP_SHARED_B_APK).run();
 
         runDeviceTests(APPB_PKG, APPB_CLASS, APPB_METHOD_CAN_ACCESS_APPA_DIR);
     }
@@ -306,8 +306,8 @@
     public void testNormalProcessCannotAccessOtherAppExternalDataDir() throws Exception {
         assumeThatFuseDataIsolationIsEnabled(getDevice());
 
-        new InstallMultiple().addApk(APPA_APK).run();
-        new InstallMultiple().addApk(APPB_APK).run();
+        new InstallMultiple().addFile(APPA_APK).run();
+        new InstallMultiple().addFile(APPB_APK).run();
 
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CREATE_EXTERNAL_DIRS);
         runDeviceTests(APPB_PKG, APPB_CLASS, APPB_METHOD_CAN_NOT_ACCESS_APPA_EXTERNAL_DIRS);
@@ -315,8 +315,8 @@
 
     @Test
     public void testSharedAppAbleToAccessOtherAppExternalDataDir() throws Exception {
-        new InstallMultiple().addApk(APP_SHARED_A_APK).run();
-        new InstallMultiple().addApk(APP_SHARED_B_APK).run();
+        new InstallMultiple().addFile(APP_SHARED_A_APK).run();
+        new InstallMultiple().addFile(APP_SHARED_B_APK).run();
 
         runDeviceTests(APPA_PKG, APPA_CLASS, APPA_METHOD_CREATE_EXTERNAL_DIRS);
         runDeviceTests(APPB_PKG, APPB_CLASS, APPB_METHOD_CAN_ACCESS_APPA_EXTERNAL_DIRS);
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java
index 008eea4..0f43a54 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java
@@ -108,8 +108,8 @@
             getDevice().uninstallPackage(SIMPLE_APP_PKG);
             getDevice().uninstallPackage(SIMPLE_APP_DIFF_CERT_APK);
 
-            new InstallMultiple(instant).addApk(SIMPLE_APP_APK).run();
-            new InstallMultiple(instant).addApk(SIMPLE_APP_DIFF_CERT_APK)
+            new InstallMultiple(instant).addFile(SIMPLE_APP_APK).run();
+            new InstallMultiple(instant).addFile(SIMPLE_APP_DIFF_CERT_APK)
                     .runExpectingFailure("INSTALL_FAILED_UPDATE_INCOMPATIBLE");
         } finally {
             getDevice().uninstallPackage(SIMPLE_APP_PKG);
@@ -137,10 +137,10 @@
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
             getDevice().uninstallPackage(APP_ACCESS_DATA_PKG);
 
-            new InstallMultiple().addApk(APP_WITH_DATA_APK).run();
+            new InstallMultiple().addFile(APP_WITH_DATA_APK).run();
             runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD);
 
-            new InstallMultiple(instant).addApk(APP_ACCESS_DATA_APK).run();
+            new InstallMultiple(instant).addFile(APP_ACCESS_DATA_APK).run();
             runDeviceTests(APP_ACCESS_DATA_PKG, null, null, instant);
         } finally {
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
@@ -166,13 +166,13 @@
         try {
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
 
-            new InstallMultiple(instant).addApk(APP_WITH_DATA_APK).run();
+            new InstallMultiple(instant).addFile(APP_WITH_DATA_APK).run();
             runDeviceTests(
                     APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD);
 
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
 
-            new InstallMultiple(instant).addApk(APP_WITH_DATA_APK).run();
+            new InstallMultiple(instant).addFile(APP_WITH_DATA_APK).run();
             runDeviceTests(
                     APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CHECK_NOEXIST_METHOD);
         } finally {
@@ -203,8 +203,8 @@
             getDevice().uninstallPackage(TARGET_INSTRUMENT_PKG);
             getDevice().uninstallPackage(INSTRUMENT_DIFF_CERT_PKG);
 
-            new InstallMultiple(targetInstant).addApk(TARGET_INSTRUMENT_APK).run();
-            new InstallMultiple(instrumentInstant).addApk(INSTRUMENT_DIFF_CERT_APK).run();
+            new InstallMultiple(targetInstant).addFile(TARGET_INSTRUMENT_APK).run();
+            new InstallMultiple(instrumentInstant).addFile(INSTRUMENT_DIFF_CERT_APK).run();
 
             // if we've installed either the instrumentation or target as an instant application,
             // starting an instrumentation will just fail instead of throwing a security exception
@@ -234,10 +234,10 @@
             getDevice().uninstallPackage(DECLARE_PERMISSION_COMPAT_PKG);
             getDevice().uninstallPackage(PERMISSION_DIFF_CERT_PKG);
 
-            new InstallMultiple().addApk(DECLARE_PERMISSION_APK).run();
-            new InstallMultiple().addApk(DECLARE_PERMISSION_COMPAT_APK).run();
+            new InstallMultiple().addFile(DECLARE_PERMISSION_APK).run();
+            new InstallMultiple().addFile(DECLARE_PERMISSION_COMPAT_APK).run();
 
-            new InstallMultiple().addApk(PERMISSION_DIFF_CERT_APK).run();
+            new InstallMultiple().addFile(PERMISSION_DIFF_CERT_APK).run();
 
             // Enable alert window permission so it can start activity in background
             enableAlertWindowAppOp(DECLARE_PERMISSION_PKG);
@@ -256,8 +256,8 @@
     @Test
     public void rebootWithDuplicatePermission() throws Exception {
         try {
-            new InstallMultiple(false).addApk(DECLARE_PERMISSION_APK).run();
-            new InstallMultiple(false).addApk(DUPLICATE_DECLARE_PERMISSION_APK).run();
+            new InstallMultiple(false).addFile(DECLARE_PERMISSION_APK).run();
+            new InstallMultiple(false).addFile(DUPLICATE_DECLARE_PERMISSION_APK).run();
 
             // Enable alert window permission so it can start activity in background
             enableAlertWindowAppOp(DECLARE_PERMISSION_PKG);
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AuthBoundKeyTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AuthBoundKeyTest.java
index 963852d..13773bc 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AuthBoundKeyTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AuthBoundKeyTest.java
@@ -53,7 +53,7 @@
             throws DeviceNotAvailableException, FileNotFoundException {
         assumeTrue("Device does not support secure lock",
                    getDevice().hasFeature("android.software.secure_lock_screen"));
-        new InstallMultiple().addApk(APK).run();
+        new InstallMultiple().addFile(APK).run();
         getDevice().executeShellCommand("cmd lock_settings set-pin 1234");
         runDeviceTests(PKG, CLASS, "testGenerateAuthBoundKey");
         getDevice().executeShellCommand("cmd lock_settings clear --old 1234");
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseAppSecurityTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseAppSecurityTest.java
index 65bbd31..24cc5ae 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseAppSecurityTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseAppSecurityTest.java
@@ -59,7 +59,7 @@
             userId = mPrimaryUserId;
         }
         new InstallMultiple(instant)
-                .addApk(apk)
+                .addFile(apk)
                 .allowTest()
                 .forUser(userId)
                 .run();
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseInstallMultiple.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseInstallMultiple.java
index 23f1840..cb170c9 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseInstallMultiple.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/BaseInstallMultiple.java
@@ -62,10 +62,6 @@
         return (T) this;
     }
 
-    T addApk(String apk) throws FileNotFoundException {
-        return addFile(apk);
-    }
-
     T addFile(String file) throws FileNotFoundException {
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
         mFiles.add(buildHelper.getTestFile(file));
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
index 429f942..b8bb01f 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
@@ -145,8 +145,8 @@
         boolean doTest = true;
         try {
             // Set up test app and secure lock screens
-            new InstallMultiple().addApk(APK).run();
-            new InstallMultiple().addApk(OTHER_APK).run();
+            new InstallMultiple().addFile(APK).run();
+            new InstallMultiple().addFile(OTHER_APK).run();
 
             // To receive boot broadcasts, kick our other app out of stopped state
             getDevice().executeShellCommand("am start -a android.intent.action.MAIN"
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
index b150b12..7472748 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
@@ -547,33 +547,33 @@
 
     private void installApp(String apk) throws Exception {
         new InstallMultiple(false /* instant */)
-                .addApk(apk)
+                .addFile(apk)
                 .run();
     }
 
     private void installApp(String apk, String installer) throws Exception {
         new InstallMultiple(false /* instant */)
-                .addApk(apk)
+                .addFile(apk)
                 .addArg("-i " + installer)
                 .run();
     }
 
     private void installEphemeralApp(String apk) throws Exception {
         new InstallMultiple(true /* instant */)
-                .addApk(apk)
+                .addFile(apk)
                 .run();
     }
 
     private void installEphemeralApp(String apk, String installer) throws Exception {
         new InstallMultiple(true /* instant */)
-                .addApk(apk)
+                .addFile(apk)
                 .addArg("-i " + installer)
                 .run();
     }
 
     private void installFullApp(String apk) throws Exception {
         new InstallMultiple(false /* instant */)
-                .addApk(apk)
+                .addFile(apk)
                 .addArg("--full")
                 .run();
     }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/IsolatedSplitsTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/IsolatedSplitsTests.java
index 85609f9..4ed56d4 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/IsolatedSplitsTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/IsolatedSplitsTests.java
@@ -69,7 +69,7 @@
     }
 
     private void testInstallBase(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).run();
+        new InstallMultiple(instant).addFile(APK_BASE).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadDefault");
     }
 
@@ -86,7 +86,7 @@
     }
 
     private void testInstallBaseAndConfigSplit(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_BASE_pl).run();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_BASE_pl).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadPolishLocale");
     }
 
@@ -103,7 +103,7 @@
     }
 
     private void testInstallMissingDependency(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_FEATURE_B).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_FEATURE_B).runExpectingFailure();
     }
 
     @Test
@@ -114,7 +114,7 @@
     }
 
     private void testInstallOneFeatureSplit(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_FEATURE_A).run();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_FEATURE_A).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadDefault");
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS,
                 "shouldLoadFeatureADefault");
@@ -135,8 +135,8 @@
     }
 
     private void testInstallOneFeatureSplitAndConfigSplits(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_BASE_pl)
-                .addApk(APK_FEATURE_A_pl).run();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_FEATURE_A).addFile(APK_BASE_pl)
+                .addFile(APK_FEATURE_A_pl).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadPolishLocale");
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS,
                 "shouldLoadFeatureAPolishLocale");
@@ -151,7 +151,7 @@
 
     private void testInstallDependentFeatureSplits(boolean instant) throws Exception {
         new InstallMultiple(instant)
-                .addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_FEATURE_B).run();
+                .addFile(APK_BASE).addFile(APK_FEATURE_A).addFile(APK_FEATURE_B).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadDefault");
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS,
                 "shouldLoadFeatureADefault");
@@ -175,8 +175,8 @@
 
     private void testInstallDependentFeatureSplitsAndConfigSplits(boolean instant)
             throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_FEATURE_B)
-                .addApk(APK_BASE_pl).addApk(APK_FEATURE_A_pl).addApk(APK_FEATURE_B_pl).run();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_FEATURE_A).addFile(APK_FEATURE_B)
+                .addFile(APK_BASE_pl).addFile(APK_FEATURE_A_pl).addFile(APK_FEATURE_B_pl).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadPolishLocale");
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS,
                 "shouldLoadFeatureAPolishLocale");
@@ -192,8 +192,8 @@
     }
 
     private void testInstallAllFeatureSplits(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_FEATURE_B)
-                .addApk(APK_FEATURE_C).run();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_FEATURE_A).addFile(APK_FEATURE_B)
+                .addFile(APK_FEATURE_C).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadDefault");
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS,
                 "shouldLoadFeatureADefault");
@@ -218,9 +218,9 @@
     }
 
     private void testInstallAllFeatureSplitsAndConfigSplits(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_FEATURE_B)
-                .addApk(APK_FEATURE_C).addApk(APK_BASE_pl).addApk(APK_FEATURE_A_pl)
-                .addApk(APK_FEATURE_C_pl).run();
+        new InstallMultiple(instant).addFile(APK_BASE).addFile(APK_FEATURE_A).addFile(APK_FEATURE_B)
+                .addFile(APK_FEATURE_C).addFile(APK_BASE_pl).addFile(APK_FEATURE_A_pl)
+                .addFile(APK_FEATURE_C_pl).run();
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS, "shouldLoadDefault");
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, TEST_CLASS,
                 "shouldLoadFeatureADefault");
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/MajorVersionTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/MajorVersionTest.java
index ec113cb..00dac73 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/MajorVersionTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/MajorVersionTest.java
@@ -60,7 +60,7 @@
         testInstallMinorVersion(true);
     }
     private void testInstallMinorVersion(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_000000000000ffff).run();
+        new InstallMultiple(instant).addFile(APK_000000000000ffff).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
     }
@@ -76,7 +76,7 @@
         testInstallMajorVersion(true);
     }
     private void testInstallMajorVersion(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_000000ff00000000).run();
+        new InstallMultiple(instant).addFile(APK_000000ff00000000).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
     }
@@ -92,16 +92,16 @@
         testInstallUpdateAcrossMinorMajorVersion(true);
     }
     private void testInstallUpdateAcrossMinorMajorVersion(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_000000000000ffff).run();
+        new InstallMultiple(instant).addFile(APK_000000000000ffff).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
-        new InstallMultiple(instant).addApk(APK_00000000ffffffff).run();
+        new InstallMultiple(instant).addFile(APK_00000000ffffffff).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
-        new InstallMultiple(instant).addApk(APK_000000ff00000000).run();
+        new InstallMultiple(instant).addFile(APK_000000ff00000000).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
-        new InstallMultiple(instant).addApk(APK_000000ffffffffff).run();
+        new InstallMultiple(instant).addFile(APK_000000ffffffffff).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
     }
@@ -117,18 +117,18 @@
         testInstallDowngradeAcrossMajorMinorVersion(true);
     }
     private void testInstallDowngradeAcrossMajorMinorVersion(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_000000ffffffffff).run();
+        new InstallMultiple(instant).addFile(APK_000000ffffffffff).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
-        new InstallMultiple(instant).addApk(APK_00000000ffffffff)
+        new InstallMultiple(instant).addFile(APK_00000000ffffffff)
                 .runExpectingFailure("INSTALL_FAILED_VERSION_DOWNGRADE");
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
-        new InstallMultiple(instant).addApk(APK_000000ff00000000)
+        new InstallMultiple(instant).addFile(APK_000000ff00000000)
                 .runExpectingFailure("INSTALL_FAILED_VERSION_DOWNGRADE");
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
-        new InstallMultiple(instant).addApk(APK_000000000000ffff)
+        new InstallMultiple(instant).addFile(APK_000000000000ffff)
                 .runExpectingFailure("INSTALL_FAILED_VERSION_DOWNGRADE");
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
         runVersionDeviceTests("testCheckVersion");
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java
index 72a76641..21f8585 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java
@@ -69,7 +69,7 @@
 
     @Before
     public void setUp() throws Exception {
-        new InstallMultiple().addApk(TEST_APP_APK).run();
+        new InstallMultiple().addFile(TEST_APP_APK).run();
     }
 
     @After
@@ -121,8 +121,8 @@
             assertFalse(getDevice().getInstalledPackageNames().contains(OVERLAY_ALL_PACKAGE));
             assertFalse(getDevice().getInstalledPackageNames().contains(overlayPackage));
 
-            new InstallMultiple().addApk(TARGET_OVERLAYABLE_APK).run();
-            new InstallMultiple().addApk(overlayApk).run();
+            new InstallMultiple().addFile(TARGET_OVERLAYABLE_APK).run();
+            new InstallMultiple().addFile(overlayApk).run();
 
             waitForOverlayState(overlayPackage, STATE_NO_IDMAP);
             getDevice().executeShellCommand("cmd overlay enable  --user current " + overlayPackage);
@@ -142,8 +142,8 @@
             assertFalse(getDevice().getInstalledPackageNames().contains(TARGET_PACKAGE));
             assertFalse(getDevice().getInstalledPackageNames().contains(overlayPackage));
 
-            new InstallMultiple().addApk(overlayApk).run();
-            new InstallMultiple().addApk(targetApk).run();
+            new InstallMultiple().addFile(overlayApk).run();
+            new InstallMultiple().addFile(targetApk).run();
 
             waitForOverlayState(overlayPackage, STATE_DISABLED);
             getDevice().executeShellCommand("cmd overlay enable --user current " + overlayPackage);
@@ -167,7 +167,7 @@
             assertFalse(getDevice().getInstalledPackageNames().contains(OVERLAY_ANDROID_PACKAGE));
 
             // Try to install the overlay, but expect an error.
-            new InstallMultiple().addApk(OVERLAY_ANDROID_APK).runExpectingFailure();
+            new InstallMultiple().addFile(OVERLAY_ANDROID_APK).runExpectingFailure();
 
             // The install should have failed.
             assertFalse(getDevice().getInstalledPackageNames().contains(OVERLAY_ANDROID_PACKAGE));
@@ -191,7 +191,7 @@
             assertFalse(getDevice().getInstalledPackageNames().contains(OVERLAY_ALL_PACKAGE));
 
             // Try to install the overlay, but expect an error.
-            new InstallMultiple().addApk(OVERLAY_ALL_PIE_APK).runExpectingFailure();
+            new InstallMultiple().addFile(OVERLAY_ALL_PIE_APK).runExpectingFailure();
 
             // The install should have failed.
             assertFalse(getDevice().getInstalledPackageNames().contains(OVERLAY_ALL_PACKAGE));
@@ -217,8 +217,8 @@
             assertFalse(getDevice().getInstalledPackageNames().contains(OVERLAY_ALL_PACKAGE));
 
             // Try to install the overlay, but expect an error.
-            new InstallMultiple().addApk(TARGET_NO_OVERLAYABLE_APK).run();
-            new InstallMultiple().addApk(
+            new InstallMultiple().addFile(TARGET_NO_OVERLAYABLE_APK).run();
+            new InstallMultiple().addFile(
                     OVERLAY_ALL_NO_NAME_DIFFERENT_CERT_APK).runExpectingFailure();
 
             // The install should have failed.
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageResolutionHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageResolutionHostTest.java
index e081d62..b0915b7 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageResolutionHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageResolutionHostTest.java
@@ -58,7 +58,7 @@
     }
     private void testResolveOrderedActivity(boolean instant) throws Exception {
         new InstallMultiple(instant)
-                .addApk(TINY_APK)
+                .addFile(TINY_APK)
                 .run();
         Utils.runDeviceTests(getDevice(), TINY_PKG,
                 ".PackageResolutionTest", "queryActivityOrdered");
@@ -76,7 +76,7 @@
     }
     private void testResolveOrderedService(boolean instant) throws Exception {
         new InstallMultiple(instant)
-                .addApk(TINY_APK)
+                .addFile(TINY_APK)
                 .run();
         Utils.runDeviceTests(getDevice(), TINY_PKG,
                 ".PackageResolutionTest", "queryServiceOrdered");
@@ -94,7 +94,7 @@
     }
     private void testResolveOrderedReceiver(boolean instant) throws Exception {
         new InstallMultiple(instant)
-                .addApk(TINY_APK)
+                .addFile(TINY_APK)
                 .run();
         Utils.runDeviceTests(getDevice(), TINY_PKG,
                 ".PackageResolutionTest", "queryReceiverOrdered");
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java
index 23fcb2a..b4a1064 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/PkgInstallSignatureVerificationTest.java
@@ -714,6 +714,27 @@
                 "testGetSigningCertificatesShowsAll");
     }
 
+    public void testInstallV3KeyRotationGetApkContentsSigners() throws Exception {
+        // The GET_SIGNING_CERTIFICATES flag results in a PackageInfo object returned with a
+        // SigningInfo instance that can be used to query all certificates in the lineage or only
+        // the current signer(s) via getApkContentsSigners. This test verifies when a V3 signed
+        // package with a rotated key is queried getApkContentsSigners only returns the current
+        // signer.
+        installApkFromBuild("v3-ec-p256-with-por_1_2-default-caps.apk");
+        Utils.runDeviceTests(
+                getDevice(), DEVICE_TESTS_PKG, DEVICE_TESTS_CLASS,
+                "testGetApkContentsSignersShowsCurrent");
+    }
+
+    public void testInstallV2MultipleSignersGetApkContentsSigners() throws Exception {
+        // Similar to the above test, but verifies when an APK is signed with two V2 signers
+        // getApkContentsSigners returns both of the V2 signers.
+        installApkFromBuild("v1v2-ec-p256-two-signers.apk");
+        Utils.runDeviceTests(
+                getDevice(), DEVICE_TESTS_PKG, DEVICE_TESTS_CLASS,
+                "testGetApkContentsSignersShowsMultipleSigners");
+    }
+
     public void testInstallV3KeyRotationHasSigningCertificate() throws Exception {
         // tests that hasSigningCertificate() recognizes past and current signing certs
         assertInstallSucceeds("v3-rsa-pkcs1-sha256-2048-2-with-por_1_2-full-caps.apk");
@@ -894,10 +915,14 @@
     }
 
     private void installDeviceTestPkg() throws Exception {
+        installApkFromBuild(DEVICE_TESTS_APK);
+    }
+
+    private void installApkFromBuild(String apkName) throws Exception {
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
-        File apk = buildHelper.getTestFile(DEVICE_TESTS_APK);
-        String result = getDevice().installPackage(apk, true);
-        assertNull("failed to install " + DEVICE_TESTS_APK + ", Reason: " + result, result);
+        File apk = buildHelper.getTestFile(apkName);
+        String result = getDevice().installPackage(apk, true, INSTALL_ARG_FORCE_QUERYABLE);
+        assertNull("failed to install " + apkName + ", Reason: " + result, result);
     }
 
     private String installPackageFromResource(String apkFilenameInResources, boolean ephemeral)
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java
index dcbe8cb..1128c8f 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java
@@ -331,8 +331,8 @@
     }
 
     private void installTestPackages() throws Exception {
-        new InstallMultiple().addApk(APK).run();
-        new InstallMultiple().addApk(OTHER_APK).run();
+        new InstallMultiple().addFile(APK).run();
+        new InstallMultiple().addFile(OTHER_APK).run();
     }
 
     private void removeTestPackages() throws DeviceNotAvailableException {
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java
index 7477721..695ed26 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java
@@ -41,8 +41,8 @@
 
     @Before
     public void setup() throws Exception {
-        new InstallMultiple().addApk(SESSION_INSPECTOR_A_APK).run();
-        new InstallMultiple().addApk(SESSION_INSPECTOR_B_APK).run();
+        new InstallMultiple().addFile(SESSION_INSPECTOR_A_APK).run();
+        new InstallMultiple().addFile(SESSION_INSPECTOR_B_APK).run();
     }
 
     @After
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/SharedUserIdTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/SharedUserIdTest.java
index 78e4b5e..8d1024a 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/SharedUserIdTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/SharedUserIdTest.java
@@ -62,9 +62,9 @@
             getDevice().uninstallPackage(SHARED_UI_PKG);
             getDevice().uninstallPackage(SHARED_UI_DIFF_CERT_PKG);
 
-            new InstallMultiple().addApk(SHARED_UI_APK).run();
+            new InstallMultiple().addFile(SHARED_UI_APK).run();
             runDeviceTests(SHARED_UI_PKG, SHARED_UI_TEST_CLASS, SHARED_UI_TEST_METHOD);
-            new InstallMultiple().addApk(SHARED_UI_DIFF_CERT_APK)
+            new InstallMultiple().addFile(SHARED_UI_DIFF_CERT_APK)
                     .runExpectingFailure("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE");
             runDeviceTests(SHARED_UI_PKG, SHARED_UI_TEST_CLASS, SHARED_UI_TEST_METHOD);
         } finally {
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/SplitTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/SplitTests.java
index b1128a9..3fba518 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/SplitTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/SplitTests.java
@@ -112,7 +112,7 @@
         testSingleBase(true);
     }
     private void testSingleBase(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).run();
+        new InstallMultiple(instant).addFile(APK).run();
         runDeviceTests(PKG, CLASS, "testSingleBase");
     }
 
@@ -127,7 +127,7 @@
         testDensitySingle(true);
     }
     private void testDensitySingle(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_mdpi).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_mdpi).run();
         runDeviceTests(PKG, CLASS, "testDensitySingle");
     }
 
@@ -142,8 +142,8 @@
         testDensityAll(true);
     }
     private void testDensityAll(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_mdpi).addApk(APK_hdpi).addApk(APK_xhdpi)
-                .addApk(APK_xxhdpi).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_mdpi).addFile(APK_hdpi).addFile(APK_xhdpi)
+                .addFile(APK_xxhdpi).run();
         runDeviceTests(PKG, CLASS, "testDensityAll");
     }
 
@@ -162,11 +162,11 @@
         testDensityBest(true);
     }
     private void testDensityBest(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_mdpi).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_mdpi).run();
         runDeviceTests(PKG, CLASS, "testDensityBest1");
 
         // Now splice in an additional split which offers better resources
-        new InstallMultiple(instant).inheritFrom(PKG).addApk(APK_xxhdpi).run();
+        new InstallMultiple(instant).inheritFrom(PKG).addFile(APK_xxhdpi).run();
         runDeviceTests(PKG, CLASS, "testDensityBest2");
     }
 
@@ -185,7 +185,7 @@
         testApi(true);
     }
     private void testApi(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_v7).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_v7).run();
         runDeviceTests(PKG, CLASS, "testApi");
     }
 
@@ -200,7 +200,7 @@
         testLocale(true);
     }
     private void testLocale(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_de).addApk(APK_fr).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_de).addFile(APK_fr).run();
         runDeviceTests(PKG, CLASS, "testLocale");
     }
 
@@ -223,7 +223,7 @@
         final String apk = ABI_TO_APK.get(abi);
         assertNotNull("Failed to find APK for ABI " + abi, apk);
 
-        new InstallMultiple(instant).addApk(APK).addApk(apk).run();
+        new InstallMultiple(instant).addFile(APK).addFile(apk).run();
         runDeviceTests(PKG, CLASS, "testNative");
     }
 
@@ -248,7 +248,7 @@
         final String apk = ABI_TO_APK.get(abi);
         assertNotNull("Failed to find APK for ABI " + abi, apk);
 
-        new InstallMultiple(instant).useNaturalAbi().addApk(APK).addApk(apk).run();
+        new InstallMultiple(instant).useNaturalAbi().addFile(APK).addFile(apk).run();
         runDeviceTests(PKG, CLASS, "testNative");
     }
 
@@ -267,9 +267,9 @@
         testNativeAll(true);
     }
     private void testNativeAll(boolean instant) throws Exception {
-        final InstallMultiple inst = new InstallMultiple(instant).addApk(APK);
+        final InstallMultiple inst = new InstallMultiple(instant).addFile(APK);
         for (String apk : ABI_TO_APK.values()) {
-            inst.addApk(apk);
+            inst.addFile(apk);
         }
         inst.run();
         runDeviceTests(PKG, CLASS, "testNative");
@@ -292,9 +292,9 @@
         testNativeAllNatural(true);
     }
     private void testNativeAllNatural(boolean instant) throws Exception {
-        final InstallMultiple inst = new InstallMultiple(instant).useNaturalAbi().addApk(APK);
+        final InstallMultiple inst = new InstallMultiple(instant).useNaturalAbi().addFile(APK);
         for (String apk : ABI_TO_APK.values()) {
-            inst.addApk(apk);
+            inst.addFile(apk);
         }
         inst.run();
         runDeviceTests(PKG, CLASS, "testNative");
@@ -311,7 +311,7 @@
         testDuplicateBase(true);
     }
     private void testDuplicateBase(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).addFile(APK).runExpectingFailure();
     }
 
     @Test
@@ -325,7 +325,7 @@
         testDuplicateSplit(true);
     }
     private void testDuplicateSplit(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_v7).addApk(APK_v7).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_v7).addFile(APK_v7).runExpectingFailure();
     }
 
     @Test
@@ -339,7 +339,7 @@
         testDiffCert(true);
     }
     private void testDiffCert(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_DIFF_CERT_v7).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_DIFF_CERT_v7).runExpectingFailure();
     }
 
     @Test
@@ -353,8 +353,8 @@
         testDiffCertInherit(true);
     }
     private void testDiffCertInherit(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).run();
-        new InstallMultiple(instant).inheritFrom(PKG).addApk(APK_DIFF_CERT_v7).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).run();
+        new InstallMultiple(instant).inheritFrom(PKG).addFile(APK_DIFF_CERT_v7).runExpectingFailure();
     }
 
     @Test
@@ -368,7 +368,7 @@
         testDiffVersion(true);
     }
     private void testDiffVersion(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_DIFF_VERSION_v7).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_DIFF_VERSION_v7).runExpectingFailure();
     }
 
     @Test
@@ -382,8 +382,8 @@
         testDiffVersionInherit(true);
     }
     private void testDiffVersionInherit(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).run();
-        new InstallMultiple(instant).inheritFrom(PKG).addApk(APK_DIFF_VERSION_v7).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).run();
+        new InstallMultiple(instant).inheritFrom(PKG).addFile(APK_DIFF_VERSION_v7).runExpectingFailure();
     }
 
     @Test
@@ -397,7 +397,7 @@
         testDiffRevision(true);
     }
     private void testDiffRevision(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_DIFF_REVISION_v7).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_DIFF_REVISION_v7).run();
         runDeviceTests(PKG, CLASS, "testRevision0_12");
     }
 
@@ -412,9 +412,9 @@
         testDiffRevisionInheritBase(true);
     }
     private void testDiffRevisionInheritBase(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_v7).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_v7).run();
         runDeviceTests(PKG, CLASS, "testRevision0_0");
-        new InstallMultiple(instant).inheritFrom(PKG).addApk(APK_DIFF_REVISION_v7).run();
+        new InstallMultiple(instant).inheritFrom(PKG).addFile(APK_DIFF_REVISION_v7).run();
         runDeviceTests(PKG, CLASS, "testRevision0_12");
     }
 
@@ -429,9 +429,9 @@
         testDiffRevisionInheritSplit(true);
     }
     private void testDiffRevisionInheritSplit(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_v7).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_v7).run();
         runDeviceTests(PKG, CLASS, "testRevision0_0");
-        new InstallMultiple(instant).inheritFrom(PKG).addApk(APK_DIFF_REVISION).run();
+        new InstallMultiple(instant).inheritFrom(PKG).addFile(APK_DIFF_REVISION).run();
         runDeviceTests(PKG, CLASS, "testRevision12_0");
     }
 
@@ -446,8 +446,8 @@
         testDiffRevisionDowngrade(true);
     }
     private void testDiffRevisionDowngrade(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_DIFF_REVISION_v7).run();
-        new InstallMultiple(instant).inheritFrom(PKG).addApk(APK_v7).runExpectingFailure();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_DIFF_REVISION_v7).run();
+        new InstallMultiple(instant).inheritFrom(PKG).addFile(APK_v7).runExpectingFailure();
     }
 
     @Test
@@ -461,7 +461,7 @@
         testFeatureBase(true);
     }
     private void testFeatureBase(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_FEATURE).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_FEATURE).run();
         runDeviceTests(PKG, CLASS, "testFeatureBase");
     }
 
@@ -476,7 +476,7 @@
         testFeatureApi(true);
     }
     private void testFeatureApi(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).addApk(APK_FEATURE).addApk(APK_FEATURE_v7).run();
+        new InstallMultiple(instant).addFile(APK).addFile(APK_FEATURE).addFile(APK_FEATURE_v7).run();
         runDeviceTests(PKG, CLASS, "testFeatureApi");
     }
 
@@ -506,14 +506,14 @@
         // always install as a full app; we're testing that the instant app can be
         // updated without restarting and need a broadcast receiver to ensure the
         // correct behaviour. So, this component must be visible to instant apps.
-        new InstallMultiple().addApk(APK).run();
+        new InstallMultiple().addFile(APK).run();
 
-        new InstallMultiple(instant).addApk(APK_NO_RESTART_BASE).run();
+        new InstallMultiple(instant).addFile(APK_NO_RESTART_BASE).run();
         runDeviceTests(PKG, CLASS, "testBaseInstalled", instant);
         new InstallMultiple(instant)
                 .addArg("--dont-kill")
                 .inheritFrom(PKG_NO_RESTART)
-                .addApk(APK_NO_RESTART_FEATURE)
+                .addFile(APK_NO_RESTART_FEATURE)
                 .run();
         runDeviceTests(PKG, CLASS, "testFeatureInstalled", instant);
     }
@@ -529,7 +529,7 @@
         testSingleBase(true);
     }
     private void testRequiredSplitMissing(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_NEED_SPLIT_BASE)
+        new InstallMultiple(instant).addFile(APK_NEED_SPLIT_BASE)
                 .runExpectingFailure("INSTALL_FAILED_MISSING_SPLIT");
     }
 
@@ -544,7 +544,7 @@
         testSingleBase(true);
     }
     private void testRequiredSplitInstalledFeature(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_NEED_SPLIT_BASE).addApk(APK_NEED_SPLIT_FEATURE)
+        new InstallMultiple(instant).addFile(APK_NEED_SPLIT_BASE).addFile(APK_NEED_SPLIT_FEATURE)
                 .run();
     }
 
@@ -559,7 +559,7 @@
         testSingleBase(true);
     }
     private void testRequiredSplitInstalledConfig(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_NEED_SPLIT_BASE).addApk(APK_NEED_SPLIT_CONFIG)
+        new InstallMultiple(instant).addFile(APK_NEED_SPLIT_BASE).addFile(APK_NEED_SPLIT_CONFIG)
                 .run();
     }
 
@@ -576,9 +576,9 @@
     private void testRequiredSplitRemoved(boolean instant) throws Exception {
         // start with a base and two splits
         new InstallMultiple(instant)
-                .addApk(APK_NEED_SPLIT_BASE)
-                .addApk(APK_NEED_SPLIT_FEATURE)
-                .addApk(APK_NEED_SPLIT_CONFIG)
+                .addFile(APK_NEED_SPLIT_BASE)
+                .addFile(APK_NEED_SPLIT_FEATURE)
+                .addFile(APK_NEED_SPLIT_CONFIG)
                 .run();
         // it's okay to remove one of the splits
         new InstallMultiple(instant).inheritFrom(PKG).removeSplit("split_feature").run();
@@ -601,9 +601,9 @@
         testClearCodeCache(true);
     }
     private void testClearCodeCache(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK).run();
+        new InstallMultiple(instant).addFile(APK).run();
         runDeviceTests(PKG, CLASS, "testCodeCacheWrite");
-        new InstallMultiple(instant).addArg("-r").addApk(APK_DIFF_VERSION).run();
+        new InstallMultiple(instant).addArg("-r").addFile(APK_DIFF_VERSION).run();
         runDeviceTests(PKG, CLASS, "testCodeCacheRead");
     }
 }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/UseEmbeddedDexTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/UseEmbeddedDexTest.java
index 78f0fef..42170cd 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/UseEmbeddedDexTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/UseEmbeddedDexTest.java
@@ -37,35 +37,35 @@
 
     @Test
     public void testCanonicalInstall() throws Exception {
-        new InstallMultiple().addApk(APK_CANONICAL).run();
+        new InstallMultiple().addFile(APK_CANONICAL).run();
     }
 
     @Test
     public void testBadInstallWithCompressedDex() throws Exception {
-        new InstallMultiple().addApk(APK_DEX_COMPRESSED).runExpectingFailure();
+        new InstallMultiple().addFile(APK_DEX_COMPRESSED).runExpectingFailure();
     }
 
     @Test
     public void testCanonicalInstallWithSplit() throws Exception {
-        new InstallMultiple().addApk(APK_CANONICAL).addApk(APK_SPLIT_CANONICAL).run();
+        new InstallMultiple().addFile(APK_CANONICAL).addFile(APK_SPLIT_CANONICAL).run();
     }
 
     @Test
     public void testBadInstallWithDexCompressedSplit() throws Exception {
-        new InstallMultiple().addApk(APK_CANONICAL).addApk(APK_SPLIT_COMPRESSED_DEX)
+        new InstallMultiple().addFile(APK_CANONICAL).addFile(APK_SPLIT_COMPRESSED_DEX)
                 .runExpectingFailure();
     }
 
     @Test
     public void testCanonicalInstallWithBaseThenSplit() throws Exception {
-        new InstallMultiple().addApk(APK_CANONICAL).run();
-        new InstallMultiple().inheritFrom(PACKAGE_NAME).addApk(APK_SPLIT_CANONICAL).run();
+        new InstallMultiple().addFile(APK_CANONICAL).run();
+        new InstallMultiple().inheritFrom(PACKAGE_NAME).addFile(APK_SPLIT_CANONICAL).run();
     }
 
     @Test
     public void testBadInstallWithBaseThenDexCompressedSplit() throws Exception {
-        new InstallMultiple().addApk(APK_CANONICAL).run();
-        new InstallMultiple().inheritFrom(PACKAGE_NAME).addApk(APK_SPLIT_COMPRESSED_DEX)
+        new InstallMultiple().addFile(APK_CANONICAL).run();
+        new InstallMultiple().inheritFrom(PACKAGE_NAME).addFile(APK_SPLIT_COMPRESSED_DEX)
                 .runExpectingFailure();
     }
 }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/UseProcessTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/UseProcessTest.java
index 0543f02..4af0248 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/UseProcessTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/UseProcessTest.java
@@ -66,7 +66,7 @@
         testInstallUsePackageSuccess(true);
     }
     private void testInstallUsePackageSuccess(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_SUCCESS).run();
+        new InstallMultiple(instant).addFile(APK_SUCCESS).run();
         assertTrue(getDevice().getInstalledPackageNames().contains(PKG));
 
         Utils.runDeviceTestsAsCurrentUser(getDevice(), PKG, SUCCESS_UNIT_TEST_CLASS, null);
@@ -83,7 +83,7 @@
         testInstallUsePackageFailApplication(true);
     }
     private void testInstallUsePackageFailApplication(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_FAIL_APPLICATION).runExpectingFailure(
+        new InstallMultiple(instant).addFile(APK_FAIL_APPLICATION).runExpectingFailure(
                 "Failure [INSTALL_FAILED_PROCESS_NOT_DEFINED: Scanning Failed.: " +
                         "Can't install because application");
         assertTrue(!getDevice().getInstalledPackageNames().contains(PKG));
@@ -100,7 +100,7 @@
         testInstallUsePackageFailActivity(true);
     }
     private void testInstallUsePackageFailActivity(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_FAIL_ACTIVITY).runExpectingFailure(
+        new InstallMultiple(instant).addFile(APK_FAIL_ACTIVITY).runExpectingFailure(
                 "Failure [INSTALL_FAILED_PROCESS_NOT_DEFINED: Scanning Failed.: " +
                         "Can't install because activity com.android.cts.useprocess.DummyActivity");
         assertTrue(!getDevice().getInstalledPackageNames().contains(PKG));
@@ -117,7 +117,7 @@
         testInstallUsePackageFailService(true);
     }
     private void testInstallUsePackageFailService(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_FAIL_SERVICE).runExpectingFailure(
+        new InstallMultiple(instant).addFile(APK_FAIL_SERVICE).runExpectingFailure(
                 "Failure [INSTALL_FAILED_PROCESS_NOT_DEFINED: Scanning Failed.: " +
                         "Can't install because service com.android.cts.useprocess.DummyService");
         assertTrue(!getDevice().getInstalledPackageNames().contains(PKG));
@@ -134,7 +134,7 @@
         testInstallUsePackageFailReceiver(true);
     }
     private void testInstallUsePackageFailReceiver(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_FAIL_RECEIVER).runExpectingFailure(
+        new InstallMultiple(instant).addFile(APK_FAIL_RECEIVER).runExpectingFailure(
                 "Failure [INSTALL_FAILED_PROCESS_NOT_DEFINED: Scanning Failed.: " +
                         "Can't install because receiver com.android.cts.useprocess.DummyReceiver");
         assertTrue(!getDevice().getInstalledPackageNames().contains(PKG));
@@ -151,7 +151,7 @@
         testInstallUsePackageFailProvider(true);
     }
     private void testInstallUsePackageFailProvider(boolean instant) throws Exception {
-        new InstallMultiple(instant).addApk(APK_FAIL_PROVIDER).runExpectingFailure(
+        new InstallMultiple(instant).addFile(APK_FAIL_PROVIDER).runExpectingFailure(
                 "Failure [INSTALL_FAILED_PROCESS_NOT_DEFINED: Scanning Failed.: " +
                         "Can't install because provider com.android.cts.useprocess.DummyProvider");
         assertTrue(!getDevice().getInstalledPackageNames().contains(PKG));
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java
index f787cc9..1a46d6a 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java
@@ -19,9 +19,14 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assert.assertTrue;
+import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.fail;
 import static org.testng.Assert.expectThrows;
 
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -60,6 +65,15 @@
         });
         assertThat(exception.getMessage()).contains(JAVA_FILE_NOT_FOUND_MSG);
         assertThat(exception.getMessage()).doesNotContain(JAVA_FILE_PERMISSION_DENIED_MSG);
+
+        // Try to create a directory here, and it should return permission denied not directory
+        // exists.
+        try {
+            Os.mkdir(path, 0700);
+            fail("Should not able to mkdir() on " + path);
+        } catch (ErrnoException e) {
+            assertEquals(e.errno, OsConstants.EACCES);
+        }
     }
 
     public static void assertDirIsAccessible(String path) {
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/build b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/build
index d7c1912..205817a 100755
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/build
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/build
@@ -31,11 +31,10 @@
     compiled.flata
 
 # Basic R apk
-# STOPSHIP(b/132742131): Change --target-skd-version to 30 when the SDK is finalized
 aapt2 link \
     -I $PATH_TO_FRAMEWORK_RES \
     --manifest AndroidManifest.xml \
-    --target-sdk-version R \
+    --target-sdk-version 30 \
     -o basic_r.apk \
     compiled.flata
 
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/compressed_R.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/compressed_R.apk
index 960165e..1bdd2bb 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/compressed_R.apk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/compressed_R.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_Q.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_Q.apk
index 7fc1402..b6023bc 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_Q.apk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_Q.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_R.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_R.apk
index 7251a23..e64bcfd 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_R.apk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/unaligned_R.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml
index 1b18a34..e4c3dab 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml
@@ -26,5 +26,6 @@
         android:targetPackage="com.android.cts.externalstorageapp" />
 
     <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml
index e430a59..1f1170b 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/AndroidManifest.xml
@@ -24,5 +24,6 @@
         android:targetPackage="com.android.cts.multiuserstorageapp" />
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/AndroidManifest.xml
index 35f099b..06281ee 100644
--- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/AndroidManifest.xml
@@ -24,5 +24,6 @@
         android:targetPackage="com.android.cts.readexternalstorageapp" />
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestA.xml b/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestA.xml
index a9ae731..8837024 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestA.xml
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestA.xml
@@ -31,5 +31,6 @@
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestB.xml b/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestB.xml
index 019815a..d934c77 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestB.xml
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/AndroidManifestB.xml
@@ -30,5 +30,6 @@
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/StorageStatsApp/AndroidManifest.xml
index e7ac801..c7eddf3 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/AndroidManifest.xml
@@ -25,6 +25,7 @@
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/src/android/appsecurity/cts/v3rotationtests/V3RotationTest.java b/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/src/android/appsecurity/cts/v3rotationtests/V3RotationTest.java
index 4fe98ec..2f06395 100644
--- a/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/src/android/appsecurity/cts/v3rotationtests/V3RotationTest.java
+++ b/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/src/android/appsecurity/cts/v3rotationtests/V3RotationTest.java
@@ -19,12 +19,13 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.Signature;
-import android.util.Log;
 import android.test.AndroidTestCase;
 
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
-import java.lang.Override;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * On-device tests for APK Signature Scheme v3 based signing certificate rotation
@@ -83,6 +84,38 @@
             + "a477acbe6eecc8d575511b2b77a3551f040ccf21792f74cd95c84e3ff87ad03851db81d164c836830e31"
             + "8208a52dcdc77e376f73b96d";
 
+    // These are the hex encodings of the der form of the pkgsigverify/ec-p256[_2] certs used to
+    // sign APKs that are part of this test.
+    private static final String EC_P256_FIRST_CERT_HEX =
+            "3082016c30820111a003020102020900ca0fb64dfb66e772300a06082a86"
+                    + "48ce3d04030230123110300e06035504030c0765632d70323536301e170d"
+                    + "3136303333313134353830365a170d3433303831373134353830365a3012"
+                    + "3110300e06035504030c0765632d703235363059301306072a8648ce3d02"
+                    + "0106082a8648ce3d03010703420004a65f113d22cb4913908307ac31ee2b"
+                    + "a0e9138b785fac6536d14ea2ce90d2b4bfe194b50cdc8e169f54a73a991e"
+                    + "f0fa76329825be078cc782740703da44b4d7eba350304e301d0603551d0e"
+                    + "04160414d4133568b95b30158b322071ea8c43ff5b05ccc8301f0603551d"
+                    + "23041830168014d4133568b95b30158b322071ea8c43ff5b05ccc8300c06"
+                    + "03551d13040530030101ff300a06082a8648ce3d04030203490030460221"
+                    + "00f504a0866caef029f417142c5cb71354c79ffcd1d640618dfca4f19e16"
+                    + "db78d6022100f8eea4829799c06cad08c6d3d2d2ec05e0574154e747ea0f"
+                    + "dbb8042cb655aadd";
+
+    private static final String EC_P256_SECOND_CERT_HEX =
+            "3082016d30820113a0030201020209008855bd1dd2b2b225300a06082a86"
+                    + "48ce3d04030230123110300e06035504030c0765632d70323536301e170d"
+                    + "3138303731333137343135315a170d3238303731303137343135315a3014"
+                    + "3112301006035504030c0965632d703235365f323059301306072a8648ce"
+                    + "3d020106082a8648ce3d030107034200041d4cca0472ad97ee3cecef0da9"
+                    + "3d62b450c6788333b36e7553cde9f74ab5df00bbba6ba950e68461d70bbc"
+                    + "271b62151dad2de2bf6203cd2076801c7a9d4422e1a350304e301d060355"
+                    + "1d0e041604147991d92b0208fc448bf506d4efc9fff428cb5e5f301f0603"
+                    + "551d23041830168014d4133568b95b30158b322071ea8c43ff5b05ccc830"
+                    + "0c0603551d13040530030101ff300a06082a8648ce3d0403020348003045"
+                    + "02202769abb1b49fc2f53479c4ae92a6631dabfd522c9acb0bba2b43ebeb"
+                    + "99c63011022100d260fb1d1f176cf9b7fa60098bfd24319f4905a3e5fda1"
+                    + "00a6fe1a2ab19ff09e";
+
     public void testHasPerm() throws Exception {
         PackageManager pm = getContext().getPackageManager();
         assertTrue(PERMISSION_NAME + " not granted to " + COMPANION_PKG,
@@ -141,6 +174,31 @@
                 + SECOND_CERT_HEX, matchedSecond);
     }
 
+    public void testGetApkContentsSignersShowsCurrent() throws Exception {
+        // The SigningInfo instance returned from GET_SIGNING_CERTIFICATES provides an option to
+        // obtain only the current signer through getApkContentsSigners.
+        PackageManager pm = getContext().getPackageManager();
+        PackageInfo pi = pm.getPackageInfo(PKG, PackageManager.GET_SIGNING_CERTIFICATES);
+        assertNotNull("Failed to get signatures in Package Info of " + PKG, pi.signingInfo);
+        assertFalse("Multiple signing certificates found in signing certificate history for " + PKG,
+                pi.signingInfo.hasMultipleSigners());
+        assertExpectedSignatures(pi.signingInfo.getApkContentsSigners(), EC_P256_SECOND_CERT_HEX);
+    }
+
+    public void testGetApkContentsSignersShowsMultipleSigners() throws Exception {
+        // Similar to the test above when GET_SIGNING_CERTIFICATES is used to obtain the signers
+        // getApkContentSigners should return all of the current signatures when there are multiple
+        // V1 / V2 signers.
+        PackageManager pm = getContext().getPackageManager();
+        PackageInfo pi = pm.getPackageInfo(PKG, PackageManager.GET_SIGNING_CERTIFICATES);
+        assertNotNull("Failed to get signatures in PackageInfo of " + PKG,
+                pi.signingInfo);
+        assertTrue("Multiple signing certificates should have been reported for " + PKG,
+                pi.signingInfo.hasMultipleSigners());
+        assertExpectedSignatures(pi.signingInfo.getApkContentsSigners(), EC_P256_FIRST_CERT_HEX,
+                EC_P256_SECOND_CERT_HEX);
+    }
+
     public void testHasSigningCertificate() throws Exception {
         // make sure that hasSigningCertificate() reports that both certificates in the signing
         // history are present
@@ -226,4 +284,20 @@
         messageDigest.update(data);
         return messageDigest.digest();
     }
+
+    private static void assertExpectedSignatures(Signature[] signatures,
+            String... expectedSignatures) throws Exception {
+        int numSigners = signatures.length;
+        assertEquals("An unexpected number of signatures was returned, expected "
+                        + expectedSignatures.length + ", but received " + signatures.length,
+                expectedSignatures.length, numSigners);
+        Set<String> expectedSignatureSet = new HashSet<>(Arrays.asList(expectedSignatures));
+        for (int i = 0; i < numSigners; i++) {
+            String reportedCert = signatures[i].toCharsString();
+            // Remove the reported certificate from the set to ensure duplicates are not matched.
+            if (!expectedSignatureSet.remove(reportedCert)) {
+                fail("Received an unexpected signature during the test: " + reportedCert);
+            }
+        }
+    }
 }
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/AndroidManifest.xml
index 4010675..67d801c 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/AndroidManifest.xml
@@ -27,5 +27,6 @@
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
+    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/AndroidManifest.xml
index fdf9279..0f8a065 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/AndroidManifest.xml
@@ -25,5 +25,6 @@
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
+    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 
 </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/tinyapp/Android.bp b/hostsidetests/appsecurity/test-apps/tinyapp/Android.bp
deleted file mode 100644
index b650bb4..0000000
--- a/hostsidetests/appsecurity/test-apps/tinyapp/Android.bp
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (C) 2014 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-android_test_helper_app {
-    name: "CtsPkgInstallTinyApp",
-    defaults: ["cts_support_defaults"],
-    // tag this module as a cts test artifact
-    test_suites: [
-        "cts",
-        "vts10",
-        "general-tests",
-    ],
-    srcs: ["src/**/*.java"],
-    sdk_version: "current",
-    dex_preopt: {
-        enabled: false,
-    },
-}
diff --git a/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk b/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk
new file mode 100644
index 0000000..af5a1f1
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk
@@ -0,0 +1,44 @@
+#
+# Copyright (C) 2020 Google Inc.
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+cert_dir := cts/hostsidetests/appsecurity/certs/pkgsigverify
+
+# This is the default test package signed with the default key.
+include $(LOCAL_PATH)/base.mk
+LOCAL_PACKAGE_NAME := CtsPkgInstallTinyApp
+include $(BUILD_CTS_SUPPORT_PACKAGE)
+
+# This is the test package signed using the V1/V2 signature schemes with
+# two signers.
+include $(LOCAL_PATH)/base.mk
+LOCAL_PACKAGE_NAME := v1v2-ec-p256-two-signers
+LOCAL_CERTIFICATE := $(cert_dir)/ec-p256
+LOCAL_ADDITIONAL_CERTIFICATES := $(cert_dir)/ec-p256_2
+include $(BUILD_CTS_SUPPORT_PACKAGE)
+
+# This is the test package signed using the V3 signature scheme with
+# a rotated key and one signer in the lineage with default capabilities.
+include $(LOCAL_PATH)/base.mk
+LOCAL_PACKAGE_NAME := v3-ec-p256-with-por_1_2-default-caps
+LOCAL_CERTIFICATE := $(cert_dir)/ec-p256_2
+LOCAL_ADDITIONAL_CERTIFICATES := $(cert_dir)/ec-p256
+LOCAL_CERTIFICATE_LINEAGE := $(cert_dir)/ec-p256-por_1_2-default-caps
+include $(BUILD_CTS_SUPPORT_PACKAGE)
+
+cert_dir :=
+
diff --git a/hostsidetests/appsecurity/test-apps/tinyapp/base.mk b/hostsidetests/appsecurity/test-apps/tinyapp/base.mk
new file mode 100644
index 0000000..3c4581f
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/tinyapp/base.mk
@@ -0,0 +1,23 @@
+#
+# Copyright (C) 2020 Google Inc.
+#
+# 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.
+#
+
+# Base setup that can be included by all builds of this package.
+include $(CLEAR_VARS)
+LOCAL_COMPATIBILITY_SUITE := cts vts10 general-tests
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_RESOURCE_DIR += $(LOCAL_PATH)/res
+LOCAL_SDK_VERSION := current
+
diff --git a/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalFeatureTest.java b/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalFeatureTest.java
new file mode 100644
index 0000000..6f3e292
--- /dev/null
+++ b/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalFeatureTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.incrementalinstall.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.compatibility.common.util.CddTest;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+
+/**
+ * Test that all devices launched with R have the Incremental feature enabled. Test that the feature
+ * is working properly by installing a package.
+ */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class IncrementalFeatureTest extends BaseHostJUnit4Test {
+    private static final String FEATURE_INCREMENTAL_DELIVERY =
+            "android.software.incremental_delivery";
+    private static final String TEST_REMOTE_DIR = "/data/local/tmp/incremental_feature_test";
+    private static final String TEST_APP_PACKAGE_NAME =
+            "android.incrementalinstall.incrementaltestapp";
+    private static final String TEST_APP_BASE_APK_NAME = "IncrementalTestApp.apk";
+    private static final String IDSIG_SUFFIX = ".idsig";
+    private static final String TEST_APP_BASE_APK_IDSIG_NAME =
+            TEST_APP_BASE_APK_NAME + IDSIG_SUFFIX;
+
+    @Before
+    public void setUp() throws Exception {
+        // Test devices that are launched with R and above; ignore non-targeted devices
+        assumeTrue(getDevice().getLaunchApiLevel() >= 30 /* Build.VERSION_CODES.R */);
+    }
+
+    @CddTest(requirement="4/C-1-1")
+    @Test
+    public void testFeatureAvailable() throws Exception {
+        assertTrue(getDevice().hasFeature(FEATURE_INCREMENTAL_DELIVERY));
+    }
+
+    @CddTest(requirement="4/C-1-1,C-3-1")
+    @Test
+    public void testFeatureWorkingWithInstallation() throws Exception {
+        getDevice().executeShellCommand("mkdir " + TEST_REMOTE_DIR);
+        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(getBuild());
+        final File apk = buildHelper.getTestFile(TEST_APP_BASE_APK_NAME);
+        assertNotNull(apk);
+        final File idsig = buildHelper.getTestFile(TEST_APP_BASE_APK_IDSIG_NAME);
+        assertNotNull(idsig);
+        final String remoteApkPath = TEST_REMOTE_DIR + "/" + apk.getName();
+        final String remoteIdsigPath = remoteApkPath + IDSIG_SUFFIX;
+        assertTrue(getDevice().pushFile(apk, remoteApkPath));
+        assertTrue(getDevice().pushFile(idsig, remoteIdsigPath));
+        String installResult = getDevice().executeShellCommand(
+                "pm install-incremental -t -g " + remoteApkPath);
+        assertEquals("Success\n", installResult);
+        assertTrue(getDevice().isPackageInstalled(TEST_APP_PACKAGE_NAME));
+        getDevice().uninstallPackage(TEST_APP_PACKAGE_NAME);
+    }
+}
diff --git a/hostsidetests/net/app/AndroidManifest.xml b/hostsidetests/net/app/AndroidManifest.xml
index 5ddad7c..3940de4 100644
--- a/hostsidetests/net/app/AndroidManifest.xml
+++ b/hostsidetests/net/app/AndroidManifest.xml
@@ -28,6 +28,7 @@
     <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application android:requestLegacyExternalStorage="true" >
         <uses-library android:name="android.test.runner" />
diff --git a/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractAppIdleTestCase.java b/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractAppIdleTestCase.java
index 51bdf8e..5fe4573 100644
--- a/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractAppIdleTestCase.java
+++ b/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractAppIdleTestCase.java
@@ -50,7 +50,7 @@
     public final void tearDown() throws Exception {
         super.tearDown();
 
-        turnBatteryOff();
+        executeSilentShellCommand("cmd battery reset");
         setAppIdle(false);
     }
 
@@ -131,11 +131,11 @@
     @RequiredProperties({BATTERY_SAVER_MODE})
     @Test
     public void testAppIdleNetworkAccess_whenCharging() throws Exception {
-        // Check that idle app doesn't get network when charging
+        // Check that app is paroled when charging
         setAppIdle(true);
         assertBackgroundNetworkAccess(false);
         turnBatteryOff();
-        assertBackgroundNetworkAccess(false);
+        assertBackgroundNetworkAccess(true);
         turnBatteryOn();
         assertBackgroundNetworkAccess(false);
 
diff --git a/hostsidetests/net/src/com/android/cts/net/NetworkPolicyTestsPreparer.java b/hostsidetests/net/src/com/android/cts/net/NetworkPolicyTestsPreparer.java
index dfce7da..b0facec 100644
--- a/hostsidetests/net/src/com/android/cts/net/NetworkPolicyTestsPreparer.java
+++ b/hostsidetests/net/src/com/android/cts/net/NetworkPolicyTestsPreparer.java
@@ -24,6 +24,9 @@
 public class NetworkPolicyTestsPreparer implements ITargetPreparer {
     private ITestDevice mDevice;
     private String mOriginalAppStandbyEnabled;
+    private String mOriginalBatteryStatsConstants;
+    private final static String KEY_STABLE_CHARGING_DELAY_MS = "battery_charged_delay_ms";
+    private final static int DESIRED_STABLE_CHARGING_DELAY_MS = 0;
 
     @Override
     public void setUp(TestInformation testInformation) throws DeviceNotAvailableException {
@@ -31,12 +34,18 @@
         mOriginalAppStandbyEnabled = getAppStandbyEnabled();
         setAppStandbyEnabled("1");
         LogUtil.CLog.d("Original app_standby_enabled: " + mOriginalAppStandbyEnabled);
+
+        mOriginalBatteryStatsConstants = getBatteryStatsConstants();
+        setBatteryStatsConstants(
+                KEY_STABLE_CHARGING_DELAY_MS + "=" + DESIRED_STABLE_CHARGING_DELAY_MS);
+        LogUtil.CLog.d("Original battery_saver_constants: " + mOriginalBatteryStatsConstants);
     }
 
     @Override
     public void tearDown(TestInformation testInformation, Throwable e)
             throws DeviceNotAvailableException {
         setAppStandbyEnabled(mOriginalAppStandbyEnabled);
+        setBatteryStatsConstants(mOriginalBatteryStatsConstants);
     }
 
     private void setAppStandbyEnabled(String appStandbyEnabled) throws DeviceNotAvailableException {
@@ -51,6 +60,15 @@
         return executeCmd("settings get global app_standby_enabled").trim();
     }
 
+    private void setBatteryStatsConstants(String batteryStatsConstants)
+            throws DeviceNotAvailableException {
+        executeCmd("settings put global battery_stats_constants \"" + batteryStatsConstants + "\"");
+    }
+
+    private String getBatteryStatsConstants() throws DeviceNotAvailableException {
+        return executeCmd("settings get global battery_stats_constants");
+    }
+
     private String executeCmd(String cmd) throws DeviceNotAvailableException {
         final String output = mDevice.executeShellCommand(cmd).trim();
         LogUtil.CLog.d("Output for '%s': %s", cmd, output);
diff --git a/hostsidetests/os/Android.bp b/hostsidetests/os/Android.bp
index 24afa1a..997bfb9 100644
--- a/hostsidetests/os/Android.bp
+++ b/hostsidetests/os/Android.bp
@@ -23,6 +23,9 @@
         "compatibility-host-util",
         "truth-host-prebuilt",
     ],
+    static_libs: [
+        "compatibility-host-util-axt"
+    ],
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
diff --git a/hostsidetests/os/src/android/os/cts/InattentiveSleepTests.java b/hostsidetests/os/src/android/os/cts/InattentiveSleepTests.java
index b1bda95..e117d14 100644
--- a/hostsidetests/os/src/android/os/cts/InattentiveSleepTests.java
+++ b/hostsidetests/os/src/android/os/cts/InattentiveSleepTests.java
@@ -25,10 +25,9 @@
 
 import com.android.compatibility.common.util.PollingCheck;
 import com.android.compatibility.common.util.ProtoUtils;
+import com.android.compatibility.common.util.WindowManagerUtil;
 import com.android.server.power.PowerManagerServiceDumpProto;
 import com.android.server.power.PowerServiceSettingsAndConfigurationDumpProto;
-import com.android.server.wm.WindowManagerServiceDumpProto;
-import com.android.server.wm.WindowStateProto;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
@@ -38,8 +37,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.util.List;
-
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class InattentiveSleepTests extends BaseHostJUnit4Test {
     private static final String FEATURE_LEANBACK_ONLY = "android.software.leanback_only";
@@ -49,7 +46,6 @@
     private static final long TIME_BEFORE_WARNING_MS = 1200L;
 
     private static final String CMD_DUMPSYS_POWER = "dumpsys power --proto";
-    private static final String CMD_GET_WINDOW_TOKENS = "dumpsys window t --proto";
     private static final String WARNING_WINDOW_TOKEN_TITLE = "InattentiveSleepWarning";
     private static final String CMD_START_APP_TEMPLATE =
             "am start -W -a android.intent.action.MAIN -p %s -c android.intent.category.LAUNCHER";
@@ -234,18 +230,7 @@
     }
 
     private boolean isWarningShown() throws Exception {
-        WindowManagerServiceDumpProto windowManagerDump = ProtoUtils.getProto(getDevice(),
-                WindowManagerServiceDumpProto.parser(), CMD_GET_WINDOW_TOKENS);
-
-        List<WindowStateProto> windows =
-                windowManagerDump.getRootWindowContainer().getWindowsList();
-        for (WindowStateProto window : windows) {
-            if (WARNING_WINDOW_TOKEN_TITLE.equals(window.getIdentifier().getTitle())) {
-                return true;
-            }
-        }
-
-        return false;
+        return WindowManagerUtil.hasWindowWithTitle(getDevice(), WARNING_WINDOW_TOKEN_TITLE);
     }
 
     private void waitUntilAsleep() throws Exception {
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/Android.bp b/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
new file mode 100644
index 0000000..3f4087f
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
@@ -0,0 +1,27 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+filegroup {
+    name: "cts_securitybulletin_memutils",
+    srcs: [
+        "memutils.c",
+    ],
+}
+
+filegroup {
+    name: "cts_securitybulletin_omxutils",
+    srcs: [
+        "omxUtils.cpp",
+    ],
+}
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 9f8ec2f..9e68c8c 100644
--- a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
@@ -306,20 +306,44 @@
     }
 
     @Test
+    public void testAbandonStagedApkBeforeReady_CommitAndAbandon() throws Exception {
+        int sessionId = stageSingleApk(TestApp.A1).assertSuccessful().getSessionId();
+        assertThat(getInstalledVersion(TestApp.A)).isEqualTo(-1);
+        abandonSession(sessionId);
+        assertThat(getStagedSessionInfo(sessionId)).isNull();
+    }
+
+    @Test
+    public void testAbandonStagedApkBeforeReady_VerifyPostReboot() throws Exception {
+        assertThat(getInstalledVersion(TestApp.A)).isEqualTo(-1);
+    }
+
+    @Test
+    public void testStageAnotherSessionImmediatelyAfterAbandon() throws Exception {
+        assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+        int sessionId = stageSingleApk(TestApp.Apex2).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);
+        // Using an apex in hopes that pre-reboot verification will take longer to complete
+        // and we will manage to abandon it before session becomes ready.
+        int sessionId = stageMultipleApks(TestApp.A1, TestApp.Apex2).assertSuccessful()
+                .getSessionId();
+        abandonSession(sessionId);
+        assertThat(getStagedSessionInfo(sessionId)).isNull();
+        assertNoSessionUpdatedBroadcastSent();
+    }
+
+    @Test
     public void testGetActiveStagedSessions() throws Exception {
         PackageInstaller packageInstaller = getPackageInstaller();
         int firstSessionId = stageSingleApk(TestApp.A1).assertSuccessful().getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(firstSessionId);
         int secondSessionId = stageSingleApk(TestApp.B1).assertSuccessful().getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(secondSessionId);
         List<Integer> stagedSessionIds = packageInstaller.getActiveStagedSessions()
                 .stream().map(s -> s.getSessionId()).collect(Collectors.toList());
         assertThat(stagedSessionIds).containsExactly(firstSessionId, secondSessionId);
@@ -341,11 +365,6 @@
     public void testIsStagedSessionActive() throws Exception {
         PackageInstaller packageInstaller = getPackageInstaller();
         int sessionId = stageSingleApk(TestApp.A1).assertSuccessful().getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(sessionId);
 
         List<PackageInstaller.SessionInfo> allSessions = packageInstaller.getAllSessions();
         boolean activeStagedSessionFound = false;
@@ -377,17 +396,8 @@
     public void testGetActiveStagedSessions_MultiApkSession() throws Exception {
         int firstSessionId = stageMultipleApks(TestApp.A1, TestApp.B1)
                 .assertSuccessful().getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(firstSessionId);
         int secondSessionId = stageMultipleApks(TestApp.C1)
                 .assertSuccessful().getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        waitForIsReadyBroadcast(secondSessionId);
         List<Integer> stagedSessionIds = getPackageInstaller().getActiveStagedSessions()
                 .stream().map(s -> s.getSessionId()).collect(Collectors.toList());
         assertThat(stagedSessionIds).containsExactly(firstSessionId, secondSessionId);
@@ -873,59 +883,33 @@
     // Should fail to stage multiple sessions when check-point is not available
     @Test
     public void testFailStagingMultipleSessionsIfNoCheckPoint() throws Exception {
-        int sessionId = stageSingleApk(TestApp.A1).assertSuccessful().getSessionId();
+        stageSingleApk(TestApp.A1).assertSuccessful();
         StageSessionResult failedSessionResult = stageSingleApk(TestApp.B1);
         assertThat(failedSessionResult.getErrorMessage()).contains(
                 "Cannot stage multiple sessions without checkpoint support");
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(sessionId);
     }
 
     @Test
     public void testFailOverlappingMultipleStagedInstall_BothSinglePackage_Apk() throws Exception {
-        int sessionId = stageSingleApk(TestApp.A1).assertSuccessful().getSessionId();
+        stageSingleApk(TestApp.A1).assertSuccessful();
         StageSessionResult failedSessionResult = stageSingleApk(TestApp.A1);
         assertThat(failedSessionResult.getErrorMessage()).contains(
                 "has been staged already by session");
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(sessionId);
     }
 
     @Test
     public void testAllowNonOverlappingMultipleStagedInstall_MultiPackageSinglePackage_Apk()
             throws Exception {
-        int firstSessionId = stageMultipleApks(TestApp.A1, TestApp.B1).assertSuccessful()
-                .getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(firstSessionId);
-        int secondSessionId = stageSingleApk(TestApp.C1).assertSuccessful().getSessionId();
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(secondSessionId);
+        stageMultipleApks(TestApp.A1, TestApp.B1).assertSuccessful();
+        stageSingleApk(TestApp.C1).assertSuccessful();
     }
 
     @Test
     public void testFailOverlappingMultipleStagedInstall_BothMultiPackage_Apk() throws Exception {
-        int sessionId = stageMultipleApks(TestApp.A1, TestApp.B1).assertSuccessful().getSessionId();
+        stageMultipleApks(TestApp.A1, TestApp.B1).assertSuccessful();
         StageSessionResult failedSessionResult = stageMultipleApks(TestApp.A2, TestApp.C1);
         assertThat(failedSessionResult.getErrorMessage()).contains(
                 "has been staged already by session");
-        // Currently abandoning a session before pre-reboot verification finishes might result in
-        // a system_server crash. Before that issue is resolved we need to manually wait for
-        // pre-reboot verification to finish before abandoning sessions.
-        // TODO(b/145925842): remove following two lines after fixing the bug.
-        waitForIsReadyBroadcast(sessionId);
     }
 
     // Should succeed in installing multiple staged sessions together
@@ -1173,7 +1157,8 @@
         // Commit the session (this will start the installation workflow).
         Log.i(TAG, "Committing session for apk: " + testApp);
         commitSession(sessionId);
-        return new StageSessionResult(sessionId, LocalIntentSender.getIntentSenderResult());
+        return new StageSessionResult(sessionId,
+                LocalIntentSender.getIntentSenderResult(sessionId));
     }
 
     private static StageSessionResult stageMultipleApks(TestApp... testApps) throws Exception {
@@ -1368,6 +1353,13 @@
         assertThat(info).isNull();
     }
 
+    private void assertNoSessionUpdatedBroadcastSent() throws Exception {
+        PackageInstaller.SessionInfo info =
+                SessionUpdateBroadcastReceiver.sessionBroadcasts.poll(10,
+                        TimeUnit.SECONDS);
+        assertThat(info).isNull();
+    }
+
     @Test
     public void isCheckpointSupported() {
         Context context = InstrumentationRegistry.getInstrumentation().getContext();
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 d5b1a8e..2369a2d 100644
--- a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
@@ -125,6 +125,25 @@
 
     @Test
     @LargeTest
+    public void testAbandonStagedApkBeforeReady() throws Exception {
+        runPhase("testAbandonStagedApkBeforeReady_CommitAndAbandon");
+        getDevice().reboot();
+        runPhase("testAbandonStagedApkBeforeReady_VerifyPostReboot");
+    }
+
+    @Test
+    public void testStageAnotherSessionImmediatelyAfterAbandon() throws Exception {
+        runPhase("testStageAnotherSessionImmediatelyAfterAbandon");
+    }
+
+    @Test
+    public void testNoSessionUpdatedBroadcastSentForStagedSessionAbandon() throws Exception {
+        assumeTrue(isUpdatingApexSupported());
+        runPhase("testNoSessionUpdatedBroadcastSentForStagedSessionAbandon");
+    }
+
+    @Test
+    @LargeTest
     public void testInstallMultipleStagedApks() throws Exception {
         assumeSystemUser();
 
diff --git a/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml b/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
index a5628be..2b479bd 100644
--- a/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
+++ b/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
@@ -44,7 +44,7 @@
         <service android:name=".StatsdCtsBackgroundService" android:exported="true" />
         <activity android:name=".StatsdCtsForegroundActivity" android:exported="true" />
         <service android:name=".StatsdCtsForegroundService"
-                 android:foregroundServiceType="camera|microphone" android:exported="true" />
+                 android:foregroundServiceType="camera" android:exported="true" />
 
         <activity
             android:name=".VideoPlayerActivity"
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
index 53682ad..25727f1 100644
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
+++ b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
@@ -62,6 +62,7 @@
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.os.PowerManager;
+import android.os.Process;
 import android.os.SystemClock;
 import android.os.VibrationEffect;
 import android.os.Vibrator;
@@ -85,6 +86,7 @@
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
 
 public class AtomTests {
     private static final String TAG = AtomTests.class.getSimpleName();
@@ -226,7 +228,68 @@
         performBleScan(scanSettings, Arrays.asList(scanFilter.build()), true);
     }
 
-    private static void performBleScan(ScanSettings scanSettings, List<ScanFilter> scanFilters, boolean waitForResult) {
+    @Test
+    public void testBleScanInterrupted() throws Exception {
+        performBleAction((bluetoothAdapter, bleScanner) -> {
+            ScanSettings scanSettings = new ScanSettings.Builder()
+                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
+            ScanCallback scanCallback = new ScanCallback() {
+                @Override
+                public void onScanResult(int callbackType, ScanResult result) {
+                    Log.v(TAG, "called onScanResult");
+                }
+                @Override
+                public void onScanFailed(int errorCode) {
+                    Log.v(TAG, "called onScanFailed");
+                }
+                @Override
+                public void onBatchScanResults(List<ScanResult> results) {
+                    Log.v(TAG, "called onBatchScanResults");
+                }
+            };
+
+            int uid = Process.myUid();
+            int whatAtomId = 9_999;
+
+            // Change state to State.ON.
+            bleScanner.startScan(null, scanSettings, scanCallback);
+            sleep(500);
+            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
+            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
+            bluetoothAdapter.disable();
+            sleep(500);
+
+            // Trigger State.RESET so that new state is State.OFF.
+            if (!bluetoothAdapter.enable()) {
+                Log.e(TAG, "Could not enable bluetooth to trigger state reset");
+                return;
+            }
+            sleep(2_000); // Wait for Bluetooth to fully turn on.
+            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
+            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
+            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
+        });
+    }
+
+    private static void writeSliceByBleScanStateChangedAtom(int atomId, int firstUid,
+                                                            boolean field2, boolean field3,
+                                                            boolean field4) {
+        final StatsEvent.Builder builder = StatsEvent.newBuilder()
+                .setAtomId(atomId)
+                .writeAttributionChain(new int[] {firstUid}, new String[] {"tag1"})
+                .writeBoolean(field2)
+                .writeBoolean(field3)
+                .writeBoolean(field4)
+                .usePooledBuffer();
+
+        StatsLog.write(builder.build());
+    }
+
+    /**
+     * Set up BluetoothLeScanner and perform the action in the callback.
+     * Restore Bluetooth to original state afterwards.
+     **/
+    private static void performBleAction(BiConsumer<BluetoothAdapter, BluetoothLeScanner> actions) {
         BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
         if (bluetoothAdapter == null) {
             Log.e(TAG, "Device does not support Bluetooth");
@@ -238,7 +301,7 @@
                 Log.e(TAG, "Bluetooth is not enabled");
                 return;
             }
-            sleep(8_000);
+            sleep(2_000); // Wait for Bluetooth to fully turn on.
             bluetoothEnabledByTest = true;
         }
         BluetoothLeScanner bleScanner = bluetoothAdapter.getBluetoothLeScanner();
@@ -247,38 +310,45 @@
             return;
         }
 
-        CountDownLatch resultsLatch = new CountDownLatch(1);
-        ScanCallback scanCallback = new ScanCallback() {
-            @Override
-            public void onScanResult(int callbackType, ScanResult result) {
-                Log.v(TAG, "called onScanResult");
-                resultsLatch.countDown();
-            }
-            @Override
-            public void onScanFailed(int errorCode) {
-                Log.v(TAG, "called onScanFailed");
-            }
-            @Override
-            public void onBatchScanResults(List<ScanResult> results) {
-                Log.v(TAG, "called onBatchScanResults");
-                resultsLatch.countDown();
-            }
-        };
+        actions.accept(bluetoothAdapter, bleScanner);
 
-        bleScanner.startScan(scanFilters, scanSettings, scanCallback);
-        if (waitForResult) {
-            waitForReceiver(InstrumentationRegistry.getContext(), 59_000, resultsLatch, null);
-        } else {
-            sleep(2_000);
-        }
-        bleScanner.stopScan(scanCallback);
-
-        // Restore adapter state at end of test
+        // Restore adapter state
         if (bluetoothEnabledByTest) {
             bluetoothAdapter.disable();
         }
     }
 
+
+    private static void performBleScan(ScanSettings scanSettings, List<ScanFilter> scanFilters, boolean waitForResult) {
+        performBleAction((bluetoothAdapter, bleScanner) -> {
+            CountDownLatch resultsLatch = new CountDownLatch(1);
+            ScanCallback scanCallback = new ScanCallback() {
+                @Override
+                public void onScanResult(int callbackType, ScanResult result) {
+                    Log.v(TAG, "called onScanResult");
+                    resultsLatch.countDown();
+                }
+                @Override
+                public void onScanFailed(int errorCode) {
+                    Log.v(TAG, "called onScanFailed");
+                }
+                @Override
+                public void onBatchScanResults(List<ScanResult> results) {
+                    Log.v(TAG, "called onBatchScanResults");
+                    resultsLatch.countDown();
+                }
+            };
+
+            bleScanner.startScan(scanFilters, scanSettings, scanCallback);
+            if (waitForResult) {
+                waitForReceiver(InstrumentationRegistry.getContext(), 59_000, resultsLatch, null);
+            } else {
+                sleep(2_000);
+            }
+            bleScanner.stopScan(scanCallback);
+        });
+    }
+
     @Test
     public void testCameraState() throws Exception {
         Context context = InstrumentationRegistry.getContext();
@@ -372,6 +442,7 @@
         noteAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA, true);
         noteAppOp(appOpsManager, AppOpsManager.OPSTR_RECORD_AUDIO, false);
         noteAppOp(appOpsManager, AppOpsManager.OPSTR_RECORD_AUDIO, true);
+        noteAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA, false);
         sleep(500);
         context.stopService(fgsIntent);
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index ad5e2196..b455c36 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -571,7 +571,7 @@
             int expectedCount = 0;
             switch (opName) {
                 case AppOpEnum.APP_OP_CAMERA_VALUE:
-                    expectedCount = 2;
+                    expectedCount = 3;
                     break;
                 case AppOpEnum.APP_OP_FINE_LOCATION_VALUE:
                     expectedCount = 1;
@@ -1978,8 +1978,7 @@
             final AtomsProto.MobileBytesTransfer data = ((Atom) atom).getMobileBytesTransfer();
             if (data.getUid() == appUid) {
                 assertDataUsageAtomDataExpected(data.getRxBytes(), data.getTxBytes(),
-                        data.getRxPackets(), data.getTxPackets(), data.getRatType(),
-                        subtypeCombined);
+                        data.getRxPackets(), data.getTxPackets());
                 return true; // found
             }
             return false;
@@ -1995,8 +1994,7 @@
                     ((Atom) atom).getMobileBytesTransferByFgBg();
             if (data.getUid() == appUid) {
                 assertDataUsageAtomDataExpected(data.getRxBytes(), data.getTxBytes(),
-                        data.getRxPackets(), data.getTxPackets(), data.getRatType(),
-                        subtypeCombined);
+                        data.getRxPackets(), data.getTxPackets());
                 // IsForeground cannot be judged since foreground activity that launched
                 // while screen off (PROCESS_STATE_TOP_SLEEPING) will be treated as background
                 // in NetworkPolicyManagerService.
@@ -2021,18 +2019,11 @@
         assertThat(atom.getState()).isEqualTo(AppBreadcrumbReported.State.START);
     }
 
-    private void assertDataUsageAtomDataExpected(
-            long rxb, long txb, long rxp, long txp, int ratType, boolean subtypeCombined) {
+    private void assertDataUsageAtomDataExpected(long rxb, long txb, long rxp, long txp) {
         assertThat(rxb).isGreaterThan(0L);
         assertThat(txb).isGreaterThan(0L);
         assertThat(rxp).isGreaterThan(0L);
         assertThat(txp).isGreaterThan(0L);
-        // TODO: verify the RAT type field with the value get from device.
-        if (subtypeCombined) {
-            assertThat(ratType).isEqualTo(NetworkTypeEnum.NETWORK_TYPE_UNKNOWN_VALUE);
-        } else {
-            assertThat(ratType).isGreaterThan(NetworkTypeEnum.NETWORK_TYPE_UNKNOWN_VALUE);
-        }
     }
 
     private void doTestMobileBytesTransferThat(int atomTag, ThrowingPredicate p)
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
index 4eeb74c..aaf94af 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
@@ -21,8 +21,12 @@
 import android.cts.statsd.atom.DeviceAtomTestCase;
 
 import com.android.internal.os.StatsdConfigProto;
+import com.android.internal.os.StatsdConfigProto.FieldMatcher;
+import com.android.internal.os.StatsdConfigProto.Position;
 import com.android.os.AtomsProto.Atom;
 import com.android.os.AtomsProto.AppBreadcrumbReported;
+import com.android.os.AtomsProto.AttributionNode;
+import com.android.os.AtomsProto.BleScanStateChanged;
 import com.android.os.StatsLog;
 import com.android.os.StatsLog.ConfigMetricsReport;
 import com.android.os.StatsLog.ConfigMetricsReportList;
@@ -296,7 +300,7 @@
         assertThat(bucketInfo.getCount()).isEqualTo(1);
         assertWithMessage("First report's bucket should be less than 1 day")
                 .that(bucketInfo.getEndBucketElapsedNanos())
-                .isLessThan(bucketInfo.getStartBucketElapsedNanos() + 
+                .isLessThan(bucketInfo.getStartBucketElapsedNanos() +
                         1_000_000_000L * 60L * 60L * 24L);
 
         //Second report should have a count of 2.
@@ -307,4 +311,118 @@
         }
         assertThat(totalCount).isEqualTo(2);
     }
+
+    public void testSlicedStateCountMetric() throws Exception {
+        if (statsdDisabled()) {
+            return;
+        }
+        if (!hasFeature(FEATURE_BLUETOOTH_LE, true)) return;
+
+        int whatMatcherId = 3;
+        int stateId = 4;
+
+        // Atom 9999 {
+        //     repeated AttributionNode attribution_node = 1;
+        //     optional bool is_filtered = 2;
+        //     optional bool is_first_match = 3;
+        //     optional bool is_opportunistic = 4;
+        // }
+        int whatAtomId = 9_999;
+
+        StatsdConfigProto.AtomMatcher whatMatcher =
+                MetricsUtils.getAtomMatcher(whatAtomId)
+                        .setId(whatMatcherId)
+                        .build();
+
+        StatsdConfigProto.State state = StatsdConfigProto.State.newBuilder()
+            .setId(stateId)
+            .setAtomId(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER)
+            .build();
+
+        StatsdConfigProto.MetricStateLink stateLink = StatsdConfigProto.MetricStateLink.newBuilder()
+            .setStateAtomId(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER)
+            .setFieldsInWhat(FieldMatcher.newBuilder()
+                    .setField(whatAtomId)
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(1)
+                            .setPosition(Position.FIRST)
+                            .addChild(FieldMatcher.newBuilder()
+                                    .setField(AttributionNode.UID_FIELD_NUMBER)
+                            )
+                    )
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(2)
+                    )
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(3)
+                    )
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(4)
+                    )
+            )
+            .setFieldsInState(FieldMatcher.newBuilder()
+                    .setField(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER)
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(BleScanStateChanged.ATTRIBUTION_NODE_FIELD_NUMBER)
+                            .setPosition(Position.FIRST)
+                            .addChild(FieldMatcher.newBuilder()
+                                    .setField(AttributionNode.UID_FIELD_NUMBER)
+                            )
+                    )
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(BleScanStateChanged.IS_FILTERED_FIELD_NUMBER)
+                    )
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(BleScanStateChanged.IS_FIRST_MATCH_FIELD_NUMBER)
+                    )
+                    .addChild(FieldMatcher.newBuilder()
+                            .setField(BleScanStateChanged.IS_OPPORTUNISTIC_FIELD_NUMBER)
+                    )
+            )
+            .build();
+
+        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
+                .addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
+                    .setId(MetricsUtils.COUNT_METRIC_ID)
+                    .setBucket(StatsdConfigProto.TimeUnit.CTS)
+                    .setWhat(whatMatcherId)
+                    .addSliceByState(stateId)
+                    .addStateLink(stateLink)
+                )
+                .addAtomMatcher(whatMatcher)
+                .addState(state);
+        uploadConfig(builder);
+
+        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testBleScanInterrupted");
+
+        StatsLogReport metricReport = getStatsLogReport();
+        LogUtil.CLog.d("Got the following stats log report: \n" + metricReport.toString());
+        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
+        assertThat(metricReport.hasCountMetrics()).isTrue();
+
+        StatsLogReport.CountMetricDataWrapper dataWrapper = metricReport.getCountMetrics();
+        assertThat(dataWrapper.getDataCount()).isEqualTo(2);
+
+        CountMetricData data = dataWrapper.getData(0);
+        assertThat(data.getSliceByStateCount()).isEqualTo(1);
+        assertThat(data.getSliceByState(0).getAtomId())
+                .isEqualTo(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER);
+        assertThat(data.getSliceByState(0).getValue())
+                .isEqualTo(BleScanStateChanged.State.OFF.ordinal());
+        long totalCount = data.getBucketInfoList().stream()
+                .mapToLong(CountBucketInfo::getCount)
+                .sum();
+        assertThat(totalCount).isEqualTo(3);
+
+        data = dataWrapper.getData(1);
+        assertThat(data.getSliceByStateCount()).isEqualTo(1);
+        assertThat(data.getSliceByState(0).getAtomId())
+                .isEqualTo(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER);
+        assertThat(data.getSliceByState(0).getValue())
+                .isEqualTo(BleScanStateChanged.State.ON.ordinal());
+        totalCount = data.getBucketInfoList().stream()
+                .mapToLong(CountBucketInfo::getCount)
+                .sum();
+        assertThat(totalCount).isEqualTo(2);
+    }
 }
diff --git a/hostsidetests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderHostTest.java b/hostsidetests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderHostTest.java
index 6e226d1..73d1dc8 100644
--- a/hostsidetests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderHostTest.java
+++ b/hostsidetests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderHostTest.java
@@ -30,19 +30,29 @@
     protected static final String TEST_PKG = "android.telephonyprovider.device.cts";
 
     private static final long APN_READING_PERMISSION_CHANGE_ID = 124107808L;
+    private static final String FEATURE_TELEPHONY = "android.hardware.telephony";
 
     @Override
     protected void setUp() throws Exception {
+        if (!getDevice().hasFeature(FEATURE_TELEPHONY)) {
+            return;
+        }
         installPackage(TEST_APK, true);
     }
 
     public void testWithChangeEnabled() throws Exception {
+        if (!getDevice().hasFeature(FEATURE_TELEPHONY)) {
+            return;
+        }
         runDeviceCompatTest(TEST_PKG, ".TelephonyProviderTest", "testAccessToApnsWithChangeEnabled",
                 /*enabledChanges*/ImmutableSet.of(APN_READING_PERMISSION_CHANGE_ID),
                 /*disabledChanges*/ ImmutableSet.of());
     }
 
     public void testWithChangeDisabled() throws Exception {
+        if (!getDevice().hasFeature(FEATURE_TELEPHONY)) {
+            return;
+        }
         runDeviceCompatTest(TEST_PKG, ".TelephonyProviderTest",
                 "testAccessToApnsWithChangeDisabled",
                 /*enabledChanges*/ImmutableSet.of(),
diff --git a/hostsidetests/theme/app/AndroidManifest.xml b/hostsidetests/theme/app/AndroidManifest.xml
index d76c718..7487a05 100755
--- a/hostsidetests/theme/app/AndroidManifest.xml
+++ b/hostsidetests/theme/app/AndroidManifest.xml
@@ -19,6 +19,7 @@
     package="android.theme.app">
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application android:requestLegacyExternalStorage="true">
         <uses-library android:name="android.test.runner" />
diff --git a/libs/install/src/com/android/cts/install/lib/LocalIntentSender.java b/libs/install/src/com/android/cts/install/lib/LocalIntentSender.java
index cf2abe8..4560ab1 100644
--- a/libs/install/src/com/android/cts/install/lib/LocalIntentSender.java
+++ b/libs/install/src/com/android/cts/install/lib/LocalIntentSender.java
@@ -63,6 +63,21 @@
         return intent;
     }
 
+    /**
+     * Returns an Intent that targets the given {@code sessionId}, while discarding others.
+     */
+    public static Intent getIntentSenderResult(int sessionId) throws InterruptedException {
+        while (true) {
+            Intent intent = sIntentSenderResults.take();
+            if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1) == sessionId) {
+                Log.i(TAG, "Taking intent " + prettyPrint(intent));
+                return intent;
+            } else {
+                Log.i(TAG, "Discarding intent " + prettyPrint(intent));
+            }
+        }
+    }
+
     private static String prettyPrint(Intent intent) {
         int sessionId = intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1);
         int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS,
diff --git a/tests/JobScheduler/AndroidManifest.xml b/tests/JobScheduler/AndroidManifest.xml
index 347d11b..0c7471f 100755
--- a/tests/JobScheduler/AndroidManifest.xml
+++ b/tests/JobScheduler/AndroidManifest.xml
@@ -27,6 +27,7 @@
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 
     <application android:requestLegacyExternalStorage="true">
diff --git a/tests/accessibility/AndroidManifest.xml b/tests/accessibility/AndroidManifest.xml
index c9e0c71..4a7348d 100644
--- a/tests/accessibility/AndroidManifest.xml
+++ b/tests/accessibility/AndroidManifest.xml
@@ -22,6 +22,7 @@
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 
     <application android:theme="@android:style/Theme.Holo.NoActionBar"
diff --git a/tests/accessibility/common/src/android/accessibility/cts/common/AccessibilityDumpOnFailureRule.java b/tests/accessibility/common/src/android/accessibility/cts/common/AccessibilityDumpOnFailureRule.java
index df7c550..3725027 100644
--- a/tests/accessibility/common/src/android/accessibility/cts/common/AccessibilityDumpOnFailureRule.java
+++ b/tests/accessibility/common/src/android/accessibility/cts/common/AccessibilityDumpOnFailureRule.java
@@ -42,6 +42,7 @@
  * </pre>
  * <p>And disable external storage isolation:
  * <pre>
+ *  <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
  *  <application ... android:requestLegacyExternalStorage="true" ... >
  * </pre>
  */
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java
index 8143a82..9b7951f 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java
@@ -33,12 +33,14 @@
 import android.view.accessibility.AccessibilityManager;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.accessibility.AccessibilityRecord;
-import android.view.accessibility.cts.SpeakingAccessibilityService;
 import android.widget.LinearLayout;
+
 import androidx.test.filters.SmallTest;
 import androidx.test.rule.ActivityTestRule;
 import androidx.test.runner.AndroidJUnit4;
+
 import junit.framework.TestCase;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -46,11 +48,8 @@
 import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
-import java.util.concurrent.Callable;
 import java.util.List;
 
-import static org.junit.Assert.*;
-
 /**
  * Class for testing {@link AccessibilityEvent}.
  */
@@ -107,7 +106,7 @@
 
     @Test
     public void testScrollEvent() throws Exception {
-        mChildView.scrollTo(0,100);
+        mChildView.scrollTo(0, 100);
         Thread.sleep(1000);
         scrollEventFilter.assertReceivedEventCount(1);
     }
@@ -225,7 +224,8 @@
 
     private AccessibilityEventFilter stateDescriptionEventFilter = new AccessibilityEventFilter() {
         public boolean pass(AccessibilityEvent event) {
-            return event.getContentChangeTypes() == AccessibilityEvent.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION;
+            return event.getContentChangeTypes()
+                    == AccessibilityEvent.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION;
         }
     };
 
@@ -261,7 +261,8 @@
     }
 
     private void sendStateDescriptionChangedEvent(View view, CharSequence text) {
-        AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
+        AccessibilityEvent event = AccessibilityEvent.obtain(
+                AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
         event.setContentChangeTypes(AccessibilityEvent.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION);
         event.getText().add(text);
         view.sendAccessibilityEventUnchecked(event);
@@ -285,7 +286,7 @@
         AccessibilityEvent receivedEvent = AccessibilityEvent.CREATOR.createFromParcel(parcel);
 
         // make sure all fields properly marshaled
-        assertEqualsAccessiblityEvent(sentEvent, receivedEvent);
+        assertEqualsAccessibilityEvent(sentEvent, receivedEvent);
 
         parcel.recycle();
     }
@@ -349,7 +350,7 @@
         assertEquals("TYPE_VIEW_SELECTED", AccessibilityEvent.eventTypeToString(
                 AccessibilityEvent.TYPE_VIEW_SELECTED));
         assertEquals("TYPE_VIEW_TEXT_CHANGED", AccessibilityEvent.eventTypeToString(
-                AccessibilityEvent .TYPE_VIEW_TEXT_CHANGED));
+                AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED));
         assertEquals("TYPE_VIEW_TEXT_SELECTION_CHANGED", AccessibilityEvent.eventTypeToString(
                 AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED));
         assertEquals("TYPE_WINDOW_CONTENT_CHANGED", AccessibilityEvent.eventTypeToString(
@@ -379,14 +380,19 @@
     @SmallTest
     @Test
     public void testMarshaling2() {
+        // fully populate the event to marshal
         AccessibilityEvent marshaledEvent = AccessibilityEvent.obtain();
         fullyPopulateAccessibilityEvent(marshaledEvent);
+
+        // marshal and unmarshal the event
         Parcel parcel = Parcel.obtain();
         marshaledEvent.writeToParcel(parcel, 0);
         parcel.setDataPosition(0);
         AccessibilityEvent unmarshaledEvent = AccessibilityEvent.obtain();
         unmarshaledEvent.initFromParcel(parcel);
-        assertEqualsAccessiblityEvent(marshaledEvent, unmarshaledEvent);
+
+        // make sure all fields properly marshaled
+        assertEqualsAccessibilityEvent(marshaledEvent, unmarshaledEvent);
 
         parcel.recycle();
     }
@@ -412,6 +418,23 @@
         assertTrue(TextUtils.equals(originalText, event.getContentDescription()));
     }
 
+    @SmallTest
+    @Test
+    public void testConstructors() {
+        final AccessibilityEvent populatedEvent = new AccessibilityEvent();
+        fullyPopulateAccessibilityEvent(populatedEvent);
+        final AccessibilityEvent event = new AccessibilityEvent(populatedEvent);
+
+        assertEqualsAccessibilityEvent(event, populatedEvent);
+
+        final AccessibilityEvent firstEvent = new AccessibilityEvent();
+        firstEvent.setEventType(AccessibilityEvent.TYPE_VIEW_FOCUSED);
+        final AccessibilityEvent secondEvent = new AccessibilityEvent(
+                AccessibilityEvent.TYPE_VIEW_FOCUSED);
+
+        assertEqualsAccessibilityEvent(firstEvent, secondEvent);
+    }
+
     /**
      * Fully populates the {@link AccessibilityEvent} to marshal.
      *
@@ -451,14 +474,13 @@
         sentEvent.appendRecord(record);
     }
 
-
     /**
      * Compares all properties of the <code>expectedEvent</code> and the
-     * <code>receviedEvent</code> to verify that the received event is the one
+     * <code>receivedEvent</code> to verify that the received event is the one
      * that is expected.
      */
-    private static void assertEqualsAccessiblityEvent(AccessibilityEvent expectedEvent,
-                                                      AccessibilityEvent receivedEvent) {
+    private static void assertEqualsAccessibilityEvent(AccessibilityEvent expectedEvent,
+            AccessibilityEvent receivedEvent) {
         assertEquals("addedCount has incorrect value", expectedEvent.getAddedCount(), receivedEvent
                 .getAddedCount());
         assertEquals("beforeText has incorrect value", expectedEvent.getBeforeText(), receivedEvent
@@ -485,38 +507,44 @@
                 .isPassword());
         assertEquals("removedCount has incorrect value", expectedEvent.getRemovedCount(),
                 receivedEvent.getRemovedCount());
-        AccessibilityRecordTest.assertEqualsText(expectedEvent.getText(), receivedEvent.getText());
-        assertEquals("must have one record", expectedEvent.getRecordCount(),
-                receivedEvent.getRecordCount());
-        assertSame("maxScrollX has incorect value", expectedEvent.getMaxScrollX(),
+        assertSame("maxScrollX has incorrect value", expectedEvent.getMaxScrollX(),
                 receivedEvent.getMaxScrollX());
-        assertSame("maxScrollY has incorect value", expectedEvent.getMaxScrollY(),
+        assertSame("maxScrollY has incorrect value", expectedEvent.getMaxScrollY(),
                 receivedEvent.getMaxScrollY());
-        assertSame("scrollX has incorect value", expectedEvent.getScrollX(),
+        assertSame("scrollX has incorrect value", expectedEvent.getScrollX(),
                 receivedEvent.getScrollX());
-        assertSame("scrollY has incorect value", expectedEvent.getScrollY(),
+        assertSame("scrollY has incorrect value", expectedEvent.getScrollY(),
                 receivedEvent.getScrollY());
-        assertSame("scrollDeltaX has incorect value", expectedEvent.getScrollDeltaX(),
+        assertSame("scrollDeltaX has incorrect value", expectedEvent.getScrollDeltaX(),
                 receivedEvent.getScrollDeltaX());
-        assertSame("scrollDeltaY has incorect value", expectedEvent.getScrollDeltaY(),
+        assertSame("scrollDeltaY has incorrect value", expectedEvent.getScrollDeltaY(),
                 receivedEvent.getScrollDeltaY());
-        assertSame("toIndex has incorect value", expectedEvent.getToIndex(),
+        assertSame("toIndex has incorrect value", expectedEvent.getToIndex(),
                 receivedEvent.getToIndex());
-        assertSame("scrollable has incorect value", expectedEvent.isScrollable(),
+        assertSame("scrollable has incorrect value", expectedEvent.isScrollable(),
                 receivedEvent.isScrollable());
-        assertSame("granularity has incorect value", expectedEvent.getMovementGranularity(),
+        assertSame("granularity has incorrect value", expectedEvent.getMovementGranularity(),
                 receivedEvent.getMovementGranularity());
-        assertSame("action has incorect value", expectedEvent.getAction(),
+        assertSame("action has incorrect value", expectedEvent.getAction(),
                 receivedEvent.getAction());
-        assertSame("windowChangeTypes has incorect value", expectedEvent.getWindowChanges(),
+        assertSame("windowChangeTypes has incorrect value", expectedEvent.getWindowChanges(),
                 receivedEvent.getWindowChanges());
 
-        assertSame("parcelableData has incorect value",
-                ((Message) expectedEvent.getParcelableData()).what,
-                ((Message) receivedEvent.getParcelableData()).what);
+        AccessibilityRecordTest.assertEqualsText(expectedEvent.getText(), receivedEvent.getText());
+        AccessibilityRecordTest.assertEqualAccessibilityRecord(expectedEvent, receivedEvent);
 
-        AccessibilityRecord receivedRecord = receivedEvent.getRecord(0);
-        AccessibilityRecordTest.assertEqualAccessibilityRecord(expectedEvent, receivedRecord);
+        assertEqualAppendedRecord(expectedEvent, receivedEvent);
+    }
+
+    private static void assertEqualAppendedRecord(AccessibilityEvent expectedEvent,
+            AccessibilityEvent receivedEvent) {
+        assertEquals("recordCount has incorrect value", expectedEvent.getRecordCount(),
+                receivedEvent.getRecordCount());
+        if (expectedEvent.getRecordCount() != 0 && receivedEvent.getRecordCount() != 0) {
+            AccessibilityRecord expectedRecord =  expectedEvent.getRecord(0);
+            AccessibilityRecord receivedRecord = receivedEvent.getRecord(0);
+            AccessibilityRecordTest.assertEqualAccessibilityRecord(expectedRecord, receivedRecord);
+        }
     }
 
     /**
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityRecordTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityRecordTest.java
index 119de9f..08d6637 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityRecordTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityRecordTest.java
@@ -17,6 +17,7 @@
 package android.view.accessibility.cts;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertSame;
 
 import android.accessibility.cts.common.AccessibilityDumpOnFailureRule;
@@ -160,21 +161,28 @@
         assertEquals("removedCount has incorrect value", expectedRecord.getRemovedCount(),
                 receivedRecord.getRemovedCount());
         assertEqualsText(expectedRecord.getText(), receivedRecord.getText());
-        assertSame("maxScrollX has incorect value", expectedRecord.getMaxScrollX(),
+        assertSame("maxScrollX has incorrect value", expectedRecord.getMaxScrollX(),
                 receivedRecord.getMaxScrollX());
-        assertSame("maxScrollY has incorect value", expectedRecord.getMaxScrollY(),
+        assertSame("maxScrollY has incorrect value", expectedRecord.getMaxScrollY(),
                 receivedRecord.getMaxScrollY());
-        assertSame("scrollX has incorect value", expectedRecord.getScrollX(),
+        assertSame("scrollX has incorrect value", expectedRecord.getScrollX(),
                 receivedRecord.getScrollX());
-        assertSame("scrollY has incorect value", expectedRecord.getScrollY(),
+        assertSame("scrollY has incorrect value", expectedRecord.getScrollY(),
                 receivedRecord.getScrollY());
-        assertSame("toIndex has incorect value", expectedRecord.getToIndex(),
+        assertSame("toIndex has incorrect value", expectedRecord.getToIndex(),
                 receivedRecord.getToIndex());
-        assertSame("scrollable has incorect value", expectedRecord.isScrollable(),
+        assertSame("scrollable has incorrect value", expectedRecord.isScrollable(),
                 receivedRecord.isScrollable());
-        assertSame("parcelableData has incorect value",
-                ((Message) expectedRecord.getParcelableData()).what,
-                ((Message) receivedRecord.getParcelableData()).what);
+
+        assertFalse("one of the parcelableData is null",
+                expectedRecord.getParcelableData() == null
+                        ^ receivedRecord.getParcelableData() == null);
+        if (expectedRecord.getParcelableData() != null
+                && receivedRecord.getParcelableData() != null) {
+            assertSame("parcelableData has incorrect value",
+                    ((Message) expectedRecord.getParcelableData()).what,
+                    ((Message) receivedRecord.getParcelableData()).what);
+        }
     }
 
     /**
diff --git a/tests/accessibilityservice/AndroidManifest.xml b/tests/accessibilityservice/AndroidManifest.xml
index a7406bb..5a8e337 100644
--- a/tests/accessibilityservice/AndroidManifest.xml
+++ b/tests/accessibilityservice/AndroidManifest.xml
@@ -21,6 +21,7 @@
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
     <uses-permission android:name="android.permission.USE_FINGERPRINT" />
     <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
diff --git a/tests/app/AndroidManifest.xml b/tests/app/AndroidManifest.xml
index 860c1a8..b7f0371 100644
--- a/tests/app/AndroidManifest.xml
+++ b/tests/app/AndroidManifest.xml
@@ -24,6 +24,7 @@
     <uses-permission android:name="android.permission.ENTER_CAR_MODE_PRIORITIZED" />
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
     <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
+    <uses-permission android:name="android.permission.ACCESS_NOTIFICATIONS" />
 
     <application android:usesCleartextTraffic="true">
         <uses-library android:name="android.test.runner" />
diff --git a/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java b/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
index 6b11ba6..c49e89a 100644
--- a/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
+++ b/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
@@ -1145,6 +1145,7 @@
     private static class Monitor {
         static final String WAIT_FOR_EARLY_ANR = "Waiting after early ANR...  available commands:";
         static final String WAIT_FOR_ANR = "Waiting after ANR...  available commands:";
+        static final String WAIT_FOR_CRASHED = "Waiting after crash...  available commands:";
         static final String CMD_CONTINUE = "c";
         static final String CMD_KILL = "k";
 
@@ -1194,6 +1195,13 @@
                     String line = mPendingLines.remove(0);
                     if (TextUtils.equals(line, expected)) {
                         break;
+                    } else if (TextUtils.equals(line, WAIT_FOR_EARLY_ANR)
+                            || TextUtils.equals(line, WAIT_FOR_ANR)
+                            || TextUtils.equals(line, WAIT_FOR_CRASHED)) {
+                        // If we are getting any of the unexpected state,
+                        // for example, get a crash while waiting for an ANR,
+                        // it could be from another unrelated process, kill it directly.
+                        sendCommand(CMD_KILL);
                     }
                 }
             }
diff --git a/tests/app/DownloadManagerApi28Test/AndroidManifest.xml b/tests/app/DownloadManagerApi28Test/AndroidManifest.xml
index f6eb1c4..fec3c4d 100644
--- a/tests/app/DownloadManagerApi28Test/AndroidManifest.xml
+++ b/tests/app/DownloadManagerApi28Test/AndroidManifest.xml
@@ -22,6 +22,7 @@
 
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application android:usesCleartextTraffic="true"
                  android:networkSecurityConfig="@xml/network_security_config">
diff --git a/tests/app/src/android/app/cts/UiModeManagerTest.java b/tests/app/src/android/app/cts/UiModeManagerTest.java
index 25ec9a3..1d443f6 100644
--- a/tests/app/src/android/app/cts/UiModeManagerTest.java
+++ b/tests/app/src/android/app/cts/UiModeManagerTest.java
@@ -34,6 +34,7 @@
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.time.LocalTime;
 
 public class UiModeManagerTest extends AndroidTestCase {
     private static final String TAG = "UiModeManagerTest";
@@ -84,6 +85,28 @@
         }
     }
 
+    public void testSetAndGetCustomTimeStart() {
+        LocalTime time = mUiModeManager.getCustomNightModeStart();
+        // decrease time
+        LocalTime timeNew = LocalTime.of(
+                (time.getHour() + 1) % 12,
+                (time.getMinute() + 30) % 60);
+        setStartTime(timeNew);
+        assertNotSame(time, timeNew);
+        assertEquals(timeNew, mUiModeManager.getCustomNightModeStart());
+    }
+
+    public void testSetAndGetCustomTimeEnd() {
+        LocalTime time = mUiModeManager.getCustomNightModeEnd();
+        // decrease time
+        LocalTime timeNew = LocalTime.of(
+                (time.getHour() + 1) % 12,
+                (time.getMinute() + 30) % 60);
+        setEndTime(timeNew);
+        assertNotSame(time, timeNew);
+        assertEquals(timeNew, mUiModeManager.getCustomNightModeEnd());
+    }
+
     public void testNightModeYesPersisted() throws InterruptedException {
         // Reset the mode to no if it is set to another value
         setNightMode(UiModeManager.MODE_NIGHT_NO);
@@ -327,7 +350,6 @@
     }
 
     private void setNightMode(int mode) {
-        final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
         String modeString = "unknown";
         switch (mode) {
             case UiModeManager.MODE_NIGHT_AUTO:
@@ -341,6 +363,21 @@
                 break;
         }
         final String command = " cmd uimode night " + modeString;
+        applyCommand(command);
+    }
+
+    private void setStartTime(LocalTime t) {
+        final String command = " cmd uimode time start " + t.toString();
+        applyCommand(command);
+    }
+
+    private void setEndTime(LocalTime t) {
+        final String command = " cmd uimode time end " + t.toString();
+        applyCommand(command);
+    }
+
+    private void applyCommand(String command) {
+        final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
         try (ParcelFileDescriptor fd = uiAutomation.executeShellCommand(command)) {
             Assert.assertNotNull("Failed to execute shell command: " + command, fd);
             // Wait for the command to finish by reading until EOF
@@ -356,4 +393,5 @@
             uiAutomation.destroy();
         }
     }
+
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
index 65df6fb..5b1a86e 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
@@ -210,7 +210,6 @@
             }
         };
 
-        @ClassRule
         public static final MockImeSessionRule sMockImeSessionRule = new MockImeSessionRule(
                 InstrumentationRegistry.getTargetContext(),
                 InstrumentationRegistry.getInstrumentation().getUiAutomation(),
@@ -248,6 +247,9 @@
                 // test being ran and finishes dangling activities at the end
                 .around(mTestWatcher)
                 //
+                // sMockImeSessionRule make sure MockImeSession.create() is used to launch mock IME
+                .around(sMockImeSessionRule)
+                //
                 // mLoggingRule wraps the test but doesn't interfere with it
                 .around(mLoggingRule)
                 //
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginWithCustomHighlightActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginWithCustomHighlightActivityTest.java
index 282102f..0812ad7 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginWithCustomHighlightActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginWithCustomHighlightActivityTest.java
@@ -67,7 +67,7 @@
     public void testAutofillCustomHighlight_multipleFields_hasHighlight() throws Exception {
         testAutofillCustomHighlight(/* singleField= */false);
 
-        final Rect bounds = new Rect(MyDrawable.getAutofilledBounds());
+        final Rect bounds = MyDrawable.getAutofilledBounds();
         final int width = mActivity.getUsername().getWidth();
         final int height = mActivity.getUsername().getHeight();
         if (bounds.isEmpty() || bounds.right != width || bounds.bottom != height) {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MyDrawable.java b/tests/autofillservice/src/android/autofillservice/cts/MyDrawable.java
index 003effe..ada5a67 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MyDrawable.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MyDrawable.java
@@ -45,7 +45,7 @@
     @Override
     public void draw(Canvas canvas) {
         if (sInstance != null && sAutofilledBounds == null) {
-            sAutofilledBounds = getBounds();
+            sAutofilledBounds = new Rect(getBounds());
             Log.d(TAG, "Autofilled at " + sAutofilledBounds);
             sLatch.countDown();
         }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedLoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedLoginActivityTest.java
index 15816f3..bbf2cdb 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedLoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedLoginActivityTest.java
@@ -776,6 +776,93 @@
     }
 
     @Test
+    public void testAugmentedAutoFill_noPreviousRequest_requestAutofill() throws Exception {
+        // Set services
+        Helper.disableAutofillService(sContext);
+        final CtsAugmentedAutofillService service = enableAugmentedService();
+
+        // Request requestAutofill without any existing request
+        final AutofillId usernameId = mActivity.getUsername().getAutofillId();
+        final ComponentName componentName = mActivity.getComponentName();
+        final boolean requestResult = service.requestAutofill(componentName, usernameId);
+
+        assertThat(requestResult).isFalse();
+    }
+
+    @Test
+    public void testAugmentedAutoFill_hasPreviousRequestViewFocused_requestAutofill()
+            throws Exception {
+        // Set services
+        Helper.disableAutofillService(sContext);
+        final CtsAugmentedAutofillService service = enableAugmentedService();
+
+        // Set expectations
+        final EditText username = mActivity.getUsername();
+        final AutofillId usernameId = username.getAutofillId();
+        final AutofillValue usernameValue = username.getAutofillValue();
+        sAugmentedReplier.addResponse(new CannedAugmentedFillResponse.Builder()
+                .setDataset(new CannedAugmentedFillResponse.Dataset.Builder("Augment Me")
+                        .setField(usernameId, "dude")
+                        .build(), usernameId)
+                .build());
+
+        // Trigger autofill
+        mActivity.onUsername(View::requestFocus);
+        mUiBot.waitForIdleSync();
+        sAugmentedReplier.getNextFillRequest();
+
+        // Set expectations for username again
+        sAugmentedReplier.addResponse(new CannedAugmentedFillResponse.Builder()
+                .setDataset(new CannedAugmentedFillResponse.Dataset.Builder("Augment Me")
+                        .setField(usernameId, "dude")
+                        .build(), usernameId)
+                .build());
+        // Service requests requestAutofill() for same focused view
+        final ComponentName componentName = mActivity.getComponentName();
+        final boolean requestResult = service.requestAutofill(componentName, usernameId);
+        final AugmentedFillRequest request = sAugmentedReplier.getNextFillRequest();
+
+        // Assert request
+        assertThat(requestResult).isTrue();
+        assertBasicRequestInfo(request, mActivity, usernameId, usernameValue);
+
+        // Make sure standard Autofill UI is not shown.
+        mUiBot.assertNoDatasetsEver();
+
+        // Make sure Augmented Autofill UI is shown.
+        mAugmentedUiBot.assertUiShown(usernameId, "Augment Me");
+    }
+
+    @Test
+    public void testAugmentedAutoFill_hasPreviousRequestViewNotFocused_requestAutofill()
+            throws Exception {
+        // Set services
+        Helper.disableAutofillService(sContext);
+        final CtsAugmentedAutofillService service = enableAugmentedService();
+
+        // Set expectations
+        final AutofillId usernameId = mActivity.getUsername().getAutofillId();
+        sAugmentedReplier.addResponse(new CannedAugmentedFillResponse.Builder()
+                .setDataset(new CannedAugmentedFillResponse.Dataset.Builder("Augment Me")
+                        .setField(usernameId, "dude")
+                        .build(), usernameId)
+                .build());
+
+        // Trigger autofill
+        mActivity.onUsername(View::requestFocus);
+        sAugmentedReplier.getNextFillRequest();
+
+        // Clear focus
+        mActivity.clearFocus();
+
+        // Service requests requestAutofill() for non-focused view
+        final ComponentName componentName = mActivity.getComponentName();
+        final boolean requestResult = service.requestAutofill(componentName, usernameId);
+
+        assertThat(requestResult).isFalse();
+    }
+
+    @Test
     @AppModeFull(reason = "testAutoFill_mainServiceReturnedNull_augmentedAutofillOneField enough")
     public void testAugmentedAutoFill_mainServiceDisabled() throws Exception {
         // Set services
diff --git a/tests/camera/src/android/hardware/camera2/cts/ConcurrentCameraTest.java b/tests/camera/src/android/hardware/camera2/cts/ConcurrentCameraTest.java
index ebff2dd..6ee7ec2 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ConcurrentCameraTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ConcurrentCameraTest.java
@@ -80,10 +80,11 @@
         public List<ImageReader> rawTargets = new ArrayList<ImageReader>();
         public List<ImageReader> heicTargets = new ArrayList<ImageReader>();
         public TestSample(String cameraId, StaticMetadata staticInfo,
-                MandatoryStreamCombination combination) {
+                MandatoryStreamCombination combination, boolean subY8) {
             this.cameraId = cameraId;
             this.staticInfo = staticInfo;
             this.combination = combination;
+            this.substituteY8 = subY8;
         }
     }
 
@@ -123,8 +124,9 @@
                             info != null);
                     MandatoryStreamCombination chosenCombination =
                             deviceSample.getValue().combination;
+                    boolean substituteY8 = deviceSample.getValue().substituteY8;
                     TestSample testSample = new TestSample(deviceSample.getKey(), info.mStaticInfo,
-                            chosenCombination);
+                            chosenCombination, substituteY8);
                     testSamples.add(testSample);
                     openDevice(deviceSample.getKey());
                 }
@@ -242,13 +244,12 @@
             CameraTestInfo info = mCameraTestInfos.get(testSample.cameraId);
             assertTrue("CameraTestInfo not found for camera id " + testSample.cameraId,
                     info != null);
-            boolean substituteY8 = (testSample.substituteY8);
             CameraTestUtils.setupConfigurationTargets(
                 testSample.combination.getStreamsInformation(), testSample.privTargets,
                 testSample.jpegTargets, testSample.yuvTargets, testSample.y8Targets,
                 testSample.rawTargets, testSample.heicTargets, testSample.outputConfigs,
-                MIN_RESULT_COUNT, substituteY8, /*substituteHEIC*/false, /*physicalCameraId*/null,
-                mHandler);
+                MIN_RESULT_COUNT, testSample.substituteY8, /*substituteHEIC*/false,
+                /*physicalCameraId*/null, mHandler);
 
             try {
                 checkSessionConfigurationSupported(info.mCamera, mHandler, testSample.outputConfigs,
diff --git a/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
index e59b161..58fb31e 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
@@ -906,6 +906,10 @@
                     NUM_REPROCESS_CAPTURES);
             setupReprocessableSession(/*previewSurface*/null, NUM_REPROCESS_CAPTURES);
 
+            // Wait for session READY state after session creation
+            mSessionListener.getStateWaiter().waitForState(
+                    BlockingSessionCallback.SESSION_READY, SESSION_CLOSE_TIMEOUT_MS);
+
             // Test two cases: submitting reprocess requests one by one and in a burst.
             boolean submitInBursts[] = {false, true};
             for (boolean submitInBurst : submitInBursts) {
@@ -917,6 +921,10 @@
                     TotalCaptureResult result = submitCaptureRequest(mFirstImageReader.getSurface(),
                             /*inputResult*/null);
 
+                    // Wait and drain the READY state for each reprocessing input output.
+                    mSessionListener.getStateWaiter().waitForState(
+                            BlockingSessionCallback.SESSION_READY, SESSION_CLOSE_TIMEOUT_MS);
+
                     mImageWriter.queueInputImage(
                             mFirstImageReaderListener.getImage(CAPTURE_TIMEOUT_MS));
                     CaptureRequest.Builder builder = mCamera.createReprocessCaptureRequest(result);
diff --git a/tests/controls/Android.bp b/tests/controls/Android.bp
index b0346be..ead4dc8 100644
--- a/tests/controls/Android.bp
+++ b/tests/controls/Android.bp
@@ -29,6 +29,7 @@
      ],
 
     libs: [
+        "android.test.mock",
         "android.test.runner.stubs",
         "android.test.base.stubs",
     ],
diff --git a/tests/controls/res/color/custom_mower.xml b/tests/controls/res/color/custom_mower.xml
new file mode 100644
index 0000000..420265f
--- /dev/null
+++ b/tests/controls/res/color/custom_mower.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+  <item android:state_enabled="false"
+        android:color="#333333" />
+  <item android:color="#aaaaaa" />
+</selector>
diff --git a/tests/controls/res/drawable/ic_device_unknown.xml b/tests/controls/res/drawable/ic_device_unknown.xml
new file mode 100644
index 0000000..55820d0
--- /dev/null
+++ b/tests/controls/res/drawable/ic_device_unknown.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+  <path
+      android:pathData="M8,6.5V11.76C8.8027,12.2963 9.4117,13.0766 9.7369,13.9856C10.0622,14.8946 10.0865,15.8841 9.8062,16.8079C9.526,17.7317 8.9561,18.541 8.1807,19.1161C7.4052,19.6912 6.4654,20.0017 5.5,20.0017C4.5346,20.0017 3.5948,19.6912 2.8193,19.1161C2.0439,18.541 1.474,17.7317 1.1938,16.8079C0.9135,15.8841 0.9378,14.8946 1.2631,13.9856C1.5883,13.0766 2.1973,12.2963 3,11.76V6.5C3,5.837 3.2634,5.2011 3.7322,4.7322C4.2011,4.2634 4.837,4 5.5,4C6.163,4 6.7989,4.2634 7.2678,4.7322C7.7366,5.2011 8,5.837 8,6.5ZM3.049,16H7.949C8.0467,15.5132 7.9978,15.0084 7.8084,14.5495C7.619,14.0905 7.2976,13.6981 6.885,13.422L5.998,12.828V6.5C5.998,6.3674 5.9453,6.2402 5.8516,6.1465C5.7578,6.0527 5.6306,6 5.498,6C5.3654,6 5.2382,6.0527 5.1445,6.1465C5.0507,6.2402 4.998,6.3674 4.998,6.5V12.828L4.111,13.422C3.7061,13.6922 3.3887,14.0746 3.1976,14.5223C3.0065,14.97 2.95,15.4637 3.035,15.943C3.0363,15.951 3.0389,15.959 3.0416,15.967C3.0453,15.978 3.049,15.989 3.049,16Z"
+      android:fillColor="#FF000000"
+      android:fillType="evenOdd"/>
+  <path
+      android:pathData="M14,16H20V18H14V16Z"
+      android:fillColor="#FF000000" />
+  <path
+      android:pathData="M17,4C15.7113,4.0006 14.457,4.416 13.4228,5.1849C12.3886,5.9538 11.6294,7.0353 11.2577,8.2692C10.8859,9.5031 10.9214,10.824 11.3587,12.0362C11.7961,13.2484 12.6121,14.2876 13.686,15H20.314C21.3879,14.2876 22.204,13.2484 22.6413,12.0362C23.0786,10.824 23.1141,9.5031 22.7423,8.2692C22.3706,7.0353 21.6114,5.9538 20.5772,5.1849C19.543,4.416 18.2887,4.0006 17,4ZM19.643,13H14.357C13.7469,12.4629 13.3149,11.7528 13.1185,10.9641C12.9221,10.1753 12.9707,9.3455 13.2577,8.5851C13.5447,7.8246 14.0566,7.1697 14.7251,6.7074C15.3937,6.2452 16.1872,5.9976 17,5.9976C17.8128,5.9976 18.6063,6.2452 19.2749,6.7074C19.9434,7.1697 20.4553,7.8246 20.7423,8.5851C21.0293,9.3455 21.0779,10.1753 20.8815,10.9641C20.6851,11.7528 20.2531,12.4629 19.643,13Z"
+      android:fillColor="#FF000000"
+      android:fillType="evenOdd"/>
+  <path
+      android:pathData="M18.0607,19.5607C17.7793,19.842 17.3978,20 17,20C16.6022,20 16.2207,19.842 15.9393,19.5607C15.658,19.2794 15.5,18.8978 15.5,18.5H18.5C18.5,18.8978 18.342,19.2794 18.0607,19.5607Z"
+      android:fillColor="#FF000000" />
+</vector>
diff --git a/tests/controls/src/android/controls/cts/CtsControlBuilderTest.java b/tests/controls/src/android/controls/cts/CtsControlBuilderTest.java
new file mode 100644
index 0000000..911ccc2
--- /dev/null
+++ b/tests/controls/src/android/controls/cts/CtsControlBuilderTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.controls.cts;
+
+import static org.junit.Assert.assertEquals;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.ColorStateList;
+import android.graphics.drawable.Icon;
+import android.service.controls.Control;
+import android.service.controls.DeviceTypes;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Covers Control builder methods that are not already covered in CtsControlsServiceTest.
+ */
+@RunWith(AndroidJUnit4.class)
+public class CtsControlBuilderTest {
+
+    private static final String TITLE = "title";
+    private static final String SUBTITLE = "subtitle";
+    private static final String ZONE = "zone";
+    private static final String STRUCTURE = "structure";
+    private static final String CONTROL_ID = "testId";
+    private static final String CONTROL_ID2 = "testId2";
+    private static final int DEVICE_TYPE = DeviceTypes.TYPE_PERGOLA;
+    private static final int STATUS_STATEFUL = Control.STATUS_ERROR;
+    private static final int STATUS_STATELESS = Control.STATUS_UNKNOWN;
+    private static final String STATUS_TEXT_STATELESS = "";
+    private static final String STATUS_TEXT_STATEFUL = "statusText";
+
+    private Context mContext;
+    private PendingIntent mPendingIntent;
+    private PendingIntent mPendingIntent2;
+    private ColorStateList mColorStateList;
+    private Icon mIcon;
+
+    @Before
+    public void setUp() {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        mPendingIntent = PendingIntent.getActivity(mContext, 1, new Intent(),
+            PendingIntent.FLAG_UPDATE_CURRENT);
+        mPendingIntent2 = PendingIntent.getActivity(mContext, 2, new Intent(),
+            PendingIntent.FLAG_UPDATE_CURRENT);
+        mIcon = Icon.createWithResource(mContext, R.drawable.ic_device_unknown);
+        mColorStateList = mContext.getResources().getColorStateList(R.color.custom_mower, null);
+    }
+
+    @Test
+    public void testStatelessBuilder() {
+        Control control = new Control.StatelessBuilder(CONTROL_ID, mPendingIntent)
+                .setTitle(TITLE)
+                .setControlId(CONTROL_ID2)
+                .setAppIntent(mPendingIntent2)
+                .setSubtitle(SUBTITLE)
+                .setStructure(STRUCTURE)
+                .setDeviceType(DEVICE_TYPE)
+                .setZone(ZONE)
+                .setCustomIcon(mIcon)
+                .setCustomColor(mColorStateList)
+                .build();
+
+        assertControl(control, true);
+    }
+
+    @Test
+    public void testStatefulBuilderAlternateConstructor() {
+        Control control = new Control.StatefulBuilder(CONTROL_ID, mPendingIntent)
+                .setTitle(TITLE)
+                .setControlId(CONTROL_ID2)
+                .setAppIntent(mPendingIntent2)
+                .setSubtitle(SUBTITLE)
+                .setStructure(STRUCTURE)
+                .setDeviceType(DEVICE_TYPE)
+                .setZone(ZONE)
+                .setStatus(STATUS_STATEFUL)
+                .setStatusText(STATUS_TEXT_STATEFUL)
+                .setCustomIcon(mIcon)
+                .setCustomColor(mColorStateList)
+                .build();
+
+        Control updatedControl = new Control.StatefulBuilder(control).build();
+        assertControl(updatedControl, false);
+    }
+
+    private void assertControl(Control control, boolean isStateless) {
+        assertEquals(control.getTitle(), TITLE);
+        assertEquals(control.getSubtitle(), SUBTITLE);
+        assertEquals(control.getStructure(), STRUCTURE);
+        assertEquals(control.getZone(), ZONE);
+        assertEquals(control.getDeviceType(), DEVICE_TYPE);
+        assertEquals(control.getStatus(), isStateless ? STATUS_STATELESS : STATUS_STATEFUL);
+        assertEquals(control.getStatusText(),
+                isStateless ? STATUS_TEXT_STATELESS : STATUS_TEXT_STATEFUL);
+        assertEquals(control.getControlId(), CONTROL_ID2);
+        assertEquals(control.getCustomColor(), mColorStateList);
+        assertEquals(control.getCustomIcon(), mIcon);
+    }
+}
diff --git a/tests/controls/src/android/controls/cts/CtsControlsService.java b/tests/controls/src/android/controls/cts/CtsControlsService.java
index 8890664..593394f 100644
--- a/tests/controls/src/android/controls/cts/CtsControlsService.java
+++ b/tests/controls/src/android/controls/cts/CtsControlsService.java
@@ -15,9 +15,14 @@
  */
 package android.controls.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.Intent;
+import android.content.res.ColorStateList;
+import android.graphics.drawable.Icon;
 import android.service.controls.Control;
 import android.service.controls.ControlsProviderService;
 import android.service.controls.DeviceTypes;
@@ -54,12 +59,16 @@
     private final Map<String, Control> mControlsById = new HashMap<>();
     private final Context mContext;
     private final PendingIntent mPendingIntent;
+    private ColorStateList mColorStateList;
+    private Icon mIcon;
 
     public CtsControlsService() {
         mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
-
         mPendingIntent = PendingIntent.getActivity(mContext, 1, new Intent(),
             PendingIntent.FLAG_UPDATE_CURRENT);
+        mIcon = Icon.createWithResource(mContext, R.drawable.ic_device_unknown);
+        mColorStateList = mContext.getResources().getColorStateList(R.color.custom_mower, null);
+
         mAllControls.add(buildLight(false /* isOn */, 0.0f /* intensity */));
         mAllControls.add(buildLock(false /* isLocked */));
         mAllControls.add(buildRoutine());
@@ -116,6 +125,8 @@
             .setStructure("Vacation")
             .setZone("Outside")
             .setControlTemplate(template)
+            .setCustomIcon(mIcon)
+            .setCustomColor(mColorStateList)
             .build();
     }
 
@@ -214,6 +225,10 @@
         Control c = mControlsById.get(controlId);
         if (c == null) return;
 
+        // all values are hardcoded for this test
+        assertEquals(action.getTemplateId(), "action");
+        assertNotEquals(action, ControlAction.getErrorAction());
+
         Control.StatefulBuilder builder = controlToBuilder(c);
 
         // Modify the builder in order to update the Control to have predefined, verifiable behavior
@@ -318,7 +333,9 @@
             .setStructure(c.getStructure())
             .setDeviceType(c.getDeviceType())
             .setZone(c.getZone())
-            .setStatus(Control.STATUS_OK)
-            .setStatusText("Refreshed");
+            .setCustomIcon(c.getCustomIcon())
+            .setCustomColor(c.getCustomColor())
+            .setStatus(c.getStatus())
+            .setStatusText(c.getStatusText());
     }
 }
diff --git a/tests/controls/src/android/controls/cts/CtsControlsServiceTest.java b/tests/controls/src/android/controls/cts/CtsControlsServiceTest.java
index 97dae17..8ae32df 100644
--- a/tests/controls/src/android/controls/cts/CtsControlsServiceTest.java
+++ b/tests/controls/src/android/controls/cts/CtsControlsServiceTest.java
@@ -16,7 +16,20 @@
 
 package android.controls.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
 import android.service.controls.Control;
+import android.service.controls.ControlsProviderService;
 import android.service.controls.actions.BooleanAction;
 import android.service.controls.actions.CommandAction;
 import android.service.controls.actions.ControlAction;
@@ -27,6 +40,7 @@
 import android.service.controls.templates.TemperatureControlTemplate;
 import android.service.controls.templates.ToggleRangeTemplate;
 import android.service.controls.templates.ToggleTemplate;
+import android.test.mock.MockContext;
 
 import androidx.test.runner.AndroidJUnit4;
 
@@ -41,13 +55,12 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
 @RunWith(AndroidJUnit4.class)
 public class CtsControlsServiceTest {
 
+    private static final String ACTION_ADD_CONTROL = "android.service.controls.action.ADD_CONTROL";
+    private static final String EXTRA_CONTROL = "android.service.controls.extra.CONTROL";
+
     private CtsControlsService mControlsService;
 
     @Before
@@ -138,7 +151,9 @@
         List<Control> loadedControls = new ArrayList<>();
         subscribe(publisher, 10, loadedControls);
 
-        mControlsService.performControlAction("switch", new BooleanAction("action", true),
+        BooleanAction action = new BooleanAction("action", true);
+        assertEquals(action.getActionType(), ControlAction.TYPE_BOOLEAN);
+        mControlsService.performControlAction("switch", action,
                 assertConsumer(ControlAction.RESPONSE_OK));
 
         List<Control> expectedControls = new ArrayList<>();
@@ -160,7 +175,9 @@
         mControlsService.performControlAction("light", new BooleanAction("action", true),
                 assertConsumer(ControlAction.RESPONSE_OK));
 
-        mControlsService.performControlAction("light", new FloatAction("action", 80.0f),
+        FloatAction action = new FloatAction("action", 80.0f);
+        assertEquals(action.getActionType(), ControlAction.TYPE_FLOAT);
+        mControlsService.performControlAction("light", action,
                 assertConsumer(ControlAction.RESPONSE_OK));
 
         List<Control> expectedControls = new ArrayList<>();
@@ -180,7 +197,9 @@
         List<Control> loadedControls = new ArrayList<>();
         subscribe(publisher, 10, loadedControls);
 
-        mControlsService.performControlAction("routine", new CommandAction("action"),
+        CommandAction action = new CommandAction("action");
+        assertEquals(action.getActionType(), ControlAction.TYPE_COMMAND);
+        mControlsService.performControlAction("routine", action,
                 assertConsumer(ControlAction.RESPONSE_OK));
 
         List<Control> expectedControls = new ArrayList<>();
@@ -265,8 +284,9 @@
         List<Control> loadedControls = new ArrayList<>();
         subscribe(publisher, 10, loadedControls);
 
-        mControlsService.performControlAction("thermostat",
-                new ModeAction("action", TemperatureControlTemplate.MODE_COOL),
+        ModeAction action = new ModeAction("action", TemperatureControlTemplate.MODE_COOL);
+        assertEquals(action.getActionType(), ControlAction.TYPE_MODE);
+        mControlsService.performControlAction("thermostat", action,
                 assertConsumer(ControlAction.RESPONSE_OK));
 
         List<Control> expectedControls = new ArrayList<>();
@@ -277,12 +297,35 @@
         assertControlsList(loadedControls, expectedControls);
     }
 
-    private void assertConsumerOk(int status) {
-        assertEquals(status, ControlAction.RESPONSE_OK);
+    @Test
+    public void testRequestAddControl() {
+        Resources res = mock(Resources.class);
+        when(res.getString(anyInt())).thenReturn("");
+
+        final ComponentName testComponent = new ComponentName("TestPkg", "TestClass");
+        final Control control = new Control.StatelessBuilder(mControlsService.buildMower(false))
+                .build();
+
+        Context context = new MockContext() {
+            public Resources getResources() {
+                return res;
+            }
+
+            public void sendBroadcast(Intent intent, String receiverPermission) {
+                assertEquals(intent.getAction(), ACTION_ADD_CONTROL);
+                assertEquals((ComponentName) intent.getParcelableExtra(Intent.EXTRA_COMPONENT_NAME),
+                        testComponent);
+                assertEquals((Control) intent.getParcelableExtra(EXTRA_CONTROL), control);
+                assertEquals(receiverPermission, "android.permission.BIND_CONTROLS");
+            }
+        };
+
+        ControlsProviderService.requestAddControl(context, testComponent, control);
     }
 
     private Consumer<Integer> assertConsumer(int expectedStatus) {
         return (status) -> {
+            ControlAction.isValidResponse(status);
             assertEquals((int) status, expectedStatus);
         };
     }
@@ -324,6 +367,8 @@
         assertEquals(c1.getDeviceType(), c2.getDeviceType());
         assertEquals(c1.getStatus(), c2.getStatus());
         assertEquals(c1.getControlId(), c2.getControlId());
+        assertEquals(c1.getCustomIcon(), c2.getCustomIcon());
+        assertEquals(c1.getCustomColor(), c2.getCustomColor());
 
         assertTemplateEquals(c1.getControlTemplate(), c2.getControlTemplate());
     }
@@ -336,6 +381,8 @@
             assertNotNull(ct2);
         }
 
+        assertNotEquals(ct1, ControlTemplate.getErrorTemplate());
+        assertNotEquals(ct2, ControlTemplate.getErrorTemplate());
         assertEquals(ct1.getTemplateType(), ct2.getTemplateType());
         assertEquals(ct1.getTemplateId(), ct2.getTemplateId());
 
diff --git a/tests/framework/base/windowmanager/AndroidManifest.xml b/tests/framework/base/windowmanager/AndroidManifest.xml
index 0b036d9..c0d01b2 100644
--- a/tests/framework/base/windowmanager/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/AndroidManifest.xml
@@ -24,6 +24,7 @@
     <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.STOP_APP_SWITCHES" />
     <uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
@@ -330,6 +331,9 @@
                   android:showWhenLocked="true"/>
         <activity android:name="android.server.wm.WindowInsetsPolicyTest$FullscreenTestActivity"/>
         <activity android:name="android.server.wm.WindowInsetsPolicyTest$FullscreenWmFlagsTestActivity"/>
+        <activity android:name="android.server.wm.WindowInsetsPolicyTest$ImmersiveFullscreenTestActivity"
+                  android:documentLaunchMode="always"
+                  android:theme="@style/no_animation" />
         <activity android:name="android.server.wm.LayoutTests$TestActivity"
                   android:theme="@style/no_animation" />
         <activity android:name="android.server.wm.LocationOnScreenTests$TestActivity"
diff --git a/tests/framework/base/windowmanager/app/AndroidManifest.xml b/tests/framework/base/windowmanager/app/AndroidManifest.xml
index 67cae55..981f59f 100755
--- a/tests/framework/base/windowmanager/app/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/app/AndroidManifest.xml
@@ -497,6 +497,16 @@
             </intent-filter>
         </service>
 
+        <service
+            android:name=".TestStubbornDream"
+            android:exported="true"
+            android:permission="android.permission.BIND_DREAM_SERVICE">
+            <intent-filter>
+                <action android:name="android.service.dreams.DreamService" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </service>
+
         <!-- Disable home activities by default or it may disturb other tests by
              showing ResolverActivity when start home activity -->
         <activity-alias android:name=".HomeActivity"
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java
index 80c363e..8d2f216 100644
--- a/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java
@@ -210,6 +210,9 @@
     public static final ComponentName TEST_DREAM_SERVICE =
             component("TestDream");
 
+    public static final ComponentName TEST_STUBBORN_DREAM_SERVICE =
+            component("TestStubbornDream");
+
     /**
      * Action and extra key constants for {@link #INPUT_METHOD_TEST_ACTIVITY}.
      */
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/TestStubbornDream.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/TestStubbornDream.java
new file mode 100644
index 0000000..d9677a0
--- /dev/null
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/TestStubbornDream.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.server.wm.app;
+
+import android.service.dreams.DreamService;
+
+public class TestStubbornDream extends DreamService {
+    @Override
+    public void onWakeUp() {
+        // Not calling finish will trigger the DreamManager to wait for 5 seconds before forcefully
+        // killing the DreamService
+    }
+}
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
index 5023481..4f1dfcd 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
@@ -50,6 +50,8 @@
 
         public static final String ACTION_LAUNCH_BACKGROUND_ACTIVITIES =
                 Components.class.getPackage().getName() + ".ACTION_LAUNCH_BACKGROUND_ACTIVITIES";
+        public static final String ACTION_FINISH_ACTIVITY =
+                Components.class.getPackage().getName() + ".ACTION_FINISH_ACTIVITY";
     }
 
     /** Extra key constants for {@link #APP_A_SEND_PENDING_INTENT_RECEIVER} */
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
index 1413fbc..9f92875 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
@@ -16,6 +16,7 @@
 
 package android.server.wm.backgroundactivity.appa;
 
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_FINISH_ACTIVITY;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_LAUNCH_BACKGROUND_ACTIVITIES;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_BACKGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_INTENTS_EXTRA;
@@ -45,10 +46,15 @@
     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
-            // Need to copy as a new array instead of just casting to Intent[] since a new array of
-            // type Parcelable[] is created when deserializing.
-            Parcelable[] intents = intent.getParcelableArrayExtra(LAUNCH_INTENTS_EXTRA);
-            startActivities(Arrays.copyOf(intents, intents.length, Intent[].class));
+            String action = intent.getAction();
+            if (ACTION_LAUNCH_BACKGROUND_ACTIVITIES.equals(action)) {
+                // Need to copy as a new array instead of just casting to Intent[] since a new
+                // array of type Parcelable[] is created when deserializing.
+                Parcelable[] intents = intent.getParcelableArrayExtra(LAUNCH_INTENTS_EXTRA);
+                startActivities(Arrays.copyOf(intents, intents.length, Intent[].class));
+            } else if (ACTION_FINISH_ACTIVITY.equals(action)) {
+                finish();
+            }
         }
     };
 
@@ -84,7 +90,10 @@
             newIntent.setClass(this, SecondBackgroundActivity.class);
             startActivity(newIntent);
         }
-        registerReceiver(mReceiver, new IntentFilter(ACTION_LAUNCH_BACKGROUND_ACTIVITIES));
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(ACTION_LAUNCH_BACKGROUND_ACTIVITIES);
+        filter.addAction(ACTION_FINISH_ACTIVITY);
+        registerReceiver(mReceiver, filter);
     }
 
     @Override
diff --git a/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java b/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
index 40aa58e..09c8fc2 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
@@ -18,14 +18,15 @@
 
 import static android.app.AppOpsManager.MODE_ALLOWED;
 import static android.app.AppOpsManager.MODE_ERRORED;
-import static android.server.wm.WindowManagerState.STATE_INITIALIZING;
 import static android.server.wm.UiDeviceUtils.pressHomeButton;
+import static android.server.wm.WindowManagerState.STATE_INITIALIZING;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_BACKGROUND_ACTIVITY;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_FOREGROUND_ACTIVITY;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SECOND_BACKGROUND_ACTIVITY;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SEND_PENDING_INTENT_RECEIVER;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SIMPLE_ADMIN_RECEIVER;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_START_ACTIVITY_RECEIVER;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_FINISH_ACTIVITY;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_LAUNCH_BACKGROUND_ACTIVITIES;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_BACKGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_INTENTS_EXTRA;
@@ -82,6 +83,7 @@
 
     private static final int ACTIVITY_FOCUS_TIMEOUT_MS = 3000;
     private static final String APP_A_PACKAGE_NAME = APP_A_FOREGROUND_ACTIVITY.getPackageName();
+    private static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
 
     private static final String TEST_PACKAGE_APP_A = "android.server.wm.backgroundactivity.appa";
     private static final String TEST_PACKAGE_APP_B = "android.server.wm.backgroundactivity.appb";
@@ -137,6 +139,28 @@
     }
 
     @Test
+    @FlakyTest(bugId = 155454710)
+    public void testBackgroundActivityNotBlockedWithinGracePeriod() throws Exception {
+        // Start AppA foreground activity
+        Intent firstIntent = new Intent();
+        firstIntent.setComponent(APP_A_FOREGROUND_ACTIVITY);
+        firstIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(firstIntent);
+        boolean firstResult = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
+        assertTrue("Not able to start foreground activity", firstResult);
+        // Don't press home button to avoid stop app switches
+        mContext.sendBroadcast(new Intent(ACTION_FINISH_ACTIVITY));
+        mWmState.waitForHomeActivityVisible();
+        Thread.sleep(ACTIVITY_BG_START_GRACE_PERIOD_MS / 2);
+        Intent secondIntent = new Intent();
+        secondIntent.setComponent(APP_A_START_ACTIVITY_RECEIVER);
+
+        mContext.sendBroadcast(secondIntent);
+        boolean secondResult = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
+        assertTrue("Should be able to launch background activity", secondResult);
+    }
+
+    @Test
     public void testBackgroundActivityNotBlockedWhenSystemAlertWindowGranted() throws Exception {
         // enable appopp for SAW for this test
         AppOpsUtils.setOpMode(APP_A_PACKAGE_NAME, "android:system_alert_window", MODE_ALLOWED);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java b/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java
index 78ef876..9a4e9a3 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java
@@ -17,10 +17,19 @@
 package android.server.wm;
 
 import static android.server.wm.app.Components.TEST_DREAM_SERVICE;
+import static android.server.wm.app.Components.TEST_STUBBORN_DREAM_SERVICE;
+import static android.server.wm.ComponentNameUtils.getWindowName;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static android.view.Display.DEFAULT_DISPLAY;
+
+import static org.junit.Assume.assumeTrue;
 
 import android.app.DreamManager;
 import android.content.ComponentName;
 import android.platform.test.annotations.Presubmit;
+import android.view.Surface;
 
 import androidx.test.filters.FlakyTest;
 
@@ -32,9 +41,18 @@
 @FlakyTest(detail = "Promote once confirmed non-flaky")
 public class DreamManagerServiceTests extends ActivityManagerTestBase {
 
-    private static final ComponentName DREAM_ACTIVITY_COMPONENT_NAME =
-            new ComponentName(TEST_DREAM_SERVICE.getPackageName(),
-                              "android.service.dreams.DreamActivity");
+    // Timeout after which the dream should have finished willingly
+    private static final long ACTIVITY_STOP_TIMEOUT = 3000;
+
+    // Timeout after which the dream should have been forcefully stopped
+    private static final long ACTIVITY_FORCE_STOP_TIMEOUT = 5500;
+
+    private ComponentName mDreamActivityName;
+
+    private static final ComponentName getDreamActivityName(ComponentName dream) {
+        return new ComponentName(dream.getPackageName(),
+                                 "android.service.dreams.DreamActivity");
+    }
 
     private void startDream(ComponentName name) {
         DreamManager dreamer = mContext.getSystemService(DreamManager.class);
@@ -55,6 +73,20 @@
         SystemUtil.runWithShellPermissionIdentity(() -> {
             dreamer.setActiveDream(dream);
         });
+        mDreamActivityName = getDreamActivityName(dream);
+    }
+
+    private boolean getIsDreaming() {
+        DreamManager dreamer = mContext.getSystemService(DreamManager.class);
+        return SystemUtil.runWithShellPermissionIdentity(() -> {
+            return dreamer.isDreaming();
+        });
+    }
+
+    private void assertDreamActivityIsGone() {
+        mWmState.computeState();
+        assertTrue(!mWmState.containsWindow(getWindowName(mDreamActivityName))
+                   && !mWmState.containsActivity(mDreamActivityName));
     }
 
     @Test
@@ -62,13 +94,62 @@
         setActiveDream(TEST_DREAM_SERVICE);
 
         startDream(TEST_DREAM_SERVICE);
-        mWmState.waitForValidState(DREAM_ACTIVITY_COMPONENT_NAME);
-        mWmState.assertVisibility(DREAM_ACTIVITY_COMPONENT_NAME, true);
+        mWmState.waitForValidState(mDreamActivityName);
+        mWmState.assertVisibility(mDreamActivityName, true);
+        mWmState.assertHomeActivityVisible(false);
+
+        assertTrue(getIsDreaming());
+
+        stopDream();
+        mWmState.waitAndAssertActivityRemoved(mDreamActivityName);
+
+        mWmState.assertHomeActivityVisible(true);
+    }
+
+    @Test
+    public void testDreamServiceStopsTimely() throws Exception {
+        setActiveDream(TEST_DREAM_SERVICE);
+
+        startDream(TEST_DREAM_SERVICE);
+        mWmState.waitForValidState(mDreamActivityName);
+        assertTrue(getIsDreaming());
+
+        stopDream();
+
+        Thread.sleep(ACTIVITY_STOP_TIMEOUT);
+
+        assertDreamActivityIsGone();
+        assertFalse(getIsDreaming());
+    }
+
+    @Test
+    public void testForceStopStubbornDream() throws Exception {
+        setActiveDream(TEST_STUBBORN_DREAM_SERVICE);
+
+        startDream(TEST_STUBBORN_DREAM_SERVICE);
+        mWmState.waitForValidState(mDreamActivityName);
+        mWmState.assertVisibility(mDreamActivityName, true);
         mWmState.assertHomeActivityVisible(false);
 
         stopDream();
-        mWmState.waitAndAssertActivityRemoved(DREAM_ACTIVITY_COMPONENT_NAME);
 
-        mWmState.assertHomeActivityVisible(true);
+        Thread.sleep(ACTIVITY_FORCE_STOP_TIMEOUT);
+
+        assertDreamActivityIsGone();
+        assertFalse(getIsDreaming());
+    }
+
+    @Test
+    public void testDreamNotFinishAfterRotation() {
+        assumeTrue("Skipping test: no rotation support", supportsRotation());
+
+        final RotationSession rotationSession = createManagedRotationSession();
+        rotationSession.set(Surface.ROTATION_0);
+        setActiveDream(TEST_DREAM_SERVICE);
+        startDream(TEST_DREAM_SERVICE);
+        rotationSession.set(Surface.ROTATION_90);
+
+        waitAndAssertTopResumedActivity(mDreamActivityName, DEFAULT_DISPLAY,
+                "Dream activity should be the top resumed activity");
     }
 }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DumpOnFailure.java b/tests/framework/base/windowmanager/src/android/server/wm/DumpOnFailure.java
index 5326f19..a62d20e 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DumpOnFailure.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DumpOnFailure.java
@@ -48,6 +48,7 @@
  * </pre>
  * <p>And disable external storage isolation:
  * <pre>
+ *  <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
  *  <application ... android:requestLegacyExternalStorage="true" ... >
  * </pre>
  */
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/LayoutTests.java b/tests/framework/base/windowmanager/src/android/server/wm/LayoutTests.java
index b9d84d7..f0d685b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/LayoutTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/LayoutTests.java
@@ -39,7 +39,6 @@
 import android.view.View;
 import android.view.WindowManager.LayoutParams;
 
-import androidx.test.filters.FlakyTest;
 
 import com.android.compatibility.common.util.PollingCheck;
 import com.android.compatibility.common.util.SystemUtil;
@@ -120,6 +119,9 @@
         // Wait for the global layout triggered by removing window.
         activity.waitForGlobalLayout();
 
+        // Wait for the activity has focus before get the visible frame
+        activity.waitAndAssertWindowFocusState(true);
+
         // Get the visible frame of the main activity after removing the window we added.
         final Rect visibleFrameAfterRemovingWindow = new Rect();
         getInstrumentation().runOnMainSync(() ->
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
index e743aff..7b38972 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
@@ -36,6 +36,7 @@
 import static org.hamcrest.Matchers.sameInstance;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
@@ -117,6 +118,14 @@
         mActivity = startActivity(TestActivity.class);
         mRootView = mActivity.getWindow().getDecorView();
         mListener = new ControlListener(mErrorCollector);
+        assumeTestCompatibility();
+    }
+
+    private void assumeTestCompatibility() {
+        if (mType == navigationBars() || mType == statusBars()) {
+            assumeTrue(Insets.NONE
+                    != mRootView.getRootWindowInsets().getInsetsIgnoringVisibility(mType));
+        }
     }
 
     @Test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
index b307ae7..3baae0b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
@@ -16,6 +16,9 @@
 
 package android.server.wm;
 
+import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;
+import static android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
+import static android.view.View.SYSTEM_UI_FLAG_LOW_PROFILE;
 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
 import static android.view.WindowInsets.Type.ime;
 import static android.view.WindowInsets.Type.navigationBars;
@@ -23,6 +26,8 @@
 import static android.view.WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE;
 import static android.view.WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_TOUCH;
 import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
+import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
 
 import static androidx.test.InstrumentationRegistry.getInstrumentation;
 
@@ -43,6 +48,7 @@
 import android.view.WindowInsets;
 import android.view.WindowInsets.Type;
 import android.view.WindowInsetsAnimation;
+import android.view.WindowManager;
 import android.widget.EditText;
 import android.widget.LinearLayout;
 import android.widget.TextView;
@@ -195,6 +201,73 @@
     }
 
     @Test
+    public void testSystemUiVisibilityCallbackCausedByInsets() {
+        final TestActivity activity = startActivity(TestActivity.class);
+        final View controlTarget = activity.getWindow().getDecorView();
+        final int[] targetSysUiVis = new int[1];
+        final View nonControlTarget = new View(mTargetContext);
+        final int[] nonTargetSysUiVis = new int[1];
+        final WindowManager.LayoutParams nonTargetAttrs =
+                new WindowManager.LayoutParams(TYPE_APPLICATION);
+        nonTargetAttrs.flags = FLAG_NOT_FOCUSABLE;
+        getInstrumentation().runOnMainSync(() -> {
+            controlTarget.setOnSystemUiVisibilityChangeListener(
+                    visibility -> targetSysUiVis[0] = visibility);
+            nonControlTarget.setOnSystemUiVisibilityChangeListener(
+                    visibility -> nonTargetSysUiVis[0] = visibility);
+            activity.getWindowManager().addView(nonControlTarget, nonTargetAttrs);
+        });
+        waitForIdle();
+        testSysUiVisCallbackCausedByInsets(statusBars(), SYSTEM_UI_FLAG_FULLSCREEN,
+                controlTarget, targetSysUiVis, nonTargetSysUiVis);
+        testSysUiVisCallbackCausedByInsets(navigationBars(), SYSTEM_UI_FLAG_HIDE_NAVIGATION,
+                controlTarget, targetSysUiVis, nonTargetSysUiVis);
+    }
+
+    private void testSysUiVisCallbackCausedByInsets(int insetsType, int sysUiFlag, View target,
+            int[] targetSysUiVis, int[] nonTargetSysUiVis) {
+        if (target.getRootWindowInsets().isVisible(insetsType)) {
+
+            // Controlled by methods
+            getInstrumentation().runOnMainSync(
+                    () -> target.getWindowInsetsController().hide(insetsType));
+            PollingCheck.waitFor(TIMEOUT, () ->
+                    targetSysUiVis[0] == sysUiFlag && targetSysUiVis[0] == nonTargetSysUiVis[0]);
+            getInstrumentation().runOnMainSync(
+                    () -> target.getWindowInsetsController().show(insetsType));
+            PollingCheck.waitFor(TIMEOUT, () ->
+                    targetSysUiVis[0] == 0 && targetSysUiVis[0] == nonTargetSysUiVis[0]);
+
+            // Controlled by legacy flags
+            getInstrumentation().runOnMainSync(
+                    () -> target.setSystemUiVisibility(sysUiFlag));
+            PollingCheck.waitFor(TIMEOUT, () ->
+                    targetSysUiVis[0] == sysUiFlag && targetSysUiVis[0] == nonTargetSysUiVis[0]);
+            getInstrumentation().runOnMainSync(
+                    () -> target.setSystemUiVisibility(0));
+            PollingCheck.waitFor(TIMEOUT, () ->
+                    targetSysUiVis[0] == 0 && targetSysUiVis[0] == nonTargetSysUiVis[0]);
+        }
+    }
+
+    @Test
+    public void testSystemUiVisibilityCallbackCausedByAppearance() {
+        final TestActivity activity = startActivity(TestActivity.class);
+        final View controlTarget = activity.getWindow().getDecorView();
+        final int[] targetSysUiVis = new int[1];
+        getInstrumentation().runOnMainSync(() -> {
+            controlTarget.setOnSystemUiVisibilityChangeListener(
+                    visibility -> targetSysUiVis[0] = visibility);
+        });
+        waitForIdle();
+        final int sysUiFlag = SYSTEM_UI_FLAG_LOW_PROFILE;
+        getInstrumentation().runOnMainSync(() -> controlTarget.setSystemUiVisibility(sysUiFlag));
+        PollingCheck.waitFor(TIMEOUT, () -> targetSysUiVis[0] == sysUiFlag);
+        getInstrumentation().runOnMainSync(() -> controlTarget.setSystemUiVisibility(0));
+        PollingCheck.waitFor(TIMEOUT, () -> targetSysUiVis[0] == 0);
+    }
+
+    @Test
     public void testHideOnCreate() throws Exception {
         final TestHideOnCreateActivity activity = startActivity(TestHideOnCreateActivity.class);
         final View rootView = activity.getWindow().getDecorView();
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java
index b36f9bd..067b390 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java
@@ -30,6 +30,7 @@
 
 import static org.hamcrest.Matchers.notNullValue;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
@@ -40,6 +41,7 @@
 import android.graphics.Insets;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
+import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.Window;
@@ -62,6 +64,7 @@
 
 @Presubmit
 public class WindowInsetsPolicyTest extends ActivityManagerTestBase {
+    private static final String TAG = WindowInsetsPolicyTest.class.getSimpleName();
 
     private ComponentName mTestActivityComponentName;
 
@@ -83,6 +86,11 @@
             new ActivityTestRule<>(FullscreenWmFlagsTestActivity.class,
                     false /* initialTouchMode */, false /* launchActivity */);
 
+    @Rule
+    public final ActivityTestRule<ImmersiveFullscreenTestActivity> mImmersiveTestActivity =
+            new ActivityTestRule<>(ImmersiveFullscreenTestActivity.class,
+                    false /* initialTouchMode */, false /* launchActivity */);
+
     @Before
     @Override
     public void setUp() throws Exception {
@@ -173,6 +181,36 @@
         assertTrue(hasFullWidth && hasFullHeight);
     }
 
+    @Test
+    public void testImmersiveFullscreenHidesSystemBars() throws Throwable {
+        // Run the test twice, because the issue that shows system bars even in the immersive mode,
+        // happens at the 2nd try.
+        for (int i = 1; i <= 2; ++i) {
+            Log.d(TAG, "testImmersiveFullscreenHidesSystemBars: try" + i);
+
+            TestActivity immersiveActivity = launchAndWait(mImmersiveTestActivity);
+            WindowInsets insets = getOnMainSync(immersiveActivity::getDispatchedInsets);
+
+            assertFalse(insets.isVisible(WindowInsets.Type.statusBars()));
+            assertFalse(insets.isVisible(WindowInsets.Type.navigationBars()));
+
+            WindowInsets rootInsets = getOnMainSync(immersiveActivity::getRootInsets);
+            assertFalse(rootInsets.isVisible(WindowInsets.Type.statusBars()));
+            assertFalse(rootInsets.isVisible(WindowInsets.Type.navigationBars()));
+
+            View statusBarBgView = getOnMainSync(immersiveActivity::getStatusBarBackgroundView);
+            // The status bar background view can be non-existent or invisible.
+            assertTrue(statusBarBgView == null
+                    || statusBarBgView.getVisibility() == android.view.View.INVISIBLE);
+
+            View navigationBarBgView = getOnMainSync(
+                    immersiveActivity::getNavigationBarBackgroundView);
+            // The navigation bar background view can be non-existent or invisible.
+            assertTrue(navigationBarBgView == null
+                    || navigationBarBgView.getVisibility() == android.view.View.INVISIBLE);
+        }
+    }
+
     private void commonAsserts(WindowInsets insets) {
         assertForAllInsets("must be non-negative", insets, insetsGreaterThanOrEqualTo(Insets.NONE));
 
@@ -271,6 +309,14 @@
             return getWindow().getDecorView();
         }
 
+        View getStatusBarBackgroundView() {
+            return getWindow().getStatusBarBackgroundView();
+        }
+
+        View getNavigationBarBackgroundView() {
+            return getWindow().getNavigationBarBackgroundView();
+        }
+
         WindowInsets getRootInsets() {
             return getWindow().getDecorView().getRootWindowInsets();
         }
@@ -299,4 +345,22 @@
         }
     }
 
+    public static class ImmersiveFullscreenTestActivity extends TestActivity {
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            // See https://developer.android.com/training/system-ui/immersive#EnableFullscreen
+            getDecorView().setSystemUiVisibility(
+                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+                    // Set the content to appear under the system bars so that the
+                    // content doesn't resize when the system bars hide and show.
+                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+                    // Hide the nav bar and status bar
+                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
+        }
+    }
 }
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
index 951d1a7..1a069d0 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/MockIme.java
@@ -44,6 +44,7 @@
 import android.view.Gravity;
 import android.view.KeyEvent;
 import android.view.View;
+import android.view.ViewGroup;
 import android.view.Window;
 import android.view.WindowInsets;
 import android.view.WindowManager;
@@ -579,11 +580,10 @@
             mSuggestionView.removeAllViews();
             for (int i = 0; i < pendingInlineSuggestions.mTotalCount; i++) {
                 View view = pendingInlineSuggestions.mViews[i];
-                Size size = pendingInlineSuggestions.mViewSizes[i];
-                if (view == null || size == null) {
+                if (view == null) {
                     continue;
                 }
-                mSuggestionView.addView(view, size.getWidth(), size.getHeight());
+                mSuggestionView.addView(view);
             }
         }
     }
@@ -711,7 +711,6 @@
         final InlineSuggestionsResponse mResponse;
         final int mTotalCount;
         final View[] mViews;
-        final Size[] mViewSizes;
         final AtomicInteger mInflatedViewCount;
         final AtomicBoolean mValid = new AtomicBoolean(true);
 
@@ -719,7 +718,6 @@
             mResponse = response;
             mTotalCount = response.getInlineSuggestions().size();
             mViews = new View[mTotalCount];
-            mViewSizes = new Size[mTotalCount];
             mInflatedViewCount = new AtomicInteger(0);
         }
     }
@@ -761,16 +759,14 @@
                 final int index = i;
                 InlineSuggestion inlineSuggestion =
                         pendingInlineSuggestions.mResponse.getInlineSuggestions().get(index);
-                Size size = inlineSuggestion.getInfo().getInlinePresentationSpec().getMaxSize();
                 inlineSuggestion.inflate(
                         this,
-                        size,
+                        new Size(WRAP_CONTENT, WRAP_CONTENT),
                         executorService,
                         suggestionView -> {
                             Log.d(TAG, "new inline suggestion view ready");
                             if (suggestionView != null) {
                                 pendingInlineSuggestions.mViews[index] = suggestionView;
-                                pendingInlineSuggestions.mViewSizes[index] = size;
                             }
                             if (pendingInlineSuggestions.mInflatedViewCount.incrementAndGet()
                                     == pendingInlineSuggestions.mTotalCount
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java
index 2d3a344..23e4dd8 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/FocusHandlingTest.java
@@ -562,9 +562,7 @@
             CtsTouchUtils.emulateTapOnViewCenter(instrumentation, null, editText);
             TestUtils.waitOnMainUntil(() -> editTextHasWindowFocus.get()
                     && !popupTextHasWindowFocus.get(), TIMEOUT);
-            // Expect there is no "onStartInput" when window focus back to activity's EditText.
-            // Since the EditText still has view focus and served by InputMethodManager.
-            notExpectEvent(stream, editorMatcher("onStartInput", marker), NOT_EXPECT_TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInput", marker), TIMEOUT);
             expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()), TIMEOUT);
         }
     }
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java b/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java
index 3a57360..b817a2c 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/util/WindowFocusHandleService.java
@@ -21,7 +21,6 @@
 import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
 import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
 import static android.view.WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
-import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
 
 import android.app.Service;
@@ -131,12 +130,6 @@
                 150, 150, pos.x, pos.y,
                 TYPE_APPLICATION_OVERLAY, FLAG_NOT_FOCUSABLE,
                 PixelFormat.OPAQUE);
-        // Currently SOFT_INPUT_STATE_UNSPECIFIED isn't appropriate for CTS test because there is no
-        // clear spec about how it behaves.  In order to make our tests deterministic, currently we
-        // must use SOFT_INPUT_STATE_HIDDEN to make sure soft-keyboard will hide after navigating
-        // forward to next window.
-        // TODO(Bug 77152727): Remove the following code once we define how
-        params.softInputMode = SOFT_INPUT_STATE_HIDDEN;
         wm.addView(editText, params);
         return editText;
     }
diff --git a/tests/media/AndroidManifest.xml b/tests/media/AndroidManifest.xml
index 343ab29..7cd34c5 100644
--- a/tests/media/AndroidManifest.xml
+++ b/tests/media/AndroidManifest.xml
@@ -22,6 +22,7 @@
     <uses-permission android:name="android.permission.INTERNET" />
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application
         android:requestLegacyExternalStorage="true"
diff --git a/tests/providerui/AndroidManifest.xml b/tests/providerui/AndroidManifest.xml
index 8434397..b967cff 100644
--- a/tests/providerui/AndroidManifest.xml
+++ b/tests/providerui/AndroidManifest.xml
@@ -25,6 +25,7 @@
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 
     <application android:requestLegacyExternalStorage = "true">
diff --git a/tests/sensor/AndroidManifest.xml b/tests/sensor/AndroidManifest.xml
index d1a9811..ee866aa 100644
--- a/tests/sensor/AndroidManifest.xml
+++ b/tests/sensor/AndroidManifest.xml
@@ -22,6 +22,7 @@
     <uses-permission android:name="android.permission.BODY_SENSORS" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application
             android:requestLegacyExternalStorage="true">
diff --git a/tests/signature/intent-check/AndroidManifest.xml b/tests/signature/intent-check/AndroidManifest.xml
index 7917120..8938b1e 100644
--- a/tests/signature/intent-check/AndroidManifest.xml
+++ b/tests/signature/intent-check/AndroidManifest.xml
@@ -18,6 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.signature.cts.intent">
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 
     <application android:requestLegacyExternalStorage="true">
diff --git a/tests/signature/intent-check/AndroidTest.xml b/tests/signature/intent-check/AndroidTest.xml
index e9c79f8..7dbf56a 100644
--- a/tests/signature/intent-check/AndroidTest.xml
+++ b/tests/signature/intent-check/AndroidTest.xml
@@ -28,8 +28,8 @@
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
         <option name="run-command" value="mkdir -p /data/local/tmp/signature-test-packages" />
         <option name='run-command'
-            value='pm list packages | while read a; do dumpsys package ${a#"package:"} > /data/local/tmp/signature-test-packages/${a#"package:"}.txt; done' />
-        <option name="teardown-command" value="mkdir -p /data/local/tmp/signature-test-packages" />
+            value='pm list packages --user cur| while read a; do dumpsys package ${a#"package:"} > /data/local/tmp/signature-test-packages/${a#"package:"}.txt; done' />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test-packages" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
         <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
diff --git a/tests/tests/car/src/android/car/cts/CarWatchdogDaemonTest.java b/tests/tests/car/src/android/car/cts/CarWatchdogDaemonTest.java
index 29ca7c7..4e45759 100644
--- a/tests/tests/car/src/android/car/cts/CarWatchdogDaemonTest.java
+++ b/tests/tests/car/src/android/car/cts/CarWatchdogDaemonTest.java
@@ -84,8 +84,9 @@
 
     @Test
     public void testRecordsIoPerformanceData() throws Exception {
+        String packageName = getContext().getPackageName();
         runShellCommand("dumpsys " + CAR_WATCHDOG_SERVICE_NAME
-                + " --start_io --interval 5 --max_duration 120");
+                + " --start_io --interval 5 --max_duration 120 --filter_packages " + packageName);
         long writtenBytes = writeToDisk(testDir);
         assertWithMessage("Failed to write data to dir '" + testDir.getAbsolutePath() + "'").that(
                 writtenBytes).isGreaterThan(0L);
@@ -95,8 +96,6 @@
         Log.i(TAG, "stop results:" + contents);
         assertWithMessage("Failed to custom collect I/O performance data").that(
                 contents).isNotEmpty();
-        PackageManager packageManager = getContext().getPackageManager();
-        String packageName = packageManager.getNameForUid(Process.myUid());
         long recordedBytes = parseDump(contents, UserHandle.getUserId(Process.myUid()),
                 packageName);
         assertThat(recordedBytes).isAtLeast(writtenBytes);
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanDeqpLevelTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanDeqpLevelTest.java
index 0374082..a736878 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanDeqpLevelTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanDeqpLevelTest.java
@@ -68,7 +68,7 @@
         }
     }
 
-    @CddTest(requirement = "7.1.4.2/C-1-8")
+    @CddTest(requirement = "7.1.4.2/C-1-8,C-1-9")
     @Test
     public void testVulkanDeqpLevel() {
         if (mVulkanHardwareVersion.version >= VULKAN_1_0) {
diff --git a/tests/tests/media/src/android/media/cts/AudioMetadataTest.java b/tests/tests/media/src/android/media/cts/AudioMetadataTest.java
index bafd83d..9a7cd26 100755
--- a/tests/tests/media/src/android/media/cts/AudioMetadataTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioMetadataTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.*;
 import static org.testng.Assert.assertThrows;
 
+import android.media.AudioFormat;
 import android.media.AudioMetadata;
 import android.media.AudioMetadataMap;
 import android.media.AudioMetadataReadMap;
@@ -117,6 +118,31 @@
         assertEquals(audioMetadata, audioMetadata.dup());
     }
 
+    @Test
+    public void testFormatKeys() throws Exception {
+        final AudioMetadataMap audioMetadata = AudioMetadata.createMap();
+        audioMetadata.set(AudioMetadata.Format.KEY_ATMOS_PRESENT, true);
+        audioMetadata.set(AudioMetadata.Format.KEY_AUDIO_ENCODING, AudioFormat.ENCODING_MP3);
+        audioMetadata.set(AudioMetadata.Format.KEY_BIT_RATE, 64000);
+        audioMetadata.set(AudioMetadata.Format.KEY_BIT_WIDTH, 16);
+        audioMetadata.set(AudioMetadata.Format.KEY_CHANNEL_MASK, AudioFormat.CHANNEL_OUT_STEREO);
+        audioMetadata.set(AudioMetadata.Format.KEY_MIME, "audio/mp3");
+        audioMetadata.set(AudioMetadata.Format.KEY_SAMPLE_RATE, 48000);
+
+        assertEquals(64000, (int)audioMetadata.get(AudioMetadata.Format.KEY_BIT_RATE));
+        assertEquals(AudioFormat.CHANNEL_OUT_STEREO,
+                (int)audioMetadata.get(AudioMetadata.Format.KEY_CHANNEL_MASK));
+        assertEquals("audio/mp3", (String)audioMetadata.get(AudioMetadata.Format.KEY_MIME));
+        assertEquals(48000, (int)audioMetadata.get(AudioMetadata.Format.KEY_SAMPLE_RATE));
+        assertEquals(16, (int)audioMetadata.get(AudioMetadata.Format.KEY_BIT_WIDTH));
+        assertEquals(true, (boolean)audioMetadata.get(AudioMetadata.Format.KEY_ATMOS_PRESENT));
+        assertEquals(AudioFormat.ENCODING_MP3,
+                (int)audioMetadata.get(AudioMetadata.Format.KEY_AUDIO_ENCODING));
+
+        // Additional test to ensure we can survive parceling
+        testPackingAndUnpacking((AudioMetadata.BaseMap)audioMetadata);
+    }
+
     // Vendor keys created by direct override of the AudioMetadata interface.
     private static final AudioMetadata.Key<Integer>
         KEY_VENDOR_INTEGER = new AudioMetadata.Key<Integer>() {
@@ -276,16 +302,7 @@
 
     @Test
     public void testUnpackingByteBuffer() throws Exception {
-        ByteBuffer bufferPackedAtJava = AudioMetadata.toByteBuffer(
-                AUDIO_METADATA_REFERENCE, ByteOrder.nativeOrder());
-        assertNotNull(bufferPackedAtJava);
-        ByteBuffer buffer = nativeGetByteBuffer(bufferPackedAtJava, bufferPackedAtJava.limit());
-        assertNotNull(buffer);
-        buffer.order(ByteOrder.nativeOrder());
-
-        AudioMetadata.BaseMap metadataFromByteBuffer = AudioMetadata.fromByteBuffer(buffer);
-        assertNotNull(metadataFromByteBuffer);
-        assertEquals(metadataFromByteBuffer, AUDIO_METADATA_REFERENCE);
+        testPackingAndUnpacking(AUDIO_METADATA_REFERENCE);
     }
 
     @Test
@@ -303,6 +320,19 @@
         assertNull(metadataFromByteBuffer);
     }
 
+    private static void testPackingAndUnpacking(AudioMetadata.BaseMap audioMetadata) {
+        ByteBuffer bufferPackedAtJava = AudioMetadata.toByteBuffer(
+                audioMetadata, ByteOrder.nativeOrder());
+        assertNotNull(bufferPackedAtJava);
+        ByteBuffer buffer = nativeGetByteBuffer(bufferPackedAtJava, bufferPackedAtJava.limit());
+        assertNotNull(buffer);
+        buffer.order(ByteOrder.nativeOrder());
+
+        AudioMetadata.BaseMap metadataFromByteBuffer = AudioMetadata.fromByteBuffer(buffer);
+        assertNotNull(metadataFromByteBuffer);
+        assertEquals(metadataFromByteBuffer, audioMetadata);
+    }
+
     static {
         System.loadLibrary("audio_jni");
     }
diff --git a/tests/tests/mediastress/AndroidManifest.xml b/tests/tests/mediastress/AndroidManifest.xml
index b847ff5..81d8a00 100644
--- a/tests/tests/mediastress/AndroidManifest.xml
+++ b/tests/tests/mediastress/AndroidManifest.xml
@@ -25,6 +25,7 @@
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application
         android:requestLegacyExternalStorage="true">
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
index afaea87..c6f7184 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
@@ -1627,6 +1627,7 @@
                 if (isGlFormat) {
                     glRenderbufferStorage(GL_RENDERBUFFER, GetParam().format, width, height);
                 } else {
+                    ASSERT_FALSE(FormatIsYuv(GetParam().format)) << "YUV renderbuffers unsupported";
                     glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER,
                                                            static_cast<GLeglImageOES>(mEGLImage));
                 }
@@ -1869,8 +1870,17 @@
 
     for (int i = 0; i < mContextCount; ++i) {
         MakeCurrent(i);
-        ASSERT_NO_FATAL_FAILURE(
-            SetUpFramebuffer(desc.width, desc.height, 0, kBufferAsRenderbuffer));
+
+        // YUV renderbuffers are unsupported, so we attach as a texture in this case.
+        AttachmentType attachmentType;
+        if (FormatIsYuv(desc.format)) {
+            ASSERT_NO_FATAL_FAILURE(SetUpTexture(desc, 1));
+            attachmentType = kBufferAsTexture;
+        } else {
+            attachmentType = kBufferAsRenderbuffer;
+        }
+
+        ASSERT_NO_FATAL_FAILURE(SetUpFramebuffer(desc.width, desc.height, 0, attachmentType));
     }
 
     // Draw a simple checkerboard pattern in the second context, which will
@@ -1903,8 +1913,18 @@
     if (!SetUpBuffer(desc)) return;
 
     MakeCurrent(1);
-    ASSERT_NO_FATAL_FAILURE(
-        SetUpFramebuffer(desc.width, desc.height, 0, kBufferAsRenderbuffer));
+
+    // YUV renderbuffers are unsupported, so we attach as a texture in this case.
+    AttachmentType attachmentType;
+    if (FormatIsYuv(desc.format)) {
+        ASSERT_NO_FATAL_FAILURE(SetUpTexture(desc, 1));
+        attachmentType = kBufferAsTexture;
+    } else {
+        attachmentType = kBufferAsRenderbuffer;
+    }
+
+    ASSERT_NO_FATAL_FAILURE(SetUpFramebuffer(desc.width, desc.height, 0, attachmentType));
+
     // Draw a simple checkerboard pattern in the second context, which will
     // be current after the loop above, then read it in the first.
     DrawCheckerboard(desc.width, desc.height, desc.format);
@@ -2614,4 +2634,4 @@
         AHardwareBuffer_Desc{17, 23, 7, AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT, 0, 0, 0, 0}),
     &GetTestName);
 
-}  // namespace android
+}  // namespace android
\ No newline at end of file
diff --git a/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java b/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java
index a2b8189..37d7c57 100644
--- a/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java
+++ b/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java
@@ -34,6 +34,7 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 import android.os.UserHandle;
@@ -201,7 +202,6 @@
 
         try {
             mUi.adoptShellPermissionIdentity("android.permission.STATUS_BAR_SERVICE");
-            mNotificationManager.cancelAll();
             mNotificationManager.allowAssistantAdjustment(Adjustment.KEY_RANKING_SCORE);
             mUi.dropShellPermissionIdentity();
 
@@ -220,8 +220,6 @@
 
             int currentRank1 = out1.getRank();
             int currentRank2 = out2.getRank();
-            int newRank1 = out2.getRank();
-            int newRank2 = out1.getRank();
 
             float rankingScore1 = (currentRank1 > currentRank2) ? 1f : 0;
             float rankingScore2 = (currentRank1 > currentRank2) ? 0 : 1f;
@@ -240,8 +238,13 @@
             mNotificationListenerService.mRankingMap.getRanking(sbn1.getKey(), out1);
             mNotificationListenerService.mRankingMap.getRanking(sbn2.getKey(), out2);
 
-            assertEquals(newRank1, out1.getRank());
-            assertEquals(newRank2, out2.getRank());
+            int newRank1 = out1.getRank();
+            int newRank2 = out2.getRank();
+            if (currentRank1 > currentRank2) {
+                assertTrue(newRank1 < newRank2);
+            } else {
+                assertTrue(newRank1 > newRank2);
+            }
         } finally {
             mUi.adoptShellPermissionIdentity("android.permission.STATUS_BAR_SERVICE");
             mNotificationManager.disallowAssistantAdjustment(Adjustment.KEY_RANKING_SCORE);
@@ -544,6 +547,9 @@
 
     @Test
     public void testOnNotificationVisibilityChanged() throws Exception {
+        if (isTelevision()) {
+            return;
+        }
         setUpListeners();
         turnScreenOn();
         mUi.adoptShellPermissionIdentity("android.permission.EXPAND_STATUS_BAR");
@@ -572,6 +578,9 @@
 
     @Test
     public void testOnNotificationsSeen() throws Exception {
+        if (isTelevision()) {
+            return;
+        }
         setUpListeners();
         turnScreenOn();
         mUi.adoptShellPermissionIdentity("android.permission.EXPAND_STATUS_BAR");
@@ -594,6 +603,9 @@
 
     @Test
     public void testOnPanelRevealedAndHidden() throws Exception {
+        if (isTelevision()) {
+            return;
+        }
         setUpListeners();
         turnScreenOn();
         mUi.adoptShellPermissionIdentity("android.permission.EXPAND_STATUS_BAR");
@@ -669,11 +681,18 @@
         mNotificationManager.notify(id, notification);
     }
 
-   private void turnScreenOn() throws IOException {
-       Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
-       runCommand("input keyevent KEYCODE_WAKEUP", instrumentation);
-       runCommand("wm dismiss-keyguard", instrumentation);
-   }
+    private void turnScreenOn() throws IOException {
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        runCommand("input keyevent KEYCODE_WAKEUP", instrumentation);
+        runCommand("wm dismiss-keyguard", instrumentation);
+    }
+
+    private boolean isTelevision() {
+        PackageManager packageManager = mContext.getPackageManager();
+        return packageManager != null
+                && (packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+                || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION));
+    }
 
     private void toggleListenerAccess(boolean on) throws IOException {
 
diff --git a/tests/tests/os/AndroidManifest.xml b/tests/tests/os/AndroidManifest.xml
index 7c9ea67..07de155 100644
--- a/tests/tests/os/AndroidManifest.xml
+++ b/tests/tests/os/AndroidManifest.xml
@@ -34,6 +34,7 @@
     <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.VIBRATE" />
     <uses-permission android:name="android.permission.ACCESS_VIBRATOR_STATE" />
diff --git a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
index 739bc21..39d8f1b 100644
--- a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
+++ b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
@@ -16,7 +16,6 @@
 
 package android.os.cts
 
-import android.Manifest.permission.READ_CALENDAR
 import android.content.Intent
 import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
 import android.content.pm.PackageManager
@@ -175,17 +174,18 @@
         }
     }
 
-    // TODO grantRuntimePermission fails to grant permission
     @AppModeFull(reason = "Uses separate apps for testing")
-    fun _testInstallGrants_notRevokedImmediately() {
+    fun testInstallGrants_notRevokedImmediately() {
         wakeUpScreen()
         withUnusedThresholdMs(TimeUnit.DAYS.toMillis(30)) {
             withDummyApp {
                 // Setup
-                runWithShellPermissionIdentity {
-                    instrumentation.uiAutomation
-                            .grantRuntimePermission(APK_PACKAGE_NAME, READ_CALENDAR)
-                }
+                goToPermissions()
+                click("Calendar")
+                click("Allow")
+                goBack()
+                goBack()
+                goBack()
                 eventually {
                     assertPermission(PERMISSION_GRANTED)
                 }
@@ -283,11 +283,7 @@
 //        }
 
         try {
-            context.startActivity(Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
-                    .setData(Uri.fromParts("package", packageName, null))
-                    .addFlags(FLAG_ACTIVITY_NEW_TASK))
-
-            waitFindNode(hasTextThat(containsStringIgnoringCase("Permissions"))).click()
+            goToPermissions(packageName)
 
             waitForIdle()
             val ui = instrumentation.uiAutomation.rootInActiveWindow
@@ -315,6 +311,18 @@
         }
     }
 
+    private fun goToPermissions(packageName: String = APK_PACKAGE_NAME) {
+        context.startActivity(Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
+                .setData(Uri.fromParts("package", packageName, null))
+                .addFlags(FLAG_ACTIVITY_NEW_TASK))
+
+        click("Permissions")
+    }
+
+    private fun click(label: String) {
+        waitFindNode(hasTextThat(containsStringIgnoringCase(label))).click()
+    }
+
     private fun assertWhitelistState(state: Boolean) {
         assertThat(
             waitFindObject(By.textStartsWith("Auto-revoke whitelisted: ")).text,
diff --git a/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/AndroidManifest.xml b/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/AndroidManifest.xml
index 179f19a..04084e7 100644
--- a/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/AndroidManifest.xml
+++ b/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/AndroidManifest.xml
@@ -21,6 +21,7 @@
     android:sharedUserId="android.permission2.cts.restrictedpermissionuser.shareduid">
 
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application android:label="CtsLegacyStorageNotIsolatedWithSharedUid"
          android:requestLegacyExternalStorage="true" />
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/AndroidManifest.xml b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/AndroidManifest.xml
index b5b5df3..bda5436 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/AndroidManifest.xml
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/AndroidManifest.xml
@@ -22,6 +22,7 @@
     <!-- Storage -->
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <uses-sdk android:targetSdkVersion="30"/>
 
diff --git a/tests/tests/preference/AndroidManifest.xml b/tests/tests/preference/AndroidManifest.xml
index 2d7e827..b861458 100644
--- a/tests/tests/preference/AndroidManifest.xml
+++ b/tests/tests/preference/AndroidManifest.xml
@@ -24,6 +24,7 @@
     <!-- Needed permission and android:requestLegacyExternalStorage to dump screenshots in case of
          failure -->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application android:requestLegacyExternalStorage="true">
         <uses-library android:name="android.test.runner" />
diff --git a/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java b/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java
index 5ab6ad7..71ab682 100644
--- a/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java
+++ b/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java
@@ -70,14 +70,15 @@
     private static final String LOG_TAG = "PrintDocumentAdapterContractTest";
 
     @Before
-    public void setDefaultPrinter() throws Exception {
+    public void setup() throws Throwable {
+        clearPrintSpoolerData();
+
         FirstPrintService.setCallbacks(createFirstMockPrintServiceCallbacks());
         SecondPrintService.setCallbacks(createSecondMockPrintServiceCallbacks());
-    }
 
-    @Before
-    public void clearPrintSpoolerState() throws Exception {
-        clearPrintSpoolerData();
+        makeDefaultPrinter(createDefaultPrintDocumentAdapter(1), "Fourth printer");
+
+        resetCounters();
     }
 
     @Test
@@ -130,9 +131,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for finish.
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -378,9 +376,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             waitForPrinterDiscoverySessionDestroyCallbackCalled(1);
         }, OPERATION_TIMEOUT_MILLIS * 2);
     }
@@ -463,9 +458,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for a finish.
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -648,9 +640,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Printing will abort automatically
 
             // Wait for a finish.
@@ -729,9 +718,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for a finish.
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -868,9 +854,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for a finish.
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -983,9 +966,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for a finish.
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -1083,9 +1063,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for a finish.
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -1476,9 +1453,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for the session to be destroyed to isolate tests.
             waitForPrinterDiscoverySessionDestroyCallbackCalled(1);
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -1545,9 +1519,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             // Wait for the session to be destroyed to isolate tests.
             waitForPrinterDiscoverySessionDestroyCallbackCalled(1);
         }, OPERATION_TIMEOUT_MILLIS * 2);
@@ -1961,9 +1932,6 @@
         mPrintHelper.submitPrintJob();
 
         eventually(() -> {
-            // Answer the dialog for the print service cloud warning
-            answerPrintServicesWarning(true);
-
             waitForAdapterFinishCallbackCalled();
         }, OPERATION_TIMEOUT_MILLIS * 2);
 
@@ -2044,6 +2012,28 @@
                 printers.add(thirdPrinter);
 
                 session.addPrinters(printers);
+
+                // Add the fourth printer matching the "Save to PDF printer".
+                PrinterId forthPrinterId = service.generatePrinterId("forth_printer");
+                PrinterCapabilitiesInfo fourthCapabilities =
+                        null;
+                try {
+                    fourthCapabilities = new PrinterCapabilitiesInfo.Builder(forthPrinterId)
+                            .addMediaSize(MediaSize.NA_LETTER, true)
+                            .addResolution(new Resolution("300x300", "300x300", 300, 300), true)
+                            .setColorModes(PrintAttributes.COLOR_MODE_COLOR,
+                                    PrintAttributes.COLOR_MODE_COLOR)
+                            .build();
+                } catch (Exception e) {
+                    Log.e(LOG_TAG, "Cannot create fourth printer", e);
+                }
+                PrinterInfo forthPrinter = new PrinterInfo.Builder(forthPrinterId,
+                        "Fourth printer", PrinterInfo.STATUS_IDLE)
+                        .setCapabilities(fourthCapabilities)
+                        .build();
+                printers.add(forthPrinter);
+
+                session.addPrinters(printers);
             }
             return null;
         }, null, null, null, null, null, invocation -> {
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java
index fd96d40..106cd6f 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_MediaTest.java
@@ -296,6 +296,43 @@
         }
     }
 
+    /**
+     * b/155320967 Test that update with conflict is resolved as replace.
+     */
+    @Test
+    public void testUpdateAndReplace() throws Exception {
+        File file = null;
+        try {
+            // Create file
+            file = copyResourceToFile(R.raw.scenery, DCIM_DIR, "cts" + System.nanoTime() + ".jpg");
+            final String externalPath = file.getAbsolutePath();
+            assertNotNull(MediaStore.scanFile(mContentResolver, file));
+
+            // Insert another file, insertedFile doesn't exist in lower file system.
+            ContentValues values = new ContentValues();
+            final File insertedFile = new File(DCIM_DIR, "cts" + System.nanoTime() + ".jpg");
+            values.put(Media.DATA, insertedFile.getAbsolutePath());
+
+            final Uri uri = mContentResolver.insert(mExternalImages, values);
+            assertNotNull(uri);
+
+            // Now update the second file to the same file path as the first file.
+            values.put(Media.DATA, externalPath);
+            // This update is implemented as update and replace on conflict and shouldn't throw
+            // UNIQUE constraint error.
+            assertEquals(1, mContentResolver.update(uri, values, Bundle.EMPTY));
+            Uri scannedUri = MediaStore.scanFile(mContentResolver, file);
+            assertNotNull(scannedUri);
+
+            // _id in inserted uri and scannedUri should be same.
+            assertEquals(uri.getLastPathSegment(), scannedUri.getLastPathSegment());
+        } finally {
+            if (file != null) {
+                file.delete();
+            }
+        }
+    }
+
     @Test
     public void testUpsert() throws Exception {
         File file = null;
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk b/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
index 4e0d109..384213f 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
Binary files differ
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk b/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
index aac758e..7c2fd22 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
Binary files differ
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk b/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
index 040251e..8e8fef8 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/FileIntegrityManagerTest.java b/tests/tests/security/src/android/security/cts/FileIntegrityManagerTest.java
index 2d65976..afb4397 100644
--- a/tests/tests/security/src/android/security/cts/FileIntegrityManagerTest.java
+++ b/tests/tests/security/src/android/security/cts/FileIntegrityManagerTest.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.security.FileIntegrityManager;
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.RestrictedBuildTest;
 import android.platform.test.annotations.SecurityTest;
 import android.util.Log;
@@ -36,6 +37,7 @@
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 
+@AppModeFull
 @SecurityTest
 public class FileIntegrityManagerTest extends CtsAndroidTestCase {
 
diff --git a/tests/tests/sharesheet/AndroidManifest.xml b/tests/tests/sharesheet/AndroidManifest.xml
index 3d83056..5723d51 100644
--- a/tests/tests/sharesheet/AndroidManifest.xml
+++ b/tests/tests/sharesheet/AndroidManifest.xml
@@ -26,6 +26,7 @@
     <!-- Needed permission and android:requestLegacyExternalStorage to dump screenshots in case of
          failure -->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
 
     <application 
         android:requestLegacyExternalStorage="true"
diff --git a/tests/tests/systemui/AndroidManifest.xml b/tests/tests/systemui/AndroidManifest.xml
index 292ef90..c7732c2 100644
--- a/tests/tests/systemui/AndroidManifest.xml
+++ b/tests/tests/systemui/AndroidManifest.xml
@@ -21,6 +21,7 @@
     <uses-permission android:name="android.permission.INJECT_EVENTS" />
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
     <application android:requestLegacyExternalStorage="true">
         <activity android:name=".LightBarActivity"
                 android:theme="@android:style/Theme.Material.NoActionBar"
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/BatteryStatsManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/BatteryStatsManagerTest.java
new file mode 100644
index 0000000..f16c83d
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/BatteryStatsManagerTest.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.telephony.cts;
+
+import static androidx.test.InstrumentationRegistry.getContext;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Matchers.anyInt;
+
+import android.os.BatteryStatsManager;
+import android.os.connectivity.CellularBatteryStats;
+
+import org.junit.Test;
+
+/**
+ * Test BatteryStatsManager and CellularBatteryStats to ensure that valid data is being reported
+ * and that invalid data is not reported.
+ */
+public class BatteryStatsManagerTest{
+
+    /** Test that {@link CellularBatteryStats} getters return sane values. */
+    @Test
+    public void testGetCellularBatteryStats() {
+        BatteryStatsManager bsm = getContext().getSystemService(BatteryStatsManager.class);
+        CellularBatteryStats cellularBatteryStats = bsm.getCellularBatteryStats();
+
+        assertThat(cellularBatteryStats.getEnergyConsumedMaMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getIdleTimeMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getLoggingDurationMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getKernelActiveTimeMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getMonitoredRailChargeConsumedMaMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getNumBytesRx()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getNumBytesTx()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getNumPacketsRx()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getNumPacketsTx()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getRxTimeMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getSleepTimeMillis()).isAtLeast(0L);
+        assertThat(cellularBatteryStats.getTimeInRatMicros(anyInt())).isAtLeast(-1L);
+        assertThat(cellularBatteryStats.getTimeInRxSignalStrengthLevelMicros(
+                anyInt())).isAtLeast(-1L);
+    }
+}
+
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
index 238a8a0..0a5a374 100755
--- a/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
@@ -658,6 +658,17 @@
         } catch (SecurityException e) {
             // expected
         }
+
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.READ_PRIVILEGED_PHONE_STATE");
+        try {
+            getSmsManager().getSmscAddress();
+        } catch (SecurityException se) {
+            fail("Caller with READ_PRIVILEGED_PHONE_STATE should be able to call API");
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
     }
 
     @Test
@@ -668,6 +679,61 @@
         } catch (SecurityException e) {
             // expected
         }
+
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.MODIFY_PHONE_STATE");
+        try {
+            getSmsManager().setSmscAddress("fake smsc");
+        } catch (SecurityException se) {
+            fail("Caller with MODIFY_PHONE_STATE should be able to call API");
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
+    }
+
+    @Test
+    public void testGetPremiumSmsConsent() {
+        try {
+            getSmsManager().getPremiumSmsConsent("fake package name");
+            fail("SmsManager.getPremiumSmsConsent() should throw a SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.READ_PRIVILEGED_PHONE_STATE");
+        try {
+            getSmsManager().getPremiumSmsConsent("fake package name");
+            fail("Caller with permission but only phone/system uid is allowed");
+        } catch (SecurityException se) {
+            // expected
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
+    }
+
+    @Test
+    public void testSetPremiumSmsConsent() {
+        try {
+            getSmsManager().setPremiumSmsConsent("fake package name", 0);
+            fail("SmsManager.setPremiumSmsConsent() should throw a SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.MODIFY_PHONE_STATE");
+        try {
+            getSmsManager().setPremiumSmsConsent("fake package name", 0);
+            fail("Caller with permission but only phone/system uid is allowed");
+        } catch (SecurityException se) {
+            // expected
+        } finally {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .dropShellPermissionIdentity();
+        }
     }
 
     @Test
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SmsMessageTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SmsMessageTest.java
index 7c8c9d46..cf7bfef 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SmsMessageTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SmsMessageTest.java
@@ -26,7 +26,9 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.telephony.SmsManager;
 import android.telephony.SmsMessage;
+import android.telephony.SubscriptionManager;
 import android.telephony.TelephonyManager;
 
 import org.junit.Before;
@@ -343,6 +345,45 @@
         assertEquals(2, result[0]);
     }
 
+    @Test
+    public void testGetSmsPdu() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        SmsMessage.SubmitPdu smsPdu;
+        String scAddress = null;
+        String destinationAddress = null;
+        String message = null;
+
+        // Null message, null destination
+        smsPdu = SmsMessage.getSmsPdu(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
+                SmsManager.STATUS_ON_ICC_READ,
+                scAddress, destinationAddress, message, System.currentTimeMillis());
+        assertNull(smsPdu);
+
+        message = "This is a test message";
+
+        // Non-null message, null destination
+        smsPdu = SmsMessage.getSmsPdu(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
+                SmsManager.STATUS_ON_ICC_READ,
+                scAddress, destinationAddress, message, System.currentTimeMillis());
+        assertNull(smsPdu);
+
+        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+            // TODO: temp workaround, OCTET encoding for EMS not properly supported
+            return;
+        }
+
+        scAddress = "1650253000";
+        destinationAddress = "18004664411";
+        message = "This is a test message";
+        smsPdu = SmsMessage.getSmsPdu(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
+                SmsManager.STATUS_ON_ICC_READ,
+                scAddress, destinationAddress, message, System.currentTimeMillis());
+        assertNotNull(smsPdu);
+    }
+
     private final static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
             'A', 'B', 'C', 'D', 'E', 'F' };
 
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
index efcc408..c7b14ec 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -25,6 +25,7 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -211,12 +212,16 @@
         if (!isSupported()) return;
 
         List<SubscriptionInfo> subList = mSm.getActiveSubscriptionInfoList();
+        int[] idList = mSm.getActiveSubscriptionIdList();
         // Assert when there is no sim card present or detected
         assertNotNull("Active subscriber required", subList);
+        assertNotNull("Active subscriber required", idList);
         assertFalse("Active subscriber required", subList.isEmpty());
+        assertNotEquals("Active subscriber required", 0, idList.length);
         for (int i = 0; i < subList.size(); i++) {
             assertTrue(subList.get(i).getSubscriptionId() >= 0);
             assertTrue(subList.get(i).getSimSlotIndex() >= 0);
+            assertTrue(ArrayUtils.contains(idList, subList.get(i).getSubscriptionId()));
             if (i >= 1) {
                 assertTrue(subList.get(i - 1).getSimSlotIndex()
                         <= subList.get(i).getSimSlotIndex());
diff --git a/tests/tests/tethering/AndroidTest.xml b/tests/tests/tethering/AndroidTest.xml
index 25051ba..d0a2bce 100644
--- a/tests/tests/tethering/AndroidTest.xml
+++ b/tests/tests/tethering/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS Tethering test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="networking" />
+    <option name="config-descriptor:metadata" key="token" value="SIM_CARD" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
diff --git a/tests/tests/textclassifier/src/android/view/textclassifier/cts/TextClassifierValueObjectsTest.java b/tests/tests/textclassifier/src/android/view/textclassifier/cts/TextClassifierValueObjectsTest.java
index c6dea6d..1d7ac22 100644
--- a/tests/tests/textclassifier/src/android/view/textclassifier/cts/TextClassifierValueObjectsTest.java
+++ b/tests/tests/textclassifier/src/android/view/textclassifier/cts/TextClassifierValueObjectsTest.java
@@ -32,6 +32,10 @@
 import android.icu.util.ULocale;
 import android.os.Bundle;
 import android.os.LocaleList;
+import android.text.Spannable;
+import android.text.SpannableString;
+import android.text.Spanned;
+import android.text.style.URLSpan;
 import android.view.View;
 import android.view.textclassifier.TextClassification;
 import android.view.textclassifier.TextClassifier;
@@ -43,6 +47,8 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.google.common.collect.ImmutableMap;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -52,6 +58,7 @@
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+
 /**
  * TextClassifier value objects tests.
  *
@@ -65,13 +72,17 @@
     private static final String BUNDLE_KEY = "key";
     private static final String BUNDLE_VALUE = "value";
     private static final Bundle BUNDLE = new Bundle();
+
     static {
         BUNDLE.putString(BUNDLE_KEY, BUNDLE_VALUE);
     }
+
     private static final double ACCEPTED_DELTA = 0.0000001;
     private static final String TEXT = "abcdefghijklmnopqrstuvwxyz";
     private static final int START = 5;
     private static final int END = 20;
+    private static final int ANOTHER_START = 22;
+    private static final int ANOTHER_END = 24;
     private static final String ID = "id123";
     private static final LocaleList LOCALES = LocaleList.forLanguageTags("fr,en,de,es");
 
@@ -259,7 +270,8 @@
         final Intent intent = new Intent();
         final String label = "label";
         final Drawable icon = new ColorDrawable(Color.RED);
-        final View.OnClickListener onClick = v -> { };
+        final View.OnClickListener onClick = v -> {
+        };
 
         final TextClassification classification = new TextClassification.Builder()
                 .setText(TEXT)
@@ -382,6 +394,120 @@
     }
 
     @Test
+    public void testTextLinks_apply() {
+        final SpannableString spannableString = SpannableString.valueOf(TEXT);
+        final TextLinks textLinks = new TextLinks.Builder(TEXT)
+                .addLink(START, END, Collections.singletonMap(TextClassifier.TYPE_ADDRESS, 1.0f))
+                .addLink(ANOTHER_START, ANOTHER_END,
+                        ImmutableMap.of(TextClassifier.TYPE_PHONE, 1.0f,
+                                TextClassifier.TYPE_ADDRESS, 0.5f))
+                .build();
+
+        final int status = textLinks.apply(
+                spannableString, TextLinks.APPLY_STRATEGY_IGNORE, null);
+        final TextLinks.TextLinkSpan[] textLinkSpans = spannableString.getSpans(0,
+                spannableString.length() - 1,
+                TextLinks.TextLinkSpan.class);
+
+        assertEquals(TextLinks.STATUS_LINKS_APPLIED, status);
+        assertEquals(2, textLinkSpans.length);
+
+        final TextLinks.TextLink textLink = textLinkSpans[0].getTextLink();
+        final TextLinks.TextLink anotherTextLink = textLinkSpans[1].getTextLink();
+
+        assertEquals(START, textLink.getStart());
+        assertEquals(END, textLink.getEnd());
+        assertEquals(1, textLink.getEntityCount());
+        assertEquals(TextClassifier.TYPE_ADDRESS, textLink.getEntity(0));
+        assertEquals(1.0f, textLink.getConfidenceScore(TextClassifier.TYPE_ADDRESS),
+                ACCEPTED_DELTA);
+        assertEquals(ANOTHER_START, anotherTextLink.getStart());
+        assertEquals(ANOTHER_END, anotherTextLink.getEnd());
+        assertEquals(2, anotherTextLink.getEntityCount());
+        assertEquals(TextClassifier.TYPE_PHONE, anotherTextLink.getEntity(0));
+        assertEquals(1.0f, anotherTextLink.getConfidenceScore(TextClassifier.TYPE_PHONE),
+                ACCEPTED_DELTA);
+        assertEquals(TextClassifier.TYPE_ADDRESS, anotherTextLink.getEntity(1));
+        assertEquals(0.5f, anotherTextLink.getConfidenceScore(TextClassifier.TYPE_ADDRESS),
+                ACCEPTED_DELTA);
+    }
+
+    @Test
+    public void testTextLinks_applyStrategyReplace() {
+        final SpannableString spannableString = SpannableString.valueOf(TEXT);
+        final URLSpan urlSpan = new URLSpan("http://www.google.com");
+        spannableString.setSpan(urlSpan, START, END, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+        final TextLinks textLinks = new TextLinks.Builder(TEXT)
+                .addLink(START, END, Collections.singletonMap(TextClassifier.TYPE_ADDRESS, 1.0f))
+                .build();
+
+        final int status = textLinks.apply(
+                spannableString, TextLinks.APPLY_STRATEGY_REPLACE, null);
+        final TextLinks.TextLinkSpan[] textLinkSpans = spannableString.getSpans(0,
+                spannableString.length() - 1,
+                TextLinks.TextLinkSpan.class);
+        final URLSpan[] urlSpans = spannableString.getSpans(0, spannableString.length() - 1,
+                URLSpan.class);
+
+        assertEquals(TextLinks.STATUS_LINKS_APPLIED, status);
+        assertEquals(1, textLinkSpans.length);
+        assertEquals(0, urlSpans.length);
+    }
+
+    @Test
+    public void testTextLinks_applyStrategyIgnore() {
+        final SpannableString spannableString = SpannableString.valueOf(TEXT);
+        final URLSpan urlSpan = new URLSpan("http://www.google.com");
+        spannableString.setSpan(urlSpan, START, END, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+        final TextLinks textLinks = new TextLinks.Builder(TEXT)
+                .addLink(START, END, Collections.singletonMap(TextClassifier.TYPE_ADDRESS, 1.0f))
+                .build();
+
+        final int status = textLinks.apply(
+                spannableString, TextLinks.APPLY_STRATEGY_IGNORE, null);
+        final TextLinks.TextLinkSpan[] textLinkSpans = spannableString.getSpans(0,
+                spannableString.length() - 1,
+                TextLinks.TextLinkSpan.class);
+        final URLSpan[] urlSpans = spannableString.getSpans(0, spannableString.length() - 1,
+                URLSpan.class);
+
+        assertEquals(TextLinks.STATUS_NO_LINKS_APPLIED, status);
+        assertEquals(0, textLinkSpans.length);
+        assertEquals(1, urlSpans.length);
+    }
+
+    @Test
+    public void testTextLinks_applyWithCustomSpanFactory() {
+        final class CustomTextLinkSpan extends TextLinks.TextLinkSpan {
+            private CustomTextLinkSpan(TextLinks.TextLink textLink) {
+                super(textLink);
+            }
+        }
+        final SpannableString spannableString = SpannableString.valueOf(TEXT);
+        final TextLinks textLinks = new TextLinks.Builder(TEXT)
+                .addLink(START, END, Collections.singletonMap(TextClassifier.TYPE_ADDRESS, 1.0f))
+                .build();
+
+        final int status = textLinks.apply(
+                spannableString, TextLinks.APPLY_STRATEGY_IGNORE, CustomTextLinkSpan::new);
+        final CustomTextLinkSpan[] customTextLinkSpans = spannableString.getSpans(0,
+                spannableString.length() - 1,
+                CustomTextLinkSpan.class);
+
+        assertEquals(TextLinks.STATUS_LINKS_APPLIED, status);
+        assertEquals(1, customTextLinkSpans.length);
+
+        final TextLinks.TextLink textLink = customTextLinkSpans[0].getTextLink();
+
+        assertEquals(START, textLink.getStart());
+        assertEquals(END, textLink.getEnd());
+        assertEquals(1, textLink.getEntityCount());
+        assertEquals(TextClassifier.TYPE_ADDRESS, textLink.getEntity(0));
+        assertEquals(1.0f, textLink.getConfidenceScore(TextClassifier.TYPE_ADDRESS),
+                ACCEPTED_DELTA);
+    }
+
+    @Test
     public void testTextLinksRequest_defaultValues() {
         final TextLinks.Request request = new TextLinks.Request.Builder(TEXT).build();
 
diff --git a/tests/tests/tv/src/android/media/tv/cts/TvInputServiceTest.java b/tests/tests/tv/src/android/media/tv/cts/TvInputServiceTest.java
index 835d254..d47c5ed 100644
--- a/tests/tests/tv/src/android/media/tv/cts/TvInputServiceTest.java
+++ b/tests/tests/tv/src/android/media/tv/cts/TvInputServiceTest.java
@@ -221,6 +221,7 @@
         mTvView.setCallback(mCallback);
 
         CountingTvInputService.sSession = null;
+        CountingTvInputService.sTvInputSessionId = null;
     }
 
     public void testTvInputServiceSession() throws Throwable {
@@ -295,7 +296,9 @@
             @Override
             protected boolean check() {
                 final CountingRecordingSession session = CountingTvInputService.sRecordingSession;
+                final String tvInputSessionId = CountingTvInputService.sTvInputSessionId;
                 return session != null && session.mTuneCount > 0
+                        && tvInputSessionId != null
                         && Objects.equals(session.mTunedChannelUri, fakeChannelUri);
             }
         }.run();
@@ -310,7 +313,9 @@
             @Override
             protected boolean check() {
                 final CountingRecordingSession session = CountingTvInputService.sRecordingSession;
+                final String tvInputSessionId = CountingTvInputService.sTvInputSessionId;
                 return session != null
+                        && tvInputSessionId != null
                         && session.mTuneCount > 0
                         && session.mTuneWithBundleCount > 0
                         && Objects.equals(session.mTunedChannelUri, fakeChannelUri)
@@ -476,7 +481,9 @@
             @Override
             protected boolean check() {
                 final CountingSession session = CountingTvInputService.sSession;
+                final String tvInputSessionId = CountingTvInputService.sTvInputSessionId;
                 return session != null
+                        && tvInputSessionId != null
                         && session.mTuneCount > 0
                         && session.mCreateOverlayView > 0
                         && Objects.equals(session.mTunedChannelUri, fakeChannelUri);
@@ -494,7 +501,9 @@
             @Override
             protected boolean check() {
                 final CountingSession session = CountingTvInputService.sSession;
+                final String tvInputSessionId = CountingTvInputService.sTvInputSessionId;
                 return session != null
+                        && tvInputSessionId != null
                         && session.mTuneCount > 0
                         && session.mTuneWithBundleCount > 0
                         && Objects.equals(session.mTunedChannelUri, fakeChannelUri)
@@ -1054,6 +1063,7 @@
     public static class CountingTvInputService extends StubTvInputService {
         static CountingSession sSession;
         static CountingRecordingSession sRecordingSession;
+        static String sTvInputSessionId;
 
         @Override
         public Session onCreateSession(String inputId) {
@@ -1068,6 +1078,18 @@
             return sRecordingSession;
         }
 
+        @Override
+        public Session onCreateSession(String inputId, String tvInputSessionId) {
+            sTvInputSessionId = tvInputSessionId;
+            return onCreateSession(inputId);
+        }
+
+        @Override
+        public RecordingSession onCreateRecordingSession(String inputId, String tvInputSessionId) {
+            sTvInputSessionId = tvInputSessionId;
+            return onCreateRecordingSession(inputId);
+        }
+
         public static class CountingSession extends Session {
             public volatile int mTuneCount;
             public volatile int mTuneWithBundleCount;
diff --git a/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java b/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
index aa8be38..08b2c25 100644
--- a/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
+++ b/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
@@ -18,6 +18,7 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
 import android.content.Context;
@@ -33,10 +34,32 @@
 import android.media.tv.tuner.filter.FilterEvent;
 import android.media.tv.tuner.filter.Filter;
 import android.media.tv.tuner.filter.TimeFilter;
+
+import android.media.tv.tuner.frontend.AnalogFrontendCapabilities;
+import android.media.tv.tuner.frontend.AnalogFrontendSettings;
+import android.media.tv.tuner.frontend.Atsc3FrontendCapabilities;
+import android.media.tv.tuner.frontend.Atsc3FrontendSettings;
 import android.media.tv.tuner.frontend.Atsc3PlpInfo;
+import android.media.tv.tuner.frontend.Atsc3PlpSettings;
+import android.media.tv.tuner.frontend.AtscFrontendCapabilities;
 import android.media.tv.tuner.frontend.AtscFrontendSettings;
+import android.media.tv.tuner.frontend.DvbcFrontendCapabilities;
+import android.media.tv.tuner.frontend.DvbcFrontendSettings;
+import android.media.tv.tuner.frontend.DvbsCodeRate;
+import android.media.tv.tuner.frontend.DvbsFrontendCapabilities;
+import android.media.tv.tuner.frontend.DvbsFrontendSettings;
+import android.media.tv.tuner.frontend.DvbtFrontendCapabilities;
+import android.media.tv.tuner.frontend.DvbtFrontendSettings;
+import android.media.tv.tuner.frontend.FrontendCapabilities;
 import android.media.tv.tuner.frontend.FrontendInfo;
 import android.media.tv.tuner.frontend.FrontendSettings;
+import android.media.tv.tuner.frontend.FrontendStatus;
+import android.media.tv.tuner.frontend.Isdbs3FrontendCapabilities;
+import android.media.tv.tuner.frontend.Isdbs3FrontendSettings;
+import android.media.tv.tuner.frontend.IsdbsFrontendCapabilities;
+import android.media.tv.tuner.frontend.IsdbsFrontendSettings;
+import android.media.tv.tuner.frontend.IsdbtFrontendCapabilities;
+import android.media.tv.tuner.frontend.IsdbtFrontendSettings;
 import android.media.tv.tuner.frontend.ScanCallback;
 
 import androidx.test.InstrumentationRegistry;
@@ -90,7 +113,11 @@
     @Test
     public void testTuning() throws Exception {
         if (!hasTuner()) return;
-        int res = mTuner.tune(getFrontendSettings());
+        List<Integer> ids = mTuner.getFrontendIds();
+        assertFalse(ids.isEmpty());
+
+        FrontendInfo info = mTuner.getFrontendInfoById(ids.get(0));
+        int res = mTuner.tune(createFrontendSettings(info));
         assertEquals(Tuner.RESULT_SUCCESS, res);
         res = mTuner.cancelTuning();
         assertEquals(Tuner.RESULT_SUCCESS, res);
@@ -100,12 +127,13 @@
     public void testScanning() throws Exception {
         if (!hasTuner()) return;
         List<Integer> ids = mTuner.getFrontendIds();
+        assertFalse(ids.isEmpty());
         for (int id : ids) {
             FrontendInfo info = mTuner.getFrontendInfoById(id);
             if (info != null && info.getType() == FrontendSettings.TYPE_ATSC) {
                 mLockLatch = new CountDownLatch(1);
                 int res = mTuner.scan(
-                        getFrontendSettings(),
+                        createFrontendSettings(info),
                         Tuner.SCAN_TYPE_AUTO,
                         getExecutor(),
                         getScanCallback());
@@ -119,6 +147,65 @@
     }
 
     @Test
+    public void testFrontendStatus() throws Exception {
+        if (!hasTuner()) return;
+        List<Integer> ids = mTuner.getFrontendIds();
+        assertFalse(ids.isEmpty());
+
+        FrontendInfo info = mTuner.getFrontendInfoById(ids.get(0));
+        int res = mTuner.tune(createFrontendSettings(info));
+        FrontendStatus status = mTuner.getFrontendStatus(
+                new int[] {
+                        FrontendStatus.FRONTEND_STATUS_TYPE_DEMOD_LOCK,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_SNR,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_BER,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_PER,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_PRE_BER,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_SIGNAL_QUALITY,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_SIGNAL_STRENGTH,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_SYMBOL_RATE,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_FEC,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_MODULATION,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_SPECTRAL,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_LNB_VOLTAGE,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_PLP_ID,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_EWBS,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_AGC,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_LNA,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_LAYER_ERROR,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_MER,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_FREQ_OFFSET,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_HIERARCHY,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_RF_LOCK,
+                        FrontendStatus.FRONTEND_STATUS_TYPE_ATSC3_PLP_INFO
+                });
+        assertNotNull(status);
+
+        status.isDemodLocked();
+        status.getSnr();
+        status.getBer();
+        status.getPer();
+        status.getPerBer();
+        status.getSignalQuality();
+        status.getSignalStrength();
+        status.getSymbolRate();
+        status.getInnerFec();
+        status.getModulation();
+        status.getSpectralInversion();
+        status.getLnbVoltage();
+        status.getPlpId();
+        status.isEwbs();
+        status.getAgc();
+        status.isLnaOn();
+        status.getLayerErrors();
+        status.getMer();
+        status.getFreqOffset();
+        status.getHierarchy();
+        status.isRfLocked();
+        status.getAtsc3PlpTuningInfo();
+    }
+
+    @Test
     public void testOpenLnb() throws Exception {
         if (!hasTuner()) return;
         Lnb lnb = mTuner.openLnb(getExecutor(), getLnbCallback());
@@ -224,12 +311,149 @@
         };
     }
 
-    private FrontendSettings getFrontendSettings() {
-        return AtscFrontendSettings
-                .builder()
-                .setFrequency(2000)
-                .setModulation(AtscFrontendSettings.MODULATION_AUTO)
-                .build();
+    private FrontendSettings createFrontendSettings(FrontendInfo info) {
+            FrontendCapabilities caps = info.getFrontendCapabilities();
+            int minFreq = info.getFrequencyRange().getLower();
+            FrontendCapabilities feCaps = info.getFrontendCapabilities();
+            switch(info.getType()) {
+                case FrontendSettings.TYPE_ANALOG: {
+                    AnalogFrontendCapabilities analogCaps = (AnalogFrontendCapabilities) caps;
+                    int signalType = getFirstCapable(analogCaps.getSignalTypeCapability());
+                    int sif = getFirstCapable(analogCaps.getSifStandardCapability());
+                    return AnalogFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setSignalType(signalType)
+                            .setSifStandard(sif)
+                            .build();
+                }
+                case FrontendSettings.TYPE_ATSC3: {
+                    Atsc3FrontendCapabilities atsc3Caps = (Atsc3FrontendCapabilities) caps;
+                    int bandwidth = getFirstCapable(atsc3Caps.getBandwidthCapability());
+                    int demod = getFirstCapable(atsc3Caps.getDemodOutputFormatCapability());
+                    return Atsc3FrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setBandwidth(bandwidth)
+                            .setDemodOutputFormat(demod)
+                            .build();
+                }
+                case FrontendSettings.TYPE_ATSC: {
+                    AtscFrontendCapabilities atscCaps = (AtscFrontendCapabilities) caps;
+                    int modulation = getFirstCapable(atscCaps.getModulationCapability());
+                    return AtscFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setModulation(modulation)
+                            .build();
+                }
+                case FrontendSettings.TYPE_DVBC: {
+                    DvbcFrontendCapabilities dvbcCaps = (DvbcFrontendCapabilities) caps;
+                    int modulation = getFirstCapable(dvbcCaps.getModulationCapability());
+                    int fec = getFirstCapable(dvbcCaps.getFecCapability());
+                    int annex = getFirstCapable(dvbcCaps.getAnnexCapability());
+                    return DvbcFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setModulation(modulation)
+                            .setInnerFec(fec)
+                            .setAnnex(annex)
+                            .build();
+                }
+                case FrontendSettings.TYPE_DVBS: {
+                    DvbsFrontendCapabilities dvbsCaps = (DvbsFrontendCapabilities) caps;
+                    int modulation = getFirstCapable(dvbsCaps.getModulationCapability());
+                    int standard = getFirstCapable(dvbsCaps.getStandardCapability());
+                    return DvbsFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setModulation(modulation)
+                            .setStandard(standard)
+                            .build();
+                }
+                case FrontendSettings.TYPE_DVBT: {
+                    DvbtFrontendCapabilities dvbtCaps = (DvbtFrontendCapabilities) caps;
+                    int transmission = getFirstCapable(dvbtCaps.getTransmissionModeCapability());
+                    int bandwidth = getFirstCapable(dvbtCaps.getBandwidthCapability());
+                    int constellation = getFirstCapable(dvbtCaps.getConstellationCapability());
+                    int codeRate = getFirstCapable(dvbtCaps.getCodeRateCapability());
+                    int hierarchy = getFirstCapable(dvbtCaps.getHierarchyCapability());
+                    int guardInterval = getFirstCapable(dvbtCaps.getGuardIntervalCapability());
+                    return DvbtFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setTransmissionMode(transmission)
+                            .setBandwidth(bandwidth)
+                            .setConstellation(constellation)
+                            .setHierarchy(hierarchy)
+                            .setHighPriorityCodeRate(codeRate)
+                            .setLowPriorityCodeRate(codeRate)
+                            .setGuardInterval(guardInterval)
+                            .setStandard(DvbtFrontendSettings.STANDARD_T)
+                            .setMiso(false)
+                            .build();
+                }
+                case FrontendSettings.TYPE_ISDBS3: {
+                    Isdbs3FrontendCapabilities isdbs3Caps = (Isdbs3FrontendCapabilities) caps;
+                    int modulation = getFirstCapable(isdbs3Caps.getModulationCapability());
+                    int codeRate = getFirstCapable(isdbs3Caps.getCodeRateCapability());
+                    return Isdbs3FrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setModulation(modulation)
+                            .setCodeRate(codeRate)
+                            .build();
+                }
+                case FrontendSettings.TYPE_ISDBS: {
+                    IsdbsFrontendCapabilities isdbsCaps = (IsdbsFrontendCapabilities) caps;
+                    int modulation = getFirstCapable(isdbsCaps.getModulationCapability());
+                    int codeRate = getFirstCapable(isdbsCaps.getCodeRateCapability());
+                    return IsdbsFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setModulation(modulation)
+                            .setCodeRate(codeRate)
+                            .build();
+                }
+                case FrontendSettings.TYPE_ISDBT: {
+                    IsdbtFrontendCapabilities isdbtCaps = (IsdbtFrontendCapabilities) caps;
+                    int mode = getFirstCapable(isdbtCaps.getModeCapability());
+                    int bandwidth = getFirstCapable(isdbtCaps.getBandwidthCapability());
+                    int modulation = getFirstCapable(isdbtCaps.getModulationCapability());
+                    int codeRate = getFirstCapable(isdbtCaps.getCodeRateCapability());
+                    int guardInterval = getFirstCapable(isdbtCaps.getGuardIntervalCapability());
+                    return IsdbtFrontendSettings
+                            .builder()
+                            .setFrequency(minFreq)
+                            .setModulation(modulation)
+                            .setBandwidth(bandwidth)
+                            .setMode(mode)
+                            .setCodeRate(codeRate)
+                            .setGuardInterval(guardInterval)
+                            .build();
+                }
+                default:
+                    break;
+            }
+        return null;
+    }
+
+    private int getFirstCapable(int caps) {
+        if (caps == 0) return 0;
+        int mask = 1;
+        while ((mask & caps) == 0) {
+            mask = mask << 1;
+        }
+        return (mask & caps);
+    }
+
+    private long getFirstCapable(long caps) {
+        if (caps == 0) return 0;
+        long mask = 1;
+        while ((mask & caps) == 0) {
+            mask = mask << 1;
+        }
+        return (mask & caps);
     }
 
     private ScanCallback getScanCallback() {
diff --git a/tests/tests/uiautomation/AndroidManifest.xml b/tests/tests/uiautomation/AndroidManifest.xml
index 75eab20..fdc7457 100644
--- a/tests/tests/uiautomation/AndroidManifest.xml
+++ b/tests/tests/uiautomation/AndroidManifest.xml
@@ -22,6 +22,7 @@
 
   <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+  <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
   <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
 
diff --git a/tests/tests/widget/AndroidTest.xml b/tests/tests/widget/AndroidTest.xml
index 9bdb58f..b9311c6 100644
--- a/tests/tests/widget/AndroidTest.xml
+++ b/tests/tests/widget/AndroidTest.xml
@@ -22,6 +22,10 @@
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsWidgetTestCases.apk" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="force-install-mode" value="FULL"/>
         <option name="test-file-name" value="CtsWidgetApp.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
diff --git a/tests/tests/widget/app/AndroidManifest.xml b/tests/tests/widget/app/AndroidManifest.xml
index 9c19ce1..106a845 100755
--- a/tests/tests/widget/app/AndroidManifest.xml
+++ b/tests/tests/widget/app/AndroidManifest.xml
@@ -22,6 +22,7 @@
         <activity
             android:name=".TranslucentActivity"
             android:exported="true"
+            android:visibleToInstantApps="true"
             android:theme="@style/TranslucentTheme" />
     </application>
 </manifest>
diff --git a/tests/tests/widget/app/src/android/widget/cts/app/TranslucentActivity.java b/tests/tests/widget/app/src/android/widget/cts/app/TranslucentActivity.java
index c9b79b3..d2a5f82 100644
--- a/tests/tests/widget/app/src/android/widget/cts/app/TranslucentActivity.java
+++ b/tests/tests/widget/app/src/android/widget/cts/app/TranslucentActivity.java
@@ -57,7 +57,9 @@
     @Override
     protected void onResume() {
         super.onResume();
-        sendBroadcast(new Intent(ACTION_TRANSLUCENT_ACTIVITY_RESUMED));
+        Intent intent = new Intent(ACTION_TRANSLUCENT_ACTIVITY_RESUMED);
+        intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
+        sendBroadcast(intent);
     }
 
     @Override
diff --git a/tests/tests/wifi/src/android/net/wifi/aware/cts/SingleDeviceTest.java b/tests/tests/wifi/src/android/net/wifi/aware/cts/SingleDeviceTest.java
index 96148c7..a476658 100644
--- a/tests/tests/wifi/src/android/net/wifi/aware/cts/SingleDeviceTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/aware/cts/SingleDeviceTest.java
@@ -69,7 +69,7 @@
     private static final String TAG = "WifiAwareCtsTests";
 
     // wait for Wi-Fi Aware state changes & network requests callbacks
-    static private final int WAIT_FOR_AWARE_CHANGE_SECS = 10; // 10 seconds
+    static private final int WAIT_FOR_AWARE_CHANGE_SECS = 15; // 15 seconds
     private static final int MIN_DISTANCE_MM = 1 * 1000;
     private static final int MAX_DISTANCE_MM = 3 * 1000;
     private static final byte[] PMK_VALID = "01234567890123456789012345678901".getBytes();