Merge "WindowManagerUtil for hostside tests" into rvc-dev
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 9d3a68c..663b54e 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -3685,6 +3685,7 @@
         Return back to this page.
     </string>
     <string name="device_owner_user_restriction_set">Set restriction</string>
+    <string name="device_owner_user_restriction_unset">Clear restriction (before leaving test)</string>
     <string name="device_owner_settings_go">Go</string>
 
     <string name="device_owner_vpn_connection">
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
index 0c905c0..ddf5e0c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -181,7 +181,12 @@
                                             UserManager.DISALLOW_CONFIG_WIFI, true)),
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
-                                    new Intent(Settings.ACTION_WIFI_SETTINGS))}));
+                                    new Intent(Settings.ACTION_WIFI_SETTINGS)),
+                            new ButtonInfo(
+                                    R.string.device_owner_user_restriction_unset,
+                                    CommandReceiverActivity.createSetUserRestrictionIntent(
+                                            UserManager.DISALLOW_CONFIG_WIFI, false))
+            }));
         }
 
         // DISALLOW_AMBIENT_DISPLAY.
@@ -214,7 +219,12 @@
                                 new Intent(Settings.ACTION_VPN_SETTINGS)),
                         new ButtonInfo(
                                 R.string.device_owner_vpn_test,
-                                new Intent(this, VpnTestActivity.class))}));
+                                new Intent(this, VpnTestActivity.class)),
+                        new ButtonInfo(
+                                R.string.device_owner_user_restriction_unset,
+                                CommandReceiverActivity.createSetUserRestrictionIntent(
+                                        UserManager.DISALLOW_CONFIG_VPN, false))
+        }));
 
         // DISALLOW_DATA_ROAMING
         if(packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
@@ -228,7 +238,12 @@
                                             UserManager.DISALLOW_DATA_ROAMING, true)),
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
-                                    new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS))}));
+                                    new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)),
+                            new ButtonInfo(
+                                    R.string.device_owner_user_restriction_unset,
+                                    CommandReceiverActivity.createSetUserRestrictionIntent(
+                                            UserManager.DISALLOW_DATA_ROAMING, false))
+            }));
         }
 
         // DISALLOW_FACTORY_RESET
@@ -239,7 +254,12 @@
                         new ButtonInfo(
                                 R.string.device_owner_user_restriction_set,
                                 CommandReceiverActivity.createSetUserRestrictionIntent(
-                                        UserManager.DISALLOW_FACTORY_RESET, true))}));
+                                        UserManager.DISALLOW_FACTORY_RESET, true)),
+                        new ButtonInfo(
+                                R.string.device_owner_user_restriction_unset,
+                                CommandReceiverActivity.createSetUserRestrictionIntent(
+                                        UserManager.DISALLOW_FACTORY_RESET, false))
+        }));
 
         // DISALLOW_CONFIG_BLUETOOTH
         if (packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
@@ -253,7 +273,12 @@
                                             UserManager.DISALLOW_CONFIG_BLUETOOTH, true)),
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
-                                    new Intent(Settings.ACTION_BLUETOOTH_SETTINGS))}));
+                                    new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)),
+                            new ButtonInfo(
+                                    R.string.device_owner_user_restriction_unset,
+                                    CommandReceiverActivity.createSetUserRestrictionIntent(
+                                            UserManager.DISALLOW_CONFIG_BLUETOOTH, false))
+            }));
         }
 
         // DISALLOW_USB_FILE_TRANSFER
@@ -265,7 +290,11 @@
                                 R.string.device_owner_user_restriction_set,
                                 CommandReceiverActivity.createSetUserRestrictionIntent(
                                         UserManager.DISALLOW_USB_FILE_TRANSFER, true)),
-                }));
+                        new ButtonInfo(
+                                R.string.device_owner_user_restriction_unset,
+                                CommandReceiverActivity.createSetUserRestrictionIntent(
+                                        UserManager.DISALLOW_USB_FILE_TRANSFER, false))
+        }));
 
         // DISABLE_STATUS_BAR_TEST
         if (isStatusBarEnabled()) {
@@ -325,7 +354,12 @@
                                 createSetUserIconIntent(R.drawable.user_icon_2)),
                         new ButtonInfo(
                                 R.string.device_owner_settings_go,
-                                new Intent(Settings.ACTION_SETTINGS))}));
+                                new Intent(Settings.ACTION_SETTINGS)),
+                        new ButtonInfo(
+                                R.string.device_owner_user_restriction_unset,
+                                CommandReceiverActivity.createSetUserRestrictionIntent(
+                                        UserManager.DISALLOW_SET_USER_ICON, false))
+        }));
 
         // setPermissionGrantState
         adapter.add(createTestItem(this, CHECK_PERMISSION_LOCKDOWN_TEST_ID,
@@ -400,7 +434,12 @@
                                             UserManager.DISALLOW_USER_SWITCH, true)),
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
-                                    new Intent(Settings.ACTION_USER_SETTINGS))}));
+                                    new Intent(Settings.ACTION_USER_SETTINGS)),
+                            new ButtonInfo(
+                                    R.string.device_owner_user_restriction_unset,
+                                    CommandReceiverActivity.createSetUserRestrictionIntent(
+                                            UserManager.DISALLOW_USER_SWITCH, false))
+            }));
 
             // DISALLOW_REMOVE_USER
             adapter.add(createInteractiveTestItem(this, DISALLOW_REMOVE_USER_TEST_ID,
@@ -416,7 +455,12 @@
                                             UserManager.DISALLOW_REMOVE_USER, true)),
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
-                                    new Intent(Settings.ACTION_USER_SETTINGS))}));
+                                    new Intent(Settings.ACTION_USER_SETTINGS)),
+                            new ButtonInfo(
+                                    R.string.device_owner_user_restriction_unset,
+                                    CommandReceiverActivity.createSetUserRestrictionIntent(
+                                            UserManager.DISALLOW_REMOVE_USER, false))
+            }));
         }
 
         // Network logging UI
@@ -519,7 +563,7 @@
     private boolean isStatusBarEnabled() {
       // Watches don't support the status bar so this is an ok proxy, but this is not the most
       // general test for that. TODO: add a test API to do a real check for status bar support.
-      return !getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH) && 
+      return !getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH) &&
              !getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
     }
 }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
index eb8e077..372b77e 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
@@ -29,6 +29,7 @@
 import android.platform.test.annotations.AppModeFull;
 
 import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
@@ -51,12 +52,16 @@
     public static final String FEATURE_ADOPTABLE_STORAGE = "feature:android.software.adoptable_storage";
 
     private boolean mHasAdoptableInitialState;
+    private String mListVolumesInitialState;
 
     @Before
     public void setUp() throws Exception {
         // Start all possible users to make sure their storage is unlocked
         Utils.prepareMultipleUsers(getDevice(), Integer.MAX_VALUE);
 
+        // Initial state of all volumes
+        mListVolumesInitialState = getDevice().executeShellCommand("sm list-volumes");
+
         // TODO(b/146491109): Revert this change before shipping and find long-term solution.
         // Caches the initial state of adoptable feature and sets it to true (if not already set)
         mHasAdoptableInitialState = Boolean.parseBoolean(
@@ -71,6 +76,17 @@
         // currently have an SD card inserted.
         if (isSupportedDevice()) {
             getDevice().executeShellCommand("sm set-virtual-disk true");
+
+            // Ensure virtual disk is mounted.
+            int attempt = 0;
+            boolean hasVirtualDisk = false;
+            String result = "";
+            while (!hasVirtualDisk && attempt++ < 20) {
+                Thread.sleep(1000);
+                result = getDevice().executeShellCommand("sm list-disks adoptable").trim();
+                hasVirtualDisk = result.startsWith("disk:");
+            }
+            assertTrue("Virtual disk is not ready: " + result, hasVirtualDisk);
         }
     }
 
@@ -80,6 +96,32 @@
 
         if (isSupportedDevice()) {
             getDevice().executeShellCommand("sm set-virtual-disk false");
+
+            // Ensure virtual disk is removed.
+            int attempt = 0;
+            boolean hasVirtualDisk = true;
+            String result = "";
+            while (hasVirtualDisk && attempt++ < 20) {
+                Thread.sleep(1000);
+                result = getDevice().executeShellCommand("sm list-disks adoptable").trim();
+                hasVirtualDisk = result.startsWith("disk:");
+            }
+            if (hasVirtualDisk) {
+                CLog.w("Virtual disk is not removed: " + result);
+            }
+
+            // Ensure all volumes go back to the original state.
+            attempt = 0;
+            boolean volumeStateRecovered = false;
+            result = "";
+            while (!volumeStateRecovered && attempt++ < 20) {
+                Thread.sleep(1000);
+                result = getDevice().executeShellCommand("sm list-volumes");
+                volumeStateRecovered = mListVolumesInitialState.equals(result);
+            }
+            if (!volumeStateRecovered) {
+                CLog.w("Volume state is not recovered: " + result);
+            }
         }
         // Restores the initial cache value (if it is different)
         if (!mHasAdoptableInitialState) {
@@ -87,6 +129,19 @@
         }
     }
 
+    // Ensure no volume is in ejecting or checking state
+    private void waitForVolumeReady() throws Exception {
+        int attempt = 0;
+        boolean noCheckingEjecting = false;
+        String result = "";
+        while (!noCheckingEjecting && attempt++ < 20) {
+            result = getDevice().executeShellCommand("sm list-volumes");
+            noCheckingEjecting = !result.contains("ejecting") && !result.contains("checking");
+            Thread.sleep(100);
+        }
+        assertTrue("Volumes are not ready: " + result, noCheckingEjecting);
+    }
+
     @Test
     public void testApps() throws Exception {
         if (!isSupportedDevice()) return;
@@ -116,6 +171,7 @@
 
             // Unmount, remount and verify
             getDevice().executeShellCommand("sm unmount " + vol.volId);
+            waitForVolumeReady();
             getDevice().executeShellCommand("sm mount " + vol.volId);
             waitForInstrumentationReady();
 
@@ -192,6 +248,7 @@
 
         // Unmount and verify
         getDevice().executeShellCommand("sm unmount " + vol.volId);
+        waitForVolumeReady();
         runDeviceTests(PKG, CLASS, "testPrimaryUnmounted");
         getDevice().executeShellCommand("sm mount " + vol.volId);
         waitForInstrumentationReady();
@@ -238,6 +295,7 @@
 
         // Unmount and verify
         getDevice().executeShellCommand("sm unmount " + vol.volId);
+        waitForVolumeReady();
         runDeviceTests(PKG, CLASS, "testPrimaryUnmounted");
         getDevice().executeShellCommand("sm mount " + vol.volId);
         waitForInstrumentationReady();
@@ -301,6 +359,7 @@
 
             // Now unmount and uninstall; leaving stale package on adopted volume
             getDevice().executeShellCommand("sm unmount " + vol.volId);
+            waitForVolumeReady();
             getDevice().uninstallPackage(PKG);
 
             // Install second copy on internal, but don't write anything
@@ -322,6 +381,7 @@
                 fail("Unexpected data from adopted volume picked up");
             }
             getDevice().executeShellCommand("sm unmount " + vol.volId);
+            waitForVolumeReady();
 
             // Uninstall the internal copy and remount; we should have no record of app
             getDevice().uninstallPackage(PKG);
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
index 3360f07..216f9e4 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
index 29ee80b..e4ff336 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
index 0996efe..90dc8bd 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
index 8d10477..d58c7cf 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
Binary files differ
diff --git a/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java b/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java
index 9a6db96b..ac3f8d5 100644
--- a/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java
+++ b/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java
@@ -22,18 +22,15 @@
 
 import android.Manifest;
 import android.content.Context;
-import android.content.pm.PackageInstaller;
 import android.content.rollback.RollbackInfo;
 import android.content.rollback.RollbackManager;
 import android.os.storage.StorageManager;
-import android.util.Log;
 
 import androidx.test.platform.app.InstrumentationRegistry;
 
 import com.android.cts.install.lib.Install;
 import com.android.cts.install.lib.InstallUtils;
 import com.android.cts.install.lib.TestApp;
-import com.android.cts.install.lib.Uninstall;
 import com.android.cts.rollback.lib.Rollback;
 import com.android.cts.rollback.lib.RollbackUtils;
 
@@ -43,7 +40,13 @@
 import org.junit.runner.RunWith;
 import org.junit.runners.JUnit4;
 
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
 import java.io.IOException;
+import java.nio.file.Files;
 
 /**
  * On-device helper test methods used for host-driven rollback tests.
@@ -57,7 +60,8 @@
             "com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex");
     private static final String ApkInShimApexPackageName = "com.android.cts.ctsshim";
     private static final String PrivApkInShimApexPackageName = "com.android.cts.priv.ctsshim";
-    private static final long ApkInShimApexVersion = 29;
+    private static final String APK_VERSION_FILENAME = "ctsrollback_apkversion";
+    private static final String APK_VERSION_SEPARATOR = ",";
 
     /**
      * Adopts common permissions needed to test rollbacks.
@@ -84,6 +88,8 @@
         RollbackManager rm = RollbackUtils.getRollbackManager();
         rm.getAvailableRollbacks().stream().flatMap(info -> info.getPackages().stream())
                 .map(info -> info.getPackageName()).forEach(rm::expireRollbackForPackage);
+        // remove the version file.
+        Files.deleteIfExists(getApkInApexVersionFile().toPath());
     }
 
     /**
@@ -319,6 +325,10 @@
     @Test
     public void testApexOnlyStagedRollback_Phase2() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(2);
+
+        // keep the versions of the apks in shim apex for verifying in phase3
+        recordApkInApexVersion();
+
         Install.single(TestApp.Apex3).setStaged().setEnableRollback().commit();
     }
 
@@ -329,14 +339,19 @@
     @Test
     public void testApexOnlyStagedRollback_Phase3() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(3);
+
+        long[] versions = retrieveApkInApexVersion();
+        final long apkInShimApexVersion = versions[0];
+        final long privApkInShimApexVersion = versions[1];
+
         RollbackInfo available = RollbackUtils.getAvailableRollback(TestApp.Apex);
         assertThat(available).isStaged();
         assertThat(available).packagesContainsExactly(
                 Rollback.from(TestApp.Apex3).to(TestApp.Apex2),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
 
         RollbackUtils.rollback(available.getRollbackId(), TestApp.Apex3);
         RollbackInfo committed = RollbackUtils.getCommittedRollbackById(available.getRollbackId());
@@ -345,9 +360,9 @@
         assertThat(committed).packagesContainsExactly(
                 Rollback.from(TestApp.Apex3).to(TestApp.Apex2),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
         assertThat(committed).causePackagesContainsExactly(TestApp.Apex3);
         assertThat(committed.getCommittedSessionId()).isNotEqualTo(-1);
 
@@ -376,20 +391,29 @@
     @Test
     public void testApexOnlySystemVersionStagedRollback_Phase1() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+
+        // keep the versions of the apks in shim apex for verifying in phase2
+        recordApkInApexVersion();
+
         Install.single(TestApp.Apex2).setStaged().setEnableRollback().commit();
     }
 
     @Test
     public void testApexOnlySystemVersionStagedRollback_Phase2() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(2);
+
+        long[] versions = retrieveApkInApexVersion();
+        final long apkInShimApexVersion = versions[0];
+        final long privApkInShimApexVersion = versions[1];
+
         RollbackInfo available = RollbackUtils.getAvailableRollback(TestApp.Apex);
         assertThat(available).isStaged();
         assertThat(available).packagesContainsExactly(
                 Rollback.from(TestApp.Apex2).to(TestApp.Apex1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
 
         RollbackUtils.rollback(available.getRollbackId(), TestApp.Apex2);
         RollbackInfo committed = RollbackUtils.getCommittedRollbackById(available.getRollbackId());
@@ -398,9 +422,9 @@
         assertThat(committed).packagesContainsExactly(
                 Rollback.from(TestApp.Apex2).to(TestApp.Apex1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
         assertThat(committed).causePackagesContainsExactly(TestApp.Apex2);
         assertThat(committed.getCommittedSessionId()).isNotEqualTo(-1);
 
@@ -435,6 +459,10 @@
     public void testApexAndApkStagedRollback_Phase2() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(2);
         assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(1);
+
+        // keep the versions of the apks in shim apex for verifying in phase3 and phase4
+        recordApkInApexVersion();
+
         Install.multi(TestApp.Apex3, TestApp.A2).setStaged().setEnableRollback().commit();
     }
 
@@ -448,15 +476,19 @@
         assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(2);
         InstallUtils.processUserData(TestApp.A);
 
+        long[] versions = retrieveApkInApexVersion();
+        final long apkInShimApexVersion = versions[0];
+        final long privApkInShimApexVersion = versions[1];
+
         RollbackInfo available = RollbackUtils.getAvailableRollback(TestApp.Apex);
         assertThat(available).isStaged();
         assertThat(available).packagesContainsExactly(
                 Rollback.from(TestApp.Apex3).to(TestApp.Apex2),
                 Rollback.from(TestApp.A2).to(TestApp.A1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
 
         RollbackUtils.rollback(available.getRollbackId(), TestApp.Apex3, TestApp.A2);
         RollbackInfo committed = RollbackUtils.getCommittedRollback(TestApp.A);
@@ -466,9 +498,9 @@
                 Rollback.from(TestApp.Apex3).to(TestApp.Apex2),
                 Rollback.from(TestApp.A2).to(TestApp.A1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
         assertThat(committed).causePackagesContainsExactly(TestApp.Apex3, TestApp.A2);
         assertThat(committed.getCommittedSessionId()).isNotEqualTo(-1);
 
@@ -489,15 +521,19 @@
         assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(1);
         InstallUtils.processUserData(TestApp.A);
 
+        long[] versions = retrieveApkInApexVersion();
+        final long apkInShimApexVersion = versions[0];
+        final long privApkInShimApexVersion = versions[1];
+
         RollbackInfo committed = RollbackUtils.getCommittedRollback(TestApp.A);
         assertThat(committed).isStaged();
         assertThat(committed).packagesContainsExactly(
                 Rollback.from(TestApp.Apex3).to(TestApp.Apex2),
                 Rollback.from(TestApp.A2).to(TestApp.A1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
         assertThat(committed).causePackagesContainsExactly(TestApp.Apex3, TestApp.A2);
         assertThat(committed.getCommittedSessionId()).isNotEqualTo(-1);
 
@@ -544,6 +580,10 @@
     @Test
     public void testApexKeyRotationStagedRollback_Phase1() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+
+        // keep the versions of the apks in shim apex for verifying in phase2
+        recordApkInApexVersion();
+
         Install.single(Apex2SignedBobRotRollback).setStaged().setEnableRollback().commit();
     }
 
@@ -551,13 +591,17 @@
     public void testApexKeyRotationStagedRollback_Phase2() throws Exception {
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(2);
         RollbackInfo available = RollbackUtils.getAvailableRollback(TestApp.Apex);
+        long[] versions = retrieveApkInApexVersion();
+        final long apkInShimApexVersion = versions[0];
+        final long privApkInShimApexVersion = versions[1];
+
         assertThat(available).isStaged();
         assertThat(available).packagesContainsExactly(
                 Rollback.from(Apex2SignedBobRotRollback).to(TestApp.Apex1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
 
         RollbackUtils.rollback(available.getRollbackId(), Apex2SignedBobRotRollback);
         RollbackInfo committed = RollbackUtils.getCommittedRollbackById(available.getRollbackId());
@@ -566,9 +610,9 @@
         assertThat(committed).packagesContainsExactly(
                 Rollback.from(Apex2SignedBobRotRollback).to(TestApp.Apex1),
                 Rollback.from(ApkInShimApexPackageName, 0)
-                        .to(ApkInShimApexPackageName, ApkInShimApexVersion),
+                        .to(ApkInShimApexPackageName, apkInShimApexVersion),
                 Rollback.from(PrivApkInShimApexPackageName, 0)
-                        .to(PrivApkInShimApexPackageName, ApkInShimApexVersion));
+                        .to(PrivApkInShimApexPackageName, privApkInShimApexVersion));
         assertThat(committed).causePackagesContainsExactly(Apex2SignedBobRotRollback);
         assertThat(committed.getCommittedSessionId()).isNotEqualTo(-1);
 
@@ -611,4 +655,56 @@
         StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
         assertThat(sm.isCheckpointSupported()).isTrue();
     }
+
+    /**
+     * Record the versions of Apk in shim apex and PrivApk in shim apex
+     * in the order into {@link #APK_VERSION_FILENAME}.
+     *
+     * @see #ApkInShimApexPackageName
+     * @see #PrivApkInShimApexPackageName
+     */
+    private void recordApkInApexVersion() throws Exception {
+        final File versionFile = getApkInApexVersionFile();
+
+        if (!versionFile.exists()) {
+            versionFile.createNewFile();
+        }
+
+        final long apkInApexVersion = InstallUtils.getInstalledVersion(ApkInShimApexPackageName);
+        final long privApkInApexVersion = InstallUtils.getInstalledVersion(
+                PrivApkInShimApexPackageName);
+
+        try (BufferedWriter writer = new BufferedWriter(new FileWriter(versionFile))) {
+            writer.write(apkInApexVersion + APK_VERSION_SEPARATOR + privApkInApexVersion);
+        }
+    }
+
+    /**
+     * Returns the array of the versions of Apk in shim apex and PrivApk in shim apex
+     * in the order from {@link #APK_VERSION_FILENAME}.
+     *
+     * @see #ApkInShimApexPackageName
+     * @see #PrivApkInShimApexPackageName
+     */
+    private long[] retrieveApkInApexVersion() throws Exception {
+        final File versionFile = getApkInApexVersionFile();
+
+        if (!versionFile.exists()) {
+            throw new IllegalStateException("The RollbackTest version file not found");
+        }
+
+        try (BufferedReader reader = new BufferedReader(new FileReader(versionFile))) {
+            String[] versions = reader.readLine().split(APK_VERSION_SEPARATOR);
+
+            if (versions.length != 2) {
+                throw new IllegalStateException("The RollbackTest version file is wrong.");
+            }
+            return new long[]{Long.parseLong(versions[0]), Long.parseLong(versions[1])};
+        }
+    }
+
+    private File getApkInApexVersionFile() {
+        final Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        return new File(context.getFilesDir(), APK_VERSION_FILENAME);
+    }
 }
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 83584e5..d5b1a8e 100644
--- a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
@@ -529,6 +529,8 @@
      */
     @Test
     public void testApexTargetingOldDevSdkFailsVerification() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+
         runPhase("testApexTargetingOldDevSdkFailsVerification");
     }
 
@@ -538,6 +540,8 @@
     @Test
     @LargeTest
     public void testApexFailsToInstallIfApkInApexFailsToScan() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+
         runPhase("testApexFailsToInstallIfApkInApexFailsToScan_Commit");
         getDevice().reboot();
         runPhase("testApexFailsToInstallIfApkInApexFailsToScan_VerifyPostReboot");
@@ -545,6 +549,8 @@
 
     @Test
     public void testCorruptedApexFailsVerification_b146895998() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+
         runPhase("testCorruptedApexFailsVerification_b146895998");
     }
 
@@ -553,6 +559,8 @@
      */
     @Test
     public void testApexWithUnsignedApkFailsVerification() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+
         runPhase("testApexWithUnsignedApkFailsVerification");
     }
 
@@ -561,6 +569,8 @@
      */
     @Test
     public void testApexWithUnsignedPayloadFailsVerification() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+
         runPhase("testApexWithUnsignedPayloadFailsVerification");
     }
 
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex
index 093770b..cd1bc20 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex
index b45c93a..63edbd3 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex
index 2c7fb51..e91f134 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex
index 4829ab7..500dc7a 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
index 8f18159..9d7b0a2 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex
index 15c9ebf..8641f6d 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex
index 027cc9f..eb26cf3 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex
index 88f4355..4206578 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex
index 4b4bc9c..5ee9333 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex
index db36942..8f0fefa 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex
index 94726c8..adf7957 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
index 59f3c88..14fe873 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_apk_container.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_apk_container.apex
index 1187674..a64e7d4 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_apk_container.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_apk_container.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex
index f6f8719..2373c56 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex
index d04bf00a..dc131f3 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
index 9b418a0..e8a73ab 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex
index cee12d8..4ec56c6 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex
index 73320d5..967f224 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex
index 0358430..064dde9 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex
index 4b467f7..3cd1a25 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex
index 085c1a9..2fdfc2b 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex
index 9ead68e..eacf253 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex
index 2c7fb51..e91f134 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex
index 4829ab7..500dc7a 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
index 8f18159..9d7b0a2 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex
index 15c9ebf..8641f6d 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex
index 75efea3..64bb073 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex
index 61e6bff..e785499 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex
index 4e28d6a..9c06e38 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex
index a084b94..475d3a8 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex
index b8badc5..b3b2f36 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
index 0cced96..914bedd 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_apk_container.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_apk_container.apex
index 5962142..ff26024 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_apk_container.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_apk_container.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex
index 17f4d68..84c2496 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex
index d04bf00a..dc131f3 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
index 9b418a0..e8a73ab 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex
index cee12d8..4ec56c6 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex
index 03f1ecb..84a7fcf 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex
index 3113f25..e76ca8e 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex
index 8c911bb..cbd46f7 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk
index 5cd12d2..56f162f 100644
--- a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk
+++ b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk
index 5cd12d2..56f162f 100644
--- a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk
+++ b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk
Binary files differ
diff --git a/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java b/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
index 9ee5a65..6be679b 100644
--- a/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
+++ b/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
@@ -52,6 +52,12 @@
     private String mFinishReason;
     private boolean mFinishSuccess;
 
+    class CompressOutputThread extends Thread {
+        public void run() {
+            compressOutput();
+        }
+    }
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
@@ -133,9 +139,8 @@
 
         // If we ran out of themes, we're done.
         if (!success) {
-            compressOutput();
-
-            finish("Image generation complete!", true);
+            CompressOutputThread compressOutputThread = new CompressOutputThread();
+            compressOutputThread.start();
         }
     }
 
@@ -182,6 +187,9 @@
         } catch (IOException e) {
             e.printStackTrace();
         }
+        runOnUiThread(() -> {
+            finish("Image generation complete!", true);
+        });
     }
 
     private void finish(String reason, boolean success) {
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
index bc30c7d4..b1bb32e 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
@@ -18,7 +18,6 @@
 
 import static android.accessibilityservice.cts.utils.AsyncUtils.await;
 import static android.accessibilityservice.cts.utils.GestureUtils.IS_ACTION_DOWN;
-import static android.accessibilityservice.cts.utils.GestureUtils.IS_ACTION_MOVE;
 import static android.accessibilityservice.cts.utils.GestureUtils.IS_ACTION_UP;
 import static android.accessibilityservice.cts.utils.GestureUtils.add;
 import static android.accessibilityservice.cts.utils.GestureUtils.ceil;
@@ -195,8 +194,8 @@
     }
 
     /**
-     * Test a two finger drag. TouchExplorer would perform a drag gesture when two fingers moving
-     * in the same direction.
+     * Test a two finger drag. TouchExplorer would perform a drag gesture when two fingers moving in
+     * the same direction.
      */
     @Test
     @AppModeFull
@@ -212,7 +211,8 @@
         final PointF finger1End = add(finger1Start, 0, mSwipeDistance);
         final PointF finger2Start = add(dragStart, -twoFingerOffset, 0);
         final PointF finger2End = add(finger2Start, 0, mSwipeDistance);
-        dispatch(swipe(finger1Start, finger1End, SWIPE_TIME_MILLIS),
+        dispatch(
+                swipe(finger1Start, finger1End, SWIPE_TIME_MILLIS),
                 swipe(finger2Start, finger2End, SWIPE_TIME_MILLIS));
         List<MotionEvent> twoFingerPoints = mTouchListener.getRawEvents();
 
@@ -220,26 +220,21 @@
         // adjusted to the middle of two fingers.
         final int numEvents = twoFingerPoints.size();
         final int upEventIndex = numEvents - 1;
-        final float intervalFraction = ((float) (twoFingerPoints.get(1).getEventTime()
-                - twoFingerPoints.get(0).getEventTime())) / SWIPE_TIME_MILLIS;
-        for (int i = 0; i < numEvents; i++) {
-            MotionEvent moveEvent = twoFingerPoints.get(i);
-            float fractionOfDrag = intervalFraction * (i + 1);
-            if (i == 0) {
-                PointF downPoint = add(finger2Start,
-                        ceil(times(fractionOfDrag, diff(dragEnd, dragStart))));
-                assertThat(moveEvent,
-                        both(IS_ACTION_DOWN).and(isRawAtPoint(downPoint)));
-            } else if (i == upEventIndex) {
-                assertThat(moveEvent,
-                        both(IS_ACTION_UP).and(isRawAtPoint(finger2End)));
-            } else {
-                PointF intermediatePoint = add(dragStart,
-                        ceil(times(fractionOfDrag, diff(dragEnd, dragStart))));
-                assertThat(moveEvent,
-                        both(IS_ACTION_MOVE).and(isRawAtPoint(intermediatePoint)));
-            }
-        }
+        final float stepDuration =
+                (float)
+                        (twoFingerPoints.get(1).getEventTime()
+                                - twoFingerPoints.get(0).getEventTime());
+        final float gestureDuration =
+                (float)
+                        (twoFingerPoints.get(upEventIndex).getEventTime()
+                                - twoFingerPoints.get(0).getEventTime());
+        final float intervalFraction =
+                stepDuration * (mSwipeDistance / gestureDuration) / gestureDuration;
+        PointF downPoint = add(dragStart, ceil(times(intervalFraction, diff(dragEnd, dragStart))));
+        assertThat(twoFingerPoints.get(0), both(IS_ACTION_DOWN).and(isRawAtPoint(downPoint, 1.0f)));
+        assertThat(
+                twoFingerPoints.get(upEventIndex),
+                both(IS_ACTION_UP).and(isRawAtPoint(finger2End, 1.0f)));
     }
 
     /** Test a basic single tap which should initiate touch exploration. */
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/GestureUtils.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/GestureUtils.java
index 68055cc..4e367a2 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/GestureUtils.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/GestureUtils.java
@@ -246,7 +246,7 @@
         return new TypeSafeMatcher<MotionEvent>() {
             @Override
             protected boolean matchesSafely(MotionEvent event) {
-                return Math.hypot(event.getX() - point.x, event.getY() - point.y) < tol;
+                return Math.hypot(event.getX() - point.x, event.getY() - point.y) <= tol;
             }
 
             @Override
@@ -270,7 +270,7 @@
         return new TypeSafeMatcher<MotionEvent>() {
             @Override
             protected boolean matchesSafely(MotionEvent event) {
-                return Math.hypot(event.getRawX() - point.x, event.getRawY() - point.y) < tol;
+                return Math.hypot(event.getRawX() - point.x, event.getRawY() - point.y) <= tol;
             }
 
             @Override
diff --git a/tests/framework/base/windowmanager/AndroidManifest.xml b/tests/framework/base/windowmanager/AndroidManifest.xml
index 4402729..3bac7cd 100644
--- a/tests/framework/base/windowmanager/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/AndroidManifest.xml
@@ -180,6 +180,8 @@
                   android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density|touchscreen"
         />
 
+        <activity android:name="android.server.wm.KeyguardLockedTests$ShowImeAfterLockscreenActivity" />
+
         <activity android:name="android.server.wm.KeyguardLockedTests$ShowWhenLockedImeActivity" />
 
         <activity android:name="android.server.wm.lifecycle.ActivityStarterTests$StandardActivity"
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java
index f57b3b2..c699460 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/KeyguardLockedTests.java
@@ -31,20 +31,27 @@
 import static android.server.wm.app.Components.SHOW_WHEN_LOCKED_ATTR_IME_ACTIVITY;
 import static android.server.wm.app.Components.TURN_SCREEN_ON_ATTR_DISMISS_KEYGUARD_ACTIVITY;
 import static android.view.Display.DEFAULT_DISPLAY;
+import static android.view.WindowInsets.Type.ime;
 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
 import static com.android.cts.mockime.ImeEventStreamTestUtils.expectEvent;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assume.assumeTrue;
 
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
 import android.app.Activity;
 import android.app.KeyguardManager;
 import android.content.ComponentName;
 import android.os.Bundle;
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
+import android.view.View;
 import android.widget.EditText;
 import android.widget.LinearLayout;
+
+import com.android.compatibility.common.util.CtsTouchUtils;
+import com.android.compatibility.common.util.PollingCheck;
 import com.android.cts.mockime.ImeEventStream;
 import com.android.cts.mockime.MockImeSession;
 
@@ -59,6 +66,9 @@
 @Presubmit
 @android.server.wm.annotation.Group2
 public class KeyguardLockedTests extends KeyguardTestBase {
+
+    private final static long TIMEOUT_IME = TimeUnit.SECONDS.toMillis(5);
+
     @Before
     @Override
     public void setUp() throws Exception {
@@ -317,7 +327,7 @@
         // Make sure the activity has been called showSoftInput & IME window is visible.
         final ImeEventStream stream = mockImeSession.openEventStream();
         expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()),
-                TimeUnit.SECONDS.toMillis(5) /* eventTimeout */);
+                TIMEOUT_IME);
         // Assert the IME is shown on the expected display.
         mWmState.waitAndAssertImeWindowShownOnDisplay(DEFAULT_DISPLAY);
     }
@@ -339,34 +349,93 @@
         // Make sure the activity has been called showSoftInput & IME window is visible.
         final ImeEventStream stream = mockImeSession.openEventStream();
         expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()),
-                TimeUnit.SECONDS.toMillis(5) /* eventTimeout */);
+                TIMEOUT_IME);
         // Assert the IME is shown on the expected display.
         mWmState.waitAndAssertImeWindowShownOnDisplay(DEFAULT_DISPLAY);
 
     }
 
+    @Test
+    public void testImeShowsAfterLockScreenOnEditorTap() throws Exception {
+        assumeTrue(MSG_NO_MOCK_IME, supportsInstallableIme());
+
+        final MockImeSession mockImeSession = createManagedMockImeSession(this);
+        final LockScreenSession lockScreenSession = createManagedLockScreenSession();
+        final TestActivitySession<ShowImeAfterLockscreenActivity> imeTestActivitySession =
+                createManagedTestActivitySession();
+        imeTestActivitySession.launchTestActivityOnDisplaySync(ShowImeAfterLockscreenActivity.class,
+                DEFAULT_DISPLAY);
+
+        final ShowImeAfterLockscreenActivity activity = imeTestActivitySession.getActivity();
+        final View rootView = activity.getWindow().getDecorView();
+
+        CtsTouchUtils.emulateTapOnViewCenter(getInstrumentation(), null, activity.mEditor);
+        PollingCheck.waitFor(
+                TIMEOUT_IME,
+                () -> rootView.getRootWindowInsets().isVisible(ime()));
+
+        lockScreenSession.setLockCredential().gotoKeyguard();
+        assertTrue("Keyguard is showing", mWmState.getKeyguardControllerState().keyguardShowing);
+        lockScreenSession.enterAndConfirmLockCredential();
+        mWmState.waitAndAssertKeyguardGone();
+
+        final ImeEventStream stream = mockImeSession.openEventStream();
+
+        CtsTouchUtils.emulateTapOnViewCenter(getInstrumentation(), null, activity.mEditor);
+
+        // Make sure the activity has been called showSoftInput & IME window is visible.
+        expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()),
+                TimeUnit.SECONDS.toMillis(5) /* eventTimeout */);
+        // Assert the IME is shown event on the expected display.
+        mWmState.waitAndAssertImeWindowShownOnDisplay(DEFAULT_DISPLAY);
+        // Check if IME is actually visible.
+        PollingCheck.waitFor(
+                TIMEOUT_IME,
+                () -> rootView.getRootWindowInsets().isVisible(ime()));
+    }
+
+    public static class ShowImeAfterLockscreenActivity extends Activity {
+
+        EditText mEditor;
+
+        @Override
+        protected void onCreate(Bundle icicle) {
+            super.onCreate(icicle);
+            mEditor = createViews(this, false /* showWhenLocked */);
+        }
+    }
+
     public static class ShowWhenLockedImeActivity extends Activity {
 
         @Override
         protected void onCreate(Bundle icicle) {
             super.onCreate(icicle);
-            final EditText editText = new EditText(this);
-            // Set private IME option for editorMatcher to identify which TextView received
-            // onStartInput event.
-            editText.setPrivateImeOptions(
-                    getClass().getName() + "/" + Long.toString(SystemClock.elapsedRealtimeNanos()));
-            final LinearLayout layout = new LinearLayout(this);
-            layout.setOrientation(LinearLayout.VERTICAL);
-            layout.addView(editText);
-            setContentView(layout);
-
-            // Set showWhenLocked as true & request focus for showing soft input.
-            setShowWhenLocked(true);
-            getWindow().setSoftInputMode(SOFT_INPUT_STATE_ALWAYS_VISIBLE);
-            editText.requestFocus();
+            createViews(this, true /* showWhenLocked */);
         }
     }
 
+    private static EditText createViews(
+            Activity activity, boolean showWhenLocked /* showWhenLocked */) {
+        EditText editor = new EditText(activity);
+        // Set private IME option for editorMatcher to identify which TextView received
+        // onStartInput event.
+        editor.setPrivateImeOptions(
+                activity.getClass().getName()
+                        + "/" + Long.toString(SystemClock.elapsedRealtimeNanos()));
+        final LinearLayout layout = new LinearLayout(activity);
+        layout.setOrientation(LinearLayout.VERTICAL);
+        layout.addView(editor);
+        activity.setContentView(layout);
+
+        if (showWhenLocked) {
+            // Set showWhenLocked as true & request focus for showing soft input.
+            activity.setShowWhenLocked(true);
+            activity.getWindow().setSoftInputMode(SOFT_INPUT_STATE_ALWAYS_VISIBLE);
+        }
+        editor.requestFocus();
+        return editor;
+    }
+
     /**
      * Waits until the given activity has entered picture-in-picture mode (allowing for the
      * subsequent animation to start).
diff --git a/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt b/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
index e5c05ce..71a4263 100644
--- a/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/RuntimeMessageCollectionTest.kt
@@ -33,7 +33,7 @@
 
 @AppModeFull(reason = "Test relies on seeing other apps. Instant apps can't see other apps")
 class RuntimeMessageCollectionTest {
-    private val TIMEOUT_MILLIS = 15000L
+    private val TIMEOUT_MILLIS = 5000L
     private val instrumentation = InstrumentationRegistry.getInstrumentation()
     private val context = instrumentation.targetContext
     private val appOpsManager = context.getSystemService(AppOpsManager::class.java)
@@ -53,7 +53,7 @@
 
     @Test
     fun collectAsyncStackTrace() {
-        for (attempt in 0..20) {
+        for (attempt in 0..12) {
             installApk("CtsAppToCollect.apk")
             val start = System.currentTimeMillis()
             runWithShellPermissionIdentity {
diff --git a/tests/tests/content/src/android/content/cts/ContentProviderTest.java b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
index 99d4f48..0e1172a 100644
--- a/tests/tests/content/src/android/content/cts/ContentProviderTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
@@ -21,6 +21,7 @@
 import android.content.ContentValues;
 import android.content.Context;
 import android.content.ContentProvider.CallingIdentity;
+import android.content.pm.PackageManager;
 import android.content.pm.ProviderInfo;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
@@ -252,6 +253,13 @@
         }
     }
 
+    public void testCheckUriPermission() {
+        MockContentProvider provider = new MockContentProvider();
+        final Uri uri = Uri.parse("content://test");
+        assertEquals(PackageManager.PERMISSION_DENIED,
+                provider.checkUriPermission(uri, android.os.Process.myUid(), 0));
+    }
+
     private class MockContentProvider extends ContentProvider {
         private int mInsertCount = 0;
 
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index e4d4f62..08b6977 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -62,6 +62,7 @@
 import com.android.compatibility.common.util.CddTest;
 import com.android.internal.annotations.GuardedBy;
 
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -1611,4 +1612,45 @@
             assertEquals("Allowed capture policy doesn't match", setPolicy, getPolicy);
         }
     }
+
+    public void testIsHdmiSystemAudidoSupported() {
+        // just make sure the call works
+        boolean isSupported = mAudioManager.isHdmiSystemAudioSupported();
+        Log.d(TAG, "isHdmiSystemAudioSupported() = " + isSupported);
+    }
+
+    public void testIsBluetoothScoAvailableOffCall() {
+        // just make sure the call works
+        boolean isSupported = mAudioManager.isBluetoothScoAvailableOffCall();
+        Log.d(TAG, "isBluetoothScoAvailableOffCall() = " + isSupported);
+    }
+
+    public void testStartStopBluetoothSco() {
+        mAudioManager.startBluetoothSco();
+        mAudioManager.stopBluetoothSco();
+    }
+
+    public void testStartStopBluetoothScoVirtualCall() {
+        mAudioManager.startBluetoothScoVirtualCall();
+        mAudioManager.stopBluetoothSco();
+    }
+
+    public void testGetAdditionalOutputDeviceDelay() {
+        AudioDeviceInfo[] devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_ALL);
+        for (AudioDeviceInfo device : devices) {
+            long delay = mAudioManager.getAdditionalOutputDeviceDelay(device);
+            assertTrue("getAdditionalOutputDeviceDelay() = " + delay +" (should be >= 0)",
+                    delay >= 0);
+            delay = mAudioManager.getMaxAdditionalOutputDeviceDelay(device);
+            assertTrue("getMaxAdditionalOutputDeviceDelay() = " + delay +" (should be >= 0)",
+                    delay >= 0);
+        }
+    }
+
+    // getParameters() & setParameters() are deprecated, so don't test
+
+    // setAdditionalOutputDeviceDelay(), getAudioVolumeGroups(), getVolumeIndexForAttributes()
+    // getMinVolumeIndexForAttributes(), getMaxVolumeIndexForAttributes() &
+    // setVolumeIndexForAttributes() require privledged permission MODIFY_AUDIO_ROUTING
+    // and thus cannot be tested here.
 }
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 6f4157a..fd96d40 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
@@ -37,6 +37,8 @@
 import android.media.ExifInterface;
 import android.net.Uri;
 import android.os.Bundle;
+import android.os.Environment;
+import android.os.FileUtils;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.os.storage.StorageManager;
@@ -63,6 +65,7 @@
 
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -73,6 +76,9 @@
 public class MediaStore_Images_MediaTest {
     private static final String MIME_TYPE_JPEG = "image/jpeg";
 
+    private static final File EXTERNAL_STORAGE_DIR = Environment.getExternalStorageDirectory();
+    private static final File DCIM_DIR = new File(EXTERNAL_STORAGE_DIR, Environment.DIRECTORY_DCIM);
+
     private Context mContext;
     private ContentResolver mContentResolver;
 
@@ -290,6 +296,47 @@
         }
     }
 
+    @Test
+    public void testUpsert() throws Exception {
+        File file = null;
+        try {
+            // Create file
+            file = copyResourceToFile(R.raw.scenery, DCIM_DIR, "cts" + System.nanoTime() + ".jpg");
+            final String externalPath = file.getAbsolutePath();
+
+            // Verify a record exists in MediaProvider.
+            final Uri scannedUri = MediaStore.scanFile(mContentResolver, file);
+            assertNotNull(scannedUri);
+
+            // Now insert via ContentResolver and verify it works.
+            ContentValues values = new ContentValues();
+            values.put(Media.DATA, externalPath);
+
+            // This insert is really an upsert. It should work.
+            final Uri uri = mContentResolver.insert(mExternalImages, values);
+            assertNotNull(uri);
+            // insert was an upsert, _id in uri and scannedUri should be same.
+            assertEquals(uri.getLastPathSegment(), scannedUri.getLastPathSegment());
+        } finally {
+            if (file != null) {
+                file.delete();
+            }
+        }
+    }
+
+    private File copyResourceToFile(int sourceResId, File destinationDir,
+            String destinationFileName) throws Exception {
+        final File file = new File(destinationDir, destinationFileName);
+        file.createNewFile();
+
+        try (InputStream source = InstrumentationRegistry.getTargetContext().getResources()
+                .openRawResource(sourceResId);
+             OutputStream target = new FileOutputStream(file)) {
+            FileUtils.copy(source, target);
+        }
+        return file;
+    }
+
     private void assertInsertionSuccess(String stringUrl) throws IOException {
         final Uri uri = Uri.parse(stringUrl);
 
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
index 7cb6b1e..0916756 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
@@ -2795,6 +2795,27 @@
         }
     }
 
+    @Test
+    public void testOpportunisticNetworkState() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        boolean isEnabled = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                tm -> tm.isOpportunisticNetworkEnabled());
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setOpportunisticNetworkState(true));
+        assertTrue(ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                tm -> tm.isOpportunisticNetworkEnabled()));
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setOpportunisticNetworkState(false));
+        assertFalse(ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                tm -> tm.isOpportunisticNetworkEnabled()));
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setOpportunisticNetworkState(isEnabled));
+    }
+
+
     private boolean isDataEnabled() {
         return ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
                 TelephonyManager::isDataEnabled);