Merge "The low-end machine has poor performance, cause some cts with high performance requirements fail" into stage-aosp-rvc-ts-dev
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index f398a18..b6bfc21 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -1647,7 +1647,7 @@
             <meta-data android:name="test_required_features"
                        android:value="android.software.secure_lock_screen" />
             <meta-data android:name="test_excluded_features"
-                       android:value="android.software.lockscreen_disabled" />
+                       android:value="android.hardware.type.automotive:android.software.lockscreen_disabled" />
         </activity>
 
         <activity android:name=".streamquality.StreamingVideoActivity"
@@ -2370,6 +2370,7 @@
                 android:resource="@xml/accessory_filter" />
         </activity>
 
+<!-- Temporary disabled b/c of incorrect assumptions in part of the test: b/160938927
         <activity android:name=".usb.device.UsbDeviceTestActivity"
                 android:label="@string/usb_device_test"
                 android:configChanges="keyboardHidden|orientation|screenSize">
@@ -2383,6 +2384,7 @@
             <meta-data android:name="test_excluded_features"
                     android:value="android.hardware.type.watch" />
         </activity>
+        -->
 
         <activity android:name=".usb.mtp.MtpHostTestActivity" android:label="@string/mtp_host_test">
             <intent-filter>
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 19a8147..13247fc 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -1201,7 +1201,7 @@
       If your device supports type B (for example, because of a type B only UICC), select "Type B" from the drop-down box above. Note that all tests must be completed in the same mode (either "Type A" or "Type B").</string>
     <string name="nfc_offhost_please_wait">Please wait</string>
     <string name="nfc_offhost_setting_up">Setting up card emulation services...</string>
-    <string name="nfc_offhost_uicc_transaction_event_emulator_help">Switch application to background before starting tests. Successful transaction event will switch application to foreground with transaction event data.</string>
+    <string name="nfc_offhost_uicc_transaction_event_emulator_help"> This is an optional test for Android version beofre S. This is okay to set this test to passed and continue. Switch application to background before starting tests. Successful transaction event will switch application to foreground with transaction event data.</string>
 
     <!-- Strings for Sensor Test Activities -->
     <string name="snsr_device_admin_receiver">Sensor Tests Device Admin Receiver</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java
index 037dd7f..795028e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java
@@ -29,6 +29,7 @@
 import android.nfc.NfcAdapter;
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
@@ -53,7 +54,11 @@
 
         setContentView(R.layout.pass_fail_text);
         setPassFailButtonClickListeners();
-        getPassButton().setEnabled(false);
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
+            getPassButton().setEnabled(false);
+        } else {
+            getPassButton().setEnabled(true);
+        }
 
         mTextView = (TextView) findViewById(R.id.text);
         mTextView.setTextSize(12.0f);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java
index 6f257af..34a418b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java
@@ -29,6 +29,7 @@
 import android.nfc.NfcAdapter;
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
@@ -53,7 +54,11 @@
 
         setContentView(R.layout.pass_fail_text);
         setPassFailButtonClickListeners();
-        getPassButton().setEnabled(false);
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
+            getPassButton().setEnabled(false);
+        } else {
+            getPassButton().setEnabled(true);
+        }
 
         mTextView = (TextView) findViewById(R.id.text);
         mTextView.setTextSize(12.0f);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java
index d79674d..6055ac4 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java
@@ -29,6 +29,7 @@
 import android.nfc.NfcAdapter;
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
@@ -53,7 +54,11 @@
 
         setContentView(R.layout.pass_fail_text);
         setPassFailButtonClickListeners();
-        getPassButton().setEnabled(false);
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
+            getPassButton().setEnabled(false);
+        } else {
+            getPassButton().setEnabled(true);
+        }
 
         mTextView = (TextView) findViewById(R.id.text);
         mTextView.setTextSize(12.0f);
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/CpuFeatures.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/CpuFeatures.java
index 9360942..43a6f00 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/CpuFeatures.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/CpuFeatures.java
@@ -58,6 +58,8 @@
 
     public static native int getHwCaps();
 
+    public static native boolean isNativeBridgedCpu();
+
     public static boolean isArm64CpuIn32BitMode() {
         if (!isArmCpu()) {
             return false;
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
index fb25dd7..cf8fddf 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
@@ -16,7 +16,10 @@
 
 package com.android.compatibility.common.util;
 
+import static org.junit.Assert.assertNotEquals;
+
 import android.os.Build;
+import android.os.SystemProperties;
 
 import androidx.test.InstrumentationRegistry;
 
@@ -41,7 +44,7 @@
     private static final String BUILD_TYPE_PROPERTY = "ro.build.type";
     private static final String MANUFACTURER_PROPERTY = "ro.product.manufacturer";
     private static final String TAG_DEV_KEYS = "dev-keys";
-    private static final String VNDK_VERSION = "ro.vndk.version";
+    private static final String VENDOR_SDK_VERSION = "ro.vendor.build.version.sdk";
 
     public static final String GOOGLE_SETTINGS_QUERY =
             "content query --uri content://com.google.settings/partner";
@@ -76,29 +79,25 @@
 
     /**
      * Return whether the SDK version of the vendor partiton is newer than the given API level.
-     * If the property is set to non-integer value, this means the vendor partition is using
-     * current API level and true is returned.
      */
     public static boolean isVendorApiLevelNewerThan(int apiLevel) {
-        int vendorApiLevel = getPropertyInt(VNDK_VERSION);
-        if (vendorApiLevel == INT_VALUE_IF_UNSET) {
-            return true;
-        }
-        return vendorApiLevel > apiLevel;
+        int vendorSdkVersion = SystemProperties.getInt(VENDOR_SDK_VERSION, 0);
+
+        assertNotEquals(0, vendorSdkVersion);
+
+        return vendorSdkVersion > apiLevel;
     }
 
     /**
      * Return whether the SDK version of the vendor partiton is same or newer than the
      * given API level.
-     * If the property is set to non-integer value, this means the vendor partition is using
-     * current API level and true is returned.
      */
     public static boolean isVendorApiLevelAtLeast(int apiLevel) {
-        int vendorApiLevel = getPropertyInt(VNDK_VERSION);
-        if (vendorApiLevel == INT_VALUE_IF_UNSET) {
-            return true;
-        }
-        return vendorApiLevel >= apiLevel;
+        int vendorSdkVersion = SystemProperties.getInt(VENDOR_SDK_VERSION, 0);
+
+        assertNotEquals(0, vendorSdkVersion);
+
+        return vendorSdkVersion >= apiLevel;
     }
 
     /**
diff --git a/common/device-side/util/jni/Android.bp b/common/device-side/util/jni/Android.bp
index 536214a..b5b0b56 100644
--- a/common/device-side/util/jni/Android.bp
+++ b/common/device-side/util/jni/Android.bp
@@ -27,6 +27,8 @@
         "libdl",
     ],
 
+    stl: "c++_static",
+
     static_libs: ["cpufeatures"],
     sdk_version: "19",
 
diff --git a/common/device-side/util/jni/android_cts_CpuFeatures.cpp b/common/device-side/util/jni/android_cts_CpuFeatures.cpp
index 32a5903..41fa5ab 100644
--- a/common/device-side/util/jni/android_cts_CpuFeatures.cpp
+++ b/common/device-side/util/jni/android_cts_CpuFeatures.cpp
@@ -18,6 +18,9 @@
 #include <jni.h>
 #include <string.h>
 #include <sys/auxv.h>
+#include <sys/utsname.h>
+
+#include <string>
 
 jboolean android_cts_CpuFeatures_isArmCpu(JNIEnv* env, jobject thiz)
 {
@@ -60,6 +63,20 @@
     return (jint)getauxval(AT_HWCAP);
 }
 
+jboolean android_cts_CpuFeatures_isNativeBridgedCpu(JNIEnv* env, jobject thiz)
+{
+#if defined(__arm__) || defined(__aarch64__)
+  // If the test is compiled for arm use uname() to check if host CPU is x86.
+  struct utsname uname_data;
+  uname(&uname_data);
+  std::string machine = uname_data.machine;
+  // Matches all of i386, i686 and x86_64.
+  return machine.find("86") != std::string::npos;
+#else
+  return false;
+#endif
+}
+
 static JNINativeMethod gMethods[] = {
     {  "isArmCpu", "()Z",
             (void *) android_cts_CpuFeatures_isArmCpu  },
@@ -75,6 +92,8 @@
             (void *) android_cts_CpuFeatures_isX86_64Cpu  },
     {  "getHwCaps", "()I",
             (void *) android_cts_CpuFeatures_getHwCaps  },
+    {  "isNativeBridgedCpu", "()Z",
+            (void *) android_cts_CpuFeatures_isNativeBridgedCpu  },
 };
 
 int register_android_cts_CpuFeatures(JNIEnv* env)
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java
index 4e8cadf..f439579 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java
@@ -239,11 +239,12 @@
         mContext.registerReceiver(receiver, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
 
         testUnlockDevice();
-        setUpExternalStoragePaths();
 
         assertTrue("User not unlocked", unlocked.await(1, TimeUnit.MINUTES));
         assertTrue("No locked boot complete", bootCompleted.await(1, TimeUnit.MINUTES));
 
+        setUpExternalStoragePaths();
+
         // The test app process should be still running, make sure CE DE now is available
         testAppACeDataExists();
         testAppADeDataExists();
@@ -283,4 +284,4 @@
             mContext.unbindService(mServiceConnection);
         }
     }
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
index 8aed0cf..106434f 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
@@ -111,7 +111,7 @@
         try {
             //Enfornce to set the list mode
             //Because UiScrollable can't reach the real bottom (when WEB_LINKABLE_FILE item) in grid mode when screen landscape mode
-            new UiObject(new UiSelector().resourceId("com.android.documentsui:id/option_menu_list")).click();
+            new UiObject(new UiSelector().resourceId(getDocumentsUiPackageId() + ":id/sub_menu_list")).click();
             mDevice.waitForIdle();
         }catch (UiObjectNotFoundException e){
             //do nothing, already be in list mode.
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java b/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
index 7d94aed..af75c90 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
@@ -197,6 +197,9 @@
         // Rename to ensure that stats are updated
         video.renameTo(new File(dir, System.nanoTime() + ".PnG"));
 
+        // Since we have MANAGE_EXTERNAL_STORAGE, need to ask for a re-scan
+        MediaStore.scanFile(getContext().getContentResolver(), dir);
+        MediaStore.scanFile(getContext().getContentResolver(), downloadsDir);
         MediaStore.waitForIdle(getContext().getContentResolver());
 
         final ExternalStorageStats afterRename = stats.queryExternalStatsForUser(UUID_DEFAULT, user);
diff --git a/hostsidetests/deviceidle/src/com/android/cts/deviceidle/DeviceIdleWhitelistTest.java b/hostsidetests/deviceidle/src/com/android/cts/deviceidle/DeviceIdleWhitelistTest.java
index bdba196..def9d75 100644
--- a/hostsidetests/deviceidle/src/com/android/cts/deviceidle/DeviceIdleWhitelistTest.java
+++ b/hostsidetests/deviceidle/src/com/android/cts/deviceidle/DeviceIdleWhitelistTest.java
@@ -91,7 +91,9 @@
         final List<String> packages = new ArrayList<>();
         for (String line : output.split("\n")) {
             final int i = line.indexOf(',');
-            packages.add(line.substring(0, i));
+            if (i > 0) {
+                packages.add(line.substring(0, i));
+            }
         }
         return packages;
     }
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java
index 8a4f45c..6b41018 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java
@@ -62,7 +62,7 @@
             "com.android.cts.crossprofileappstest:id/user_textview";
     private static final String ID_USER_TEXTVIEW_NONMAIN =
             "com.android.cts.crossprofileappstest:id/user_textview_nonmain";
-    private static final long TIMEOUT_WAIT_UI = TimeUnit.SECONDS.toMillis(10);
+    private static final long TIMEOUT_WAIT_UI = TimeUnit.SECONDS.toMillis(15);
 
     private CrossProfileApps mCrossProfileApps;
     private UserHandle mTargetUser;
diff --git a/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java b/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java
index 88a3179..70f694d 100644
--- a/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java
+++ b/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java
@@ -45,7 +45,7 @@
 @RunWith(AndroidJUnit4.class)
 public class HarmfulAppWarningDeviceTest {
 
-    private static final long TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(1);
+    private static final long TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(3);
 
     private static final String ACTION_ACTIVITY_STARTED =
             "android.harmfulappwarning.sampleapp.ACTIVITY_STARTED";
diff --git a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
index 34e8f04..9237046 100644
--- a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
+++ b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
@@ -622,11 +622,20 @@
      * Asserts can rename file.
      */
     public static void assertCanRenameFile(File oldFile, File newFile) {
+        assertCanRenameFile(oldFile, newFile, /* checkDB */ true);
+    }
+
+    /**
+     * Asserts can rename file and optionally checks if the database is updated after rename.
+     */
+    public static void assertCanRenameFile(File oldFile, File newFile, boolean checkDatabase) {
         assertThat(oldFile.renameTo(newFile)).isTrue();
         assertThat(oldFile.exists()).isFalse();
         assertThat(newFile.exists()).isTrue();
-        assertThat(getFileRowIdFromDatabase(oldFile)).isEqualTo(-1);
-        assertThat(getFileRowIdFromDatabase(newFile)).isNotEqualTo(-1);
+        if (checkDatabase) {
+            assertThat(getFileRowIdFromDatabase(oldFile)).isEqualTo(-1);
+            assertThat(getFileRowIdFromDatabase(newFile)).isNotEqualTo(-1);
+        }
     }
 
     /**
diff --git a/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java b/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
index 6541a7b..abf72f0 100644
--- a/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
+++ b/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
@@ -2184,18 +2184,18 @@
             assertFileContent(otherAppPdf, BYTES_DATA1);
 
             // Assert we can rename the file and ensure the file has the same content
-            assertCanRenameFile(otherAppPdf, pdf);
+            assertCanRenameFile(otherAppPdf, pdf, /* checkDatabase */ false);
             assertFileContent(pdf, BYTES_DATA1);
             // We can even move it to the top level directory
-            assertCanRenameFile(pdf, topLevelPdf);
+            assertCanRenameFile(pdf, topLevelPdf, /* checkDatabase */ false);
             assertFileContent(topLevelPdf, BYTES_DATA1);
             // And even rename to a place where PDFs don't belong, because we're an omnipotent
             // external storage manager
-            assertCanRenameFile(topLevelPdf, pdfInObviouslyWrongPlace);
+            assertCanRenameFile(topLevelPdf, pdfInObviouslyWrongPlace, /* checkDatabase */ false);
             assertFileContent(pdfInObviouslyWrongPlace, BYTES_DATA1);
 
             // And we can even convert it into a music file, because why not?
-            assertCanRenameFile(pdfInObviouslyWrongPlace, musicFile);
+            assertCanRenameFile(pdfInObviouslyWrongPlace, musicFile, /* checkDatabase */ false);
             assertFileContent(musicFile, BYTES_DATA1);
         } finally {
             pdf.delete();
diff --git a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java
index 0944bbb..08baa6c 100644
--- a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java
+++ b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java
@@ -64,7 +64,7 @@
         }
         final int secondUserID = getOrCreateSecondaryUser();
 
-        getDevice().startUser(secondUserID);
+        getDevice().startUser(secondUserID, true);
         getDevice().switchUser(secondUserID);
         installAppAsUser(TARGET_APK, secondUserID);
 
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 144e28e..f24075e 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
@@ -271,7 +271,7 @@
                 Log.e(TAG, "Could not enable bluetooth to trigger state reset");
                 return;
             }
-            sleep(2_000); // Wait for Bluetooth to fully turn on.
+            sleep(3_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);
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java
index 2c8535d..2fb7916 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java
@@ -50,6 +50,20 @@
  */
 @RunWith(AndroidJUnit4.class)
 public class AccessibilityServiceInfoTest {
+    private static final int FLAGS_MASK = AccessibilityServiceInfo.DEFAULT
+            | AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
+            | AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY
+            | AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
+            | AccessibilityServiceInfo.FLAG_ENABLE_ACCESSIBILITY_VOLUME
+            | AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON
+            | AccessibilityServiceInfo.FLAG_REQUEST_FINGERPRINT_GESTURES
+            | AccessibilityServiceInfo.FLAG_SERVICE_HANDLES_DOUBLE_TAP
+            | AccessibilityServiceInfo.FLAG_REQUEST_MULTI_FINGER_GESTURES
+            | AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE
+            | AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS
+            | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
+            | AccessibilityServiceInfo.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK;
+
     private AccessibilityManager mAccessibilityManager;
     private PackageManager mPackageManager;
 
@@ -102,13 +116,16 @@
         final AccessibilityServiceInfo speakingService = enabledServices.get(0);
         assertSame(AccessibilityEvent.TYPES_ALL_MASK, speakingService.eventTypes);
         assertSame(AccessibilityServiceInfo.FEEDBACK_SPOKEN, speakingService.feedbackType);
-        assertEquals(AccessibilityServiceInfo.DEFAULT
+
+        int serviceFlags = AccessibilityServiceInfo.DEFAULT
                 | AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
                 | AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE
                 | AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS
                 | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
-                | AccessibilityServiceInfo.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK,
-                speakingService.flags);
+                | AccessibilityServiceInfo.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK;
+
+        assertEquals(speakingService.flags & FLAGS_MASK, serviceFlags);
+
         assertSame(/* expected= */ 0l, speakingService.notificationTimeout);
         assertEquals(/* expected= */ "Some description", speakingService.getDescription());
         assertNull(speakingService.packageNames /*all packages*/);
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
index be678913..760084b 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
@@ -69,7 +69,10 @@
 
     // Constants
     private static final float GESTURE_LENGTH_INCHES = 1.0f;
-    private static final long STROKE_MS = 400;
+    // The movement should exceed the threshold 1 cm in 150 ms defined in Swipe.java. It means the
+    // swipe velocity in testing should be greater than 2.54 cm / 381 ms. Therefore the
+    // duration should be smaller than 381.
+    private static final long STROKE_MS = 380;
     private static final long GESTURE_DISPATCH_TIMEOUT_MS = 3000;
     private static final long EVENT_DISPATCH_TIMEOUT_MS = 3000;
     private static final PointF FINGER_OFFSET_PX = new PointF(100f, -50f);
@@ -131,8 +134,11 @@
         mCenter = new Point((int) metrics.widthPixels / 2, (int) metrics.heightPixels / 2);
         mTapLocation = new PointF(mCenter);
         mStrokeLenPxX = (int) (GESTURE_LENGTH_INCHES * metrics.xdpi);
-        mStrokeLenPxY = (int) (GESTURE_LENGTH_INCHES * metrics.ydpi);
-        mScreenBigEnough = (metrics.widthPixels / (2 * metrics.xdpi) > GESTURE_LENGTH_INCHES);
+        // The threshold is determined by xdpi.
+        mStrokeLenPxY = mStrokeLenPxX;
+        final boolean screenWideEnough = metrics.widthPixels / 2 > mStrokeLenPxX;
+        final boolean screenHighEnough =  metrics.heightPixels / 2 > mStrokeLenPxY;
+        mScreenBigEnough = screenWideEnough && screenHighEnough;
         if (!mScreenBigEnough) {
             return;
         }
@@ -282,23 +288,6 @@
                 displayId);
 
         testGesture(
-                MultiFingerSwipe(displayId, 2, 0, dy),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_DOWN,
-                displayId);
-        testGesture(
-                MultiFingerSwipe(displayId, 2, -dx, 0),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_LEFT,
-                displayId);
-        testGesture(
-                MultiFingerSwipe(displayId, 2, dx, 0),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_RIGHT,
-                displayId);
-        testGesture(
-                MultiFingerSwipe(displayId, 2, 0, -dy),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_UP,
-                displayId);
-
-        testGesture(
                 MultiFingerSwipe(displayId, 3, 0, dy),
                 AccessibilityService.GESTURE_3_FINGER_SWIPE_DOWN,
                 displayId);
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
index 17acc3b..512c35a 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
@@ -1046,15 +1046,6 @@
         assertEquals(3, Selection.getSelectionStart(editText.getText()));
         assertEquals(3, Selection.getSelectionEnd(editText.getText()));
 
-        // Unfocus the view so we can get rid of the soft-keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous character and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
@@ -2048,15 +2039,6 @@
         assertEquals(11, Selection.getSelectionStart(editText.getText()));
         assertEquals(11, Selection.getSelectionEnd(editText.getText()));
 
-        // Unfocus the view so we can get rid of the soft-keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous word and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
@@ -2801,15 +2783,6 @@
         assertEquals(34, Selection.getSelectionStart(editText.getText()));
         assertEquals(34, Selection.getSelectionEnd(editText.getText()));
 
-        // Unocus the view so we can hide the keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous line and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
@@ -3560,15 +3533,6 @@
         assertEquals(47, Selection.getSelectionStart(editText.getText()));
         assertEquals(47, Selection.getSelectionEnd(editText.getText()));
 
-        // Unfocus the view so we can get rid of the soft-keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous paragraph and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java
index 2cd28c5..aba32d2 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java
@@ -15,6 +15,7 @@
 package android.accessibilityservice.cts.activities;
 
 import android.os.Bundle;
+import android.view.WindowManager;
 
 import android.accessibilityservice.cts.R;
 
@@ -28,5 +29,7 @@
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.accessibility_text_traversal_test);
+        getWindow().setSoftInputMode(
+            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
     }
 }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java
index 44fd804..34b3fc8 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java
@@ -279,8 +279,8 @@
                     AccessibilityNodeInfo node = event.getSource();
                     if (node != null) {
                         final AccessibilityWindowInfo window = node.getWindow();
-                        if(TextUtils.equals(activityTitle, window.getTitle())) {
-                            return  true;
+                        if(!TextUtils.equals(activityTitle, window.getTitle())) {
+                            return  false;
                         }
                     }
                     final AccessibilityWindowInfo window =
diff --git a/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/app/src/android/app/cts/ActivityManagerTest.java
index 1be2930..60df0d9 100644
--- a/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -211,7 +211,7 @@
         private String mActivityToFilter;
         private int result = RESULT_TIMEOUT;
         public long mTimeUsed = 0;
-        private static final int TIMEOUT_IN_MS = 2000;
+        private static final int TIMEOUT_IN_MS = 5000;
 
         // Create the filter with the intent to look for.
         public ActivityReceiverFilter(String activityToFilter) {
@@ -706,6 +706,9 @@
      * activities, the process of the package should not be alive (restarted).
      */
     public void testForceStopPackageWontRestartProcess() throws Exception {
+        // Ensure that there are no remaining component records of the test app package.
+        SystemUtil.runWithShellPermissionIdentity(
+                () -> mActivityManager.forceStopPackage(SIMPLE_PACKAGE_NAME));
         ActivityReceiverFilter appStartedReceiver = new ActivityReceiverFilter(
                 ACTIVITY_LAUNCHED_ACTION);
         // Start an activity of another APK.
diff --git a/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/app/src/android/app/cts/SystemFeaturesTest.java
index c4e1dd1..03012c8 100644
--- a/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -507,8 +507,9 @@
      */
     @Test
     public void testTelephonyFeatures() {
-        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
-            return;
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) ||
+            !mPackageManager.hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) {
+                return;
         }
 
         int phoneType = mTelephonyManager.getPhoneType();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/Helper.java b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
index b3315fd..d71006e 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/Helper.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
@@ -88,6 +88,7 @@
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
+import java.util.regex.Pattern;
 
 /**
  * Helper for common funcionalities.
@@ -234,6 +235,24 @@
     }
 
     /**
+     * Dumps the state of {@link android.service.autofill.InlineSuggestionRenderService}, and assert
+     * that it says the number of active inline suggestion views is the given number.
+     *
+     * <p>Note that ideally we should have a test api to fetch the number and verify against it.
+     * But at the time this test is added for Android 11, we have passed the deadline for adding
+     * the new test api, hence this approach.
+     */
+    public static void assertActiveViewCountFromInlineSuggestionRenderService(int count) {
+        String response = runShellCommand(
+                "dumpsys activity service .InlineSuggestionRenderService");
+        Log.d(TAG, "InlineSuggestionRenderService dump: " + response);
+        Pattern pattern = Pattern.compile(".*mActiveInlineSuggestions: " + count + ".*");
+        assertWithMessage("Expecting view count " + count
+                + ", but seeing different count from service dumpsys " + response).that(
+                pattern.matcher(response).find()).isTrue();
+    }
+
+    /**
      * Sets whether the user completed the initial setup.
      */
     public static void setUserComplete(Context context, boolean complete) {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
index ace3d6f..c7c5070 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
@@ -182,6 +182,37 @@
     /**
      * Sets the expectation for an autofill request (for username only), so it can be asserted
      * through {@link #assertAutoFilled()} later.
+     *
+     * <p><strong>NOTE: </strong>This method checks the result of text change, it should not call
+     * this method too early, it may cause test fail. Call this method before checking autofill
+     * behavior.
+     * <pre>
+     * An example usage is:
+     * <code>
+     *  public void testAutofill() throws Exception {
+     *      // Enable service and trigger autofill
+     *      enableService();
+     *      final CannedFillResponse.Builder builder = new CannedFillResponse.Builder()
+     *                 .addDataset(new CannedFillResponse.CannedDataset.Builder()
+     *                         .setField(ID_USERNAME, "test")
+     *                         .setField(ID_PASSWORD, "tweet")
+     *                         .setPresentation(createPresentation("Second Dude"))
+     *                         .setInlinePresentation(createInlinePresentation("Second Dude"))
+     *                         .build());
+     *      sReplier.addResponse(builder.build());
+     *      mUiBot.selectByRelativeId(ID_USERNAME);
+     *      sReplier.getNextFillRequest();
+     *      // Filter suggestion
+     *      mActivity.onUsername((v) -> v.setText("t"));
+     *      mUiBot.assertDatasets("Second Dude");
+     *
+     *      // Call expectAutoFill() before checking autofill behavior
+     *      mActivity.expectAutoFill("test", "tweet");
+     *      mUiBot.selectDataset("Second Dude");
+     *      mActivity.assertAutoFilled();
+     *  }
+     * </code>
+     * </pre>
      */
     public void expectAutoFill(String username) {
         mExpectation = new FillExpectation(username);
@@ -191,6 +222,10 @@
     /**
      * Sets the expectation for an autofill request (for password only), so it can be asserted
      * through {@link #assertAutoFilled()} later.
+     *
+     * <p><strong>NOTE: </strong>This method checks the result of text change, it should not call
+     * this method too early, it may cause test fail. Call this method before checking autofill
+     * behavior. {@See #expectAutoFill(String)} for how it should be used.
      */
     public void expectPasswordAutoFill(String password) {
         mExpectation = new FillExpectation(null, password);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java
index c761d02..f46dd19 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java
@@ -70,7 +70,6 @@
                         .setInlinePresentation(createInlinePresentation("Second Dude"))
                         .build());
         sReplier.addResponse(builder.build());
-        mActivity.expectAutoFill("test", "tweet");
 
         // Trigger autofill, then make sure it's showing initially.
         mUiBot.selectByRelativeId(ID_USERNAME);
@@ -93,6 +92,7 @@
         mUiBot.waitForIdleSync();
         mUiBot.assertDatasets("Second Dude");
 
+        mActivity.expectAutoFill("test", "tweet");
         mUiBot.selectDataset("Second Dude");
         mUiBot.waitForIdleSync();
         mActivity.assertAutoFilled();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java
index eb18e96..3ca3f34 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java
@@ -44,6 +44,7 @@
 import android.content.Intent;
 import android.os.Binder;
 import android.os.Bundle;
+import android.os.SystemClock;
 import android.platform.test.annotations.AppModeFull;
 import android.service.autofill.FillContext;
 import android.support.test.uiautomator.Direction;
@@ -457,4 +458,59 @@
                     MOCK_IME_TIMEOUT_MS);
         }
     }
+
+    @Test
+    public void testInlineSuggestionViewReleased() throws Exception {
+        // Set service
+        enableService();
+
+        // Prepare the autofill response
+        final CannedFillResponse.Builder builder = new CannedFillResponse.Builder()
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(ID_USERNAME, "dude")
+                        .setPresentation(createPresentation("The Username"))
+                        .setInlinePresentation(createInlinePresentation("The Username"))
+                        .build())
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(ID_PASSWORD, "sweet")
+                        .setPresentation(createPresentation("The Password"))
+                        .setInlinePresentation(createInlinePresentation("The Password"))
+                        .build())
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(ID_PASSWORD, "lollipop")
+                        .setPresentation(createPresentation("The Password2"))
+                        .setInlinePresentation(createInlinePresentation("The Password2"))
+                        .build());
+        sReplier.addResponse(builder.build());
+
+        // Trigger auto-fill on username field
+        mUiBot.selectByRelativeId(ID_USERNAME);
+        mUiBot.waitForIdleSync();
+        mUiBot.assertDatasets("The Username");
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(1);
+
+        // Switch focus to password
+        mUiBot.selectByRelativeId(ID_PASSWORD);
+        mUiBot.waitForIdleSync();
+        mUiBot.assertDatasets("The Password", "The Password2");
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(2);
+
+        // Switch focus back to username
+        mUiBot.selectByRelativeId(ID_USERNAME);
+        mUiBot.waitForIdleSync();
+        mUiBot.assertDatasets("The Username");
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(1);
+
+        // Select the autofill suggestion on username, then check the results
+        mActivity.expectAutoFill("dude");
+        mUiBot.selectDataset("The Username");
+        mUiBot.waitForIdleSync();
+        mActivity.assertAutoFilled();
+        sReplier.getNextFillRequest();
+
+        // Sleep for a while for the wait in {@link com.android.server.autofill.ui
+        // .RemoteInlineSuggestionUi} to timeout.
+        SystemClock.sleep(500);
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(0);
+    }
 }
diff --git a/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java b/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java
index b0c806f..84da4ee 100644
--- a/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java
@@ -735,9 +735,10 @@
                 @Override
                 public void onCaptureProgressed(CameraCaptureSession session,
                         CaptureRequest request, CaptureResult partialResult) {
-                    int aeState = partialResult.get(CaptureResult.CONTROL_AE_STATE);
-                    if (aeState == CaptureRequest.CONTROL_AE_STATE_CONVERGED ||
-                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
+                    Integer aeState = partialResult.get(CaptureResult.CONTROL_AE_STATE);
+                    if (aeState != null &&
+                            (aeState == CaptureRequest.CONTROL_AE_STATE_CONVERGED ||
+                             aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED)) {
                         waitForAeCondition.open();
                     }
                 }
diff --git a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
index 4a02036..94282c8 100644
--- a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
@@ -94,6 +94,7 @@
     private static final int WAIT_FOR_RESULT_TIMEOUT_MS = 3000;
     private static final int NUM_RESULTS_WAIT_TIMEOUT = 100;
     private static final int NUM_FRAMES_WAITED_FOR_UNKNOWN_LATENCY = 8;
+    private static final long FRAME_DURATION_NS_30FPS = 33333333L;
 
     private DeviceReportLog mReportLog;
 
@@ -107,8 +108,10 @@
     private ImageWriter mWriter;
     private SimpleCaptureCallback mZslResultListener;
 
+    private Size mPreviewSize;
     private Surface mPreviewSurface;
     private SurfaceTexture mPreviewSurfaceTexture;
+    private int mImageReaderFormat;
 
     private static final Instrumentation mInstrumentation =
             InstrumentationRegistry.getInstrumentation();
@@ -183,7 +186,7 @@
                         // Blocking start preview (start preview to first image arrives)
                         SimpleCaptureCallback resultListener =
                                 new SimpleCaptureCallback();
-                        blockingStartPreview(resultListener, imageListener);
+                        blockingStartPreview(id, resultListener, imageListener);
                         previewStartedTimeMs = SystemClock.elapsedRealtime();
                         startPreviewTimes[i] = previewStartedTimeMs - configureTimeMs;
                         cameraLaunchTimes[i] = previewStartedTimeMs - startTimeMs;
@@ -378,7 +381,7 @@
                         imageListeners[j] = new SimpleImageListener();
                     }
 
-                    readers = prepareStillCaptureAndStartPreview(previewBuilder, captureBuilder,
+                    readers = prepareStillCaptureAndStartPreview(id, previewBuilder, captureBuilder,
                             mTestRule.getOrderedPreviewSizes().get(0), imageSizes, formats,
                             previewResultListener, NUM_MAX_IMAGES, imageListeners,
                             false /*isHeic*/);
@@ -1151,18 +1154,30 @@
                 BlockingSessionCallback.SESSION_CLOSED, CameraTestUtils.SESSION_CLOSE_TIMEOUT_MS);
     }
 
-    private void blockingStartPreview(CaptureCallback listener, SimpleImageListener imageListener)
-            throws Exception {
+    private void blockingStartPreview(String id, CaptureCallback listener,
+            SimpleImageListener imageListener) throws Exception {
         if (mPreviewSurface == null || mTestRule.getReaderSurface() == null) {
             throw new IllegalStateException("preview and reader surface must be initilized first");
         }
 
+        StreamConfigurationMap config =
+                mTestRule.getStaticInfo().getCharacteristics().get(
+                CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
         CaptureRequest.Builder previewBuilder =
                 mTestRule.getCamera().createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
+        long minFrameDuration = Math.max(FRAME_DURATION_NS_30FPS,
+                config.getOutputMinFrameDuration(mImageReaderFormat, mPreviewSize));
         if (mTestRule.getStaticInfo().isColorOutputSupported()) {
             previewBuilder.addTarget(mPreviewSurface);
+            minFrameDuration = Math.max(minFrameDuration,
+                    config.getOutputMinFrameDuration(SurfaceTexture.class, mPreviewSize));
         }
         previewBuilder.addTarget(mTestRule.getReaderSurface());
+
+        Range<Integer> targetRange =
+                CameraTestUtils.getSuitableFpsRangeForDuration(id,
+                        minFrameDuration, mTestRule.getStaticInfo());
+        previewBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetRange);
         mTestRule.getCameraSession().setRepeatingRequest(
                 previewBuilder.build(), listener, mTestRule.getHandler());
         imageListener.waitForImageAvailable(CameraTestUtils.CAPTURE_IMAGE_TIMEOUT_MS);
@@ -1171,6 +1186,7 @@
     /**
      * Setup still capture configuration and start preview.
      *
+     * @param id The camera id under test
      * @param previewRequest The capture request to be used for preview
      * @param stillRequest The capture request to be used for still capture
      * @param previewSz Preview size
@@ -1181,7 +1197,7 @@
      * @param imageListeners The single capture capture image listeners
      * @param isHeic Capture HEIC image if true, JPEG image if false
      */
-    private ImageReader[] prepareStillCaptureAndStartPreview(
+    private ImageReader[] prepareStillCaptureAndStartPreview(String id,
             CaptureRequest.Builder previewRequest, CaptureRequest.Builder stillRequest,
             Size previewSz, Size[] captureSizes, int[] formats, CaptureCallback resultListener,
             int maxNumImages, ImageReader.OnImageAvailableListener[] imageListeners,
@@ -1202,15 +1218,31 @@
         // Update preview size.
         updatePreviewSurface(previewSz);
 
+        StreamConfigurationMap config =
+                mTestRule.getStaticInfo().getCharacteristics().get(
+                CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
         ImageReader[] readers = new ImageReader[captureSizes.length];
         List<Surface> outputSurfaces = new ArrayList<Surface>();
         outputSurfaces.add(mPreviewSurface);
+        long minFrameDuration = FRAME_DURATION_NS_30FPS;
         for (int i = 0; i < captureSizes.length; i++) {
+            long minFrameDurationForCapture =
+                    config.getOutputMinFrameDuration(formats[i], captureSizes[i]);
+            if (minFrameDurationForCapture > minFrameDuration) {
+                minFrameDuration = minFrameDurationForCapture;
+            }
             readers[i] = CameraTestUtils.makeImageReader(captureSizes[i], formats[i], maxNumImages,
                     imageListeners[i], mTestRule.getHandler());
             outputSurfaces.add(readers[i].getSurface());
         }
 
+        // Update target fps based on min frame durations
+        Range<Integer> targetRange =
+                CameraTestUtils.getSuitableFpsRangeForDuration(id,
+                minFrameDuration, mTestRule.getStaticInfo());
+        previewRequest.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetRange);
+        stillRequest.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetRange);
+
         mTestRule.setCameraSessionListener(new BlockingSessionCallback());
         mTestRule.setCameraSession(CameraTestUtils.configureCameraSession(
                 mTestRule.getCamera(), outputSurfaces,
@@ -1387,10 +1419,11 @@
                 cameraId, mTestRule.getCameraManager(), format,
                 CameraTestUtils.getPreviewSizeBound(mTestRule.getWindowManager(),
                         CameraTestUtils.PREVIEW_SIZE_BOUND)));
-        Size maxPreviewSize = mTestRule.getOrderedPreviewSizes().get(0);
+        mPreviewSize = mTestRule.getOrderedPreviewSizes().get(0);
+        mImageReaderFormat = format;
         mTestRule.createDefaultImageReader(
-                maxPreviewSize, format, NUM_MAX_IMAGES, /*listener*/null);
-        updatePreviewSurface(maxPreviewSize);
+                mPreviewSize, format, NUM_MAX_IMAGES, /*listener*/null);
+        updatePreviewSurface(mPreviewSize);
     }
 
     private void simpleOpenCamera(String cameraId) throws Exception {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
index a876088..0c87438 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
@@ -450,6 +450,8 @@
         launchActivitiesInSplitScreen(
                 getLaunchActivityBuilder().setTargetActivity(DOCKED_ACTIVITY),
                 getLaunchActivityBuilder().setTargetActivity(TEST_ACTIVITY));
+        final Rect restoreDockBounds = mWmState.getStandardRootTaskByWindowingMode(
+                WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) .getBounds();
         resizeDockedStack(STACK_SIZE, STACK_SIZE, TASK_SIZE, TASK_SIZE);
         mWmState.computeState(
                 new WaitForValidActivityState(TEST_ACTIVITY),
@@ -460,6 +462,9 @@
                 WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD);
         mWmState.assertVisibility(DOCKED_ACTIVITY, true);
         mWmState.assertVisibility(TEST_ACTIVITY, true);
+        int restoreW = restoreDockBounds.width();
+        int restoreH = restoreDockBounds.height();
+        resizeDockedStack(restoreW, restoreH, restoreW, restoreH);
     }
 
     @Test
diff --git a/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java b/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java
index d1cca19..4438304 100644
--- a/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java
+++ b/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java
@@ -39,6 +39,8 @@
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 
+import androidx.test.filters.RequiresDevice;
+
 /**
  * Test computing and verifying the pseudoranges based on the raw measurements
  * reported by the GNSS chipset
@@ -251,6 +253,7 @@
      */
     @CddTest(requirement = "7.3.3")
     @AppModeFull(reason = "Flaky in instant mode")
+    @RequiresDevice  // emulated devices do not support real measurements so far.
     public void testPseudoPosition() throws Exception {
         // Checks if Gnss hardware feature is present, skips test (pass) if not
         if (!TestMeasurementUtil.canTestRunOnCurrentDevice(Build.VERSION_CODES.N,
diff --git a/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java b/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java
index 2525581..921b0cc 100644
--- a/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java
@@ -76,6 +76,7 @@
     private static final int STEP_DETECTOR_MIN_FIFO_LENGTH = 100;
 
     private boolean mHasHifiSensors;
+    private boolean mHasProximitySensor;
     private boolean mVrModeHighPerformance;
     private SensorManager mSensorManager;
 
@@ -84,6 +85,7 @@
         PackageManager pm = getContext().getPackageManager();
         mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
         mHasHifiSensors = pm.hasSystemFeature(PackageManager.FEATURE_HIFI_SENSORS);
+        mHasProximitySensor = pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_PROXIMITY);
         mVrModeHighPerformance = pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
     }
 
@@ -197,7 +199,7 @@
     }
 
     public void testProximityFifoLength() throws Throwable {
-        if (!mHasHifiSensors) return;
+        if (!mHasHifiSensors || !mHasProximitySensor) return;
         checkMinFifoLength(Sensor.TYPE_PROXIMITY, PROXIMITY_SENSOR_MIN_FIFO_LENGTH);
     }
 
diff --git a/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt b/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt
index f286d9f..133973a 100644
--- a/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt
@@ -27,7 +27,8 @@
 import android.app.AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED
 import android.app.AppOpsManager.UID_STATE_TOP
 import android.content.Intent
-import android.content.Intent.ACTION_APPLICATION_PREFERENCES
+import android.content.Intent.ACTION_INSTALL_PACKAGE
+import android.net.Uri
 import android.os.SystemClock
 import android.platform.test.annotations.AppModeFull
 import androidx.test.platform.app.InstrumentationRegistry
@@ -251,7 +252,9 @@
     fun noteFromTwoProxiesAndVerifyProxyInfo() {
         // Find another app to blame
         val otherAppInfo = context.packageManager
-                .resolveActivity(Intent(ACTION_APPLICATION_PREFERENCES), 0)
+                .resolveActivity(Intent(ACTION_INSTALL_PACKAGE).addCategory(Intent.CATEGORY_DEFAULT)
+                        .setDataAndType(Uri.parse("content://com.example/foo.apk"),
+                                "application/vnd.android.package-archive"), 0)
                 ?.activityInfo?.applicationInfo
 
         assumeNotNull(otherAppInfo)
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
index 0fa6c9e..efb4432 100644
--- a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
@@ -33,6 +33,7 @@
 import android.os.Message;
 import android.os.Parcel;
 import android.os.Process;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.telephony.AccessNetworkConstants;
 import android.telephony.CellInfo;
@@ -444,7 +445,7 @@
                         return Process.INVALID_UID;
                     }
                 })
-                .filter(uid -> !specialUids.contains(uid))
+                .filter(uid -> !specialUids.contains(UserHandle.getAppId(uid)))
                 .collect(Collectors.toList());
 
         if (nonSpecialPackages.size() > 1) {
diff --git a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
index fa0572c..2ec7ec8 100644
--- a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
+++ b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
@@ -31,6 +31,8 @@
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 
+import com.android.compatibility.common.util.CddTest;
+
 public class ContactsContract_RawContactsTest extends AndroidTestCase {
     private ContentResolver mResolver;
     private ContactsContract_TestDataBuilder mBuilder;
@@ -150,6 +152,7 @@
         assertEquals("1", result[1]);
     }
 
+    @CddTest(requirement = "3.18/C-1-5")
     public void testRawContactDelete_localDeleteRemovesRecord() {
         String name = RawContacts.getLocalAccountName(mContext);
         String type = RawContacts.getLocalAccountType(mContext);
@@ -201,6 +204,7 @@
      * config_rawContactsLocalAccountName and config_rawContactsLocalAccountType resource strings 
      * defined in platform/frameworks/base/core/res/res/values/config.xml.
      */
+    @CddTest(requirement="3.18/C-1-1,C-1-2,C-1-3")
     public void testRawContactCreate_noAccountUsesLocalAccount() {
         // Save a raw contact without an account.
         long rawContactid = RawContactUtil.insertRawContact(mResolver, null);
@@ -218,6 +222,31 @@
         RawContactUtil.delete(mResolver, rawContactid, true);
     }
 
+    /**
+     * The local account is the default if a raw contact insert uses null for
+     * the {@link RawContacts#ACCOUNT_NAME} and {@link RawContacts#ACCOUNT_TYPE}.
+     *
+     * <p>See {@link #testRawContactCreate_noAccountUsesLocalAccount()}
+     */
+    @CddTest(requirement="3.18/C-1-1,C-1-2,C-1-3")
+    public void testRawContactCreate_nullAccountUsesLocalAccount() throws Exception {
+        // Save a raw contact using the default local account
+        TestRawContact rawContact = mBuilder.newRawContact()
+                .with(RawContacts.ACCOUNT_TYPE, (String) null)
+                .with(RawContacts.ACCOUNT_NAME, (String) null)
+                .insert();
+
+        String[] row =  RawContactUtil.queryByRawContactId(mResolver, rawContact.getId(),
+                new String[] {
+                        RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE
+                });
+
+        // When the raw contact is inserted into the default local account the contact is created
+        // in the local account.
+        assertEquals(RawContacts.getLocalAccountName(mContext), row[0]);
+        assertEquals(RawContacts.getLocalAccountType(mContext), row[1]);
+    }
+
     public void testRawContactUpdate_updatesContactUpdatedTimestamp() {
         DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver);
 
diff --git a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java
index ceaee73..9613b14 100755
--- a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java
+++ b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java
@@ -26,6 +26,8 @@
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.MediumTest;
 
+import com.android.compatibility.common.util.CddTest;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -109,6 +111,7 @@
      * {@link android.provider.ContactsContract.RawContacts#ACCOUNT_TYPE} that do not correspond
      * to an added account will be removed but this should not be done for the local account.
      */
+    @CddTest(requirement="3.18/C-1-4")
     public void testAccountRemoval_doesNotDeleteLocalAccountContacts() {
         mAccountManager.addAccountExplicitly(ACCT_1, null, null);
         ArrayList<ContactIdPair> acc1Ids = createContacts(ACCT_1, 5);
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/AbstractDeviceConfigTestCase.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/AbstractDeviceConfigTestCase.java
new file mode 100644
index 0000000..462ee62
--- /dev/null
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/AbstractDeviceConfigTestCase.java
@@ -0,0 +1,67 @@
+/*
+ * 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.deviceconfig.cts;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.content.Context;
+import android.os.UserHandle;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.Executor;
+
+@RunWith(AndroidJUnit4.class)
+abstract class AbstractDeviceConfigTestCase {
+
+    static final Context CONTEXT = InstrumentationRegistry.getContext();
+    static final Executor EXECUTOR = CONTEXT.getMainExecutor();
+
+    static final String WRITE_DEVICE_CONFIG_PERMISSION = "android.permission.WRITE_DEVICE_CONFIG";
+    static final String READ_DEVICE_CONFIG_PERMISSION = "android.permission.READ_DEVICE_CONFIG";
+
+    // String used to skip tests if not support.
+    // TODO: ideally it would be simpler to just use assumeTrue() in the @BeforeClass method, but
+    // then the test would crash - it might be an issue on atest / AndroidJUnit4
+    private static String sUnsupportedReason;
+
+    /**
+     * Get necessary permissions to access and modify properties through DeviceConfig API.
+     */
+    @BeforeClass
+    public static void setUp() throws Exception {
+        if (CONTEXT.getUserId() != UserHandle.USER_SYSTEM
+                && CONTEXT.getPackageManager().isInstantApp()) {
+            sUnsupportedReason = "cannot run test as instant app on secondary user "
+                    + CONTEXT.getUserId();
+        }
+    }
+
+    @Before
+    public void assumeSupported() {
+        assumeTrue(sUnsupportedReason, isSupported());
+    }
+
+    static boolean isSupported() {
+        return sUnsupportedReason == null;
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
index 6d77ebb..a18bbca 100644
--- a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
@@ -16,6 +16,8 @@
 
 package android.deviceconfig.cts;
 
+import androidx.test.InstrumentationRegistry;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
@@ -23,17 +25,13 @@
 import android.provider.DeviceConfig.OnPropertiesChangedListener;
 import android.provider.DeviceConfig.Properties;
 
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
 import org.junit.After;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 import java.util.concurrent.Executor;
 
-@RunWith(AndroidJUnit4.class)
-public final class DeviceConfigApiPermissionTests {
+public final class DeviceConfigApiPermissionTests extends AbstractDeviceConfigTestCase {
     private static final String NAMESPACE = "namespace";
     private static final String NAMESPACE2 = "namespace2";
     private static final String PUBLIC_NAMESPACE = "textclassifier";
@@ -41,16 +39,10 @@
     private static final String KEY2 = "key2";
     private static final String VALUE = "value";
 
-    private static final String WRITE_DEVICE_CONFIG_PERMISSION =
-            "android.permission.WRITE_DEVICE_CONFIG";
-
-    private static final String READ_DEVICE_CONFIG_PERMISSION =
-            "android.permission.READ_DEVICE_CONFIG";
-
-    private static final Executor EXECUTOR = InstrumentationRegistry.getContext().getMainExecutor();
-
     @After
     public void dropShellPermissionIdentityAfterTest() {
+        if (!isSupported()) return;
+
         InstrumentationRegistry.getInstrumentation().getUiAutomation()
                 .dropShellPermissionIdentity();
     }
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java
index 1f6d96e..9fb039d 100644
--- a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java
@@ -28,7 +28,6 @@
 import android.provider.DeviceConfig.Properties;
 
 import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.After;
 import org.junit.AfterClass;
@@ -41,8 +40,7 @@
 import java.util.concurrent.Executor;
 import java.util.concurrent.TimeUnit;
 
-@RunWith(AndroidJUnit4.class)
-public final class DeviceConfigApiTests {
+public final class DeviceConfigApiTests extends AbstractDeviceConfigTestCase {
     private static final String NAMESPACE1 = "namespace1";
     private static final String NAMESPACE2 = "namespace2";
     private static final String EMPTY_NAMESPACE = "empty_namespace";
@@ -70,24 +68,16 @@
     private static final float VALID_FLOAT = 456.789f;
     private static final String INVALID_FLOAT = "34343et";
 
-    private static final Executor EXECUTOR = InstrumentationRegistry.getContext().getMainExecutor();
-
-
     private static final long WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS = 2000; // 2 sec
     private final Object mLock = new Object();
 
-
-    private static final String WRITE_DEVICE_CONFIG_PERMISSION =
-            "android.permission.WRITE_DEVICE_CONFIG";
-
-    private static final String READ_DEVICE_CONFIG_PERMISSION =
-            "android.permission.READ_DEVICE_CONFIG";
-
     /**
      * Get necessary permissions to access and modify properties through DeviceConfig API.
      */
     @BeforeClass
     public static void setUp() throws Exception {
+        if (!isSupported()) return;
+
         InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(
                 WRITE_DEVICE_CONFIG_PERMISSION, READ_DEVICE_CONFIG_PERMISSION);
     }
@@ -97,6 +87,8 @@
      */
     @After
     public void cleanUp() throws Exception {
+        if (!isSupported()) return;
+
         // first wait to make sure callbacks for SetProperties/SetProperty
         // invoked in the test methods got emitted. So that the callbacks
         // won't interfere with setPropertiesAndAssertSuccessfulChange invoked
@@ -114,6 +106,8 @@
      */
     @AfterClass
     public static void cleanUpAfterAllTests() {
+        if (!isSupported()) return;
+
         deletePropertyThrowShell(NAMESPACE1, KEY1);
         deletePropertyThrowShell(NAMESPACE2, KEY1);
         deletePropertyThrowShell(NAMESPACE1, KEY2);
@@ -1096,4 +1090,4 @@
             }
         }
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/jni/Android.bp b/tests/tests/jni/Android.bp
index 386b2ae..74e5426 100644
--- a/tests/tests/jni/Android.bp
+++ b/tests/tests/jni/Android.bp
@@ -27,6 +27,7 @@
     static_libs: [
         "ctstestrunner-axt",
         "androidx.test.rules",
+        "compatibility-device-util-axt",
     ],
     jni_libs: [
         "libjni_test_dlclose",
diff --git a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
index 4742796b..e2bbcd7 100644
--- a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
@@ -16,7 +16,9 @@
 
 package android.jni.cts;
 
+import android.os.Build;
 import android.os.Process;
+import com.android.compatibility.common.util.PropertyUtil;
 import java.io.File;
 import java.io.IOException;
 
@@ -317,9 +319,11 @@
      * dlopen(3) any of the public lib via file name (non-absolute path) should succeed.
      */
     public void test_dlopenPublicLibraries() {
-        String error = LinkerNamespacesHelper.runDlopenPublicLibraries();
-        if (error != null) {
-            fail(error);
+        if (PropertyUtil.isVendorApiLevelAtLeast(Build.VERSION_CODES.R)) {
+            String error = LinkerNamespacesHelper.runDlopenPublicLibraries();
+            if (error != null) {
+                fail(error);
+            }
         }
     }
 
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 55ba086..637d57f 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -780,6 +780,7 @@
                 case 2:
                 case 3:
                 case 4:
+                case 41:
                     assertThat(teeEnforcedDigests, is(expectedDigests));
                     break;
 
@@ -808,8 +809,8 @@
 
     @SuppressWarnings("unchecked")
     private void checkAttestationSecurityLevelDependentParams(Attestation attestation) {
-        assertThat("Attestation version must be 1, 2, or 3", attestation.getAttestationVersion(),
-               either(is(1)).or(is(2)).or(is(3)));
+        assertThat("Attestation version must be 1, 2, 3, or 4", attestation.getAttestationVersion(),
+               either(is(1)).or(is(2)).or(is(3)).or(is(4)));
 
         AuthorizationList teeEnforced = attestation.getTeeEnforced();
         AuthorizationList softwareEnforced = attestation.getSoftwareEnforced();
@@ -822,7 +823,8 @@
                 assertThat("TEE attestation can only come from TEE keymaster",
                         attestation.getKeymasterSecurityLevel(),
                         is(KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT));
-                assertThat(attestation.getKeymasterVersion(), either(is(2)).or(is(3)).or(is(4)));
+                assertThat(attestation.getKeymasterVersion(),
+                           either(is(2)).or(is(3)).or(is(4)).or(is(41)));
 
                 checkRootOfTrust(attestation, false /* requireLocked */);
                 assertThat(teeEnforced.getOsVersion(), is(systemOsVersion));
diff --git a/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4 b/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4
index b8dce17..ac70dd3 100755
--- a/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4
+++ b/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4
Binary files differ
diff --git a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
index ab22e7e..901623e 100644
--- a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
+++ b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
@@ -16,6 +16,8 @@
 
 package android.os.cts
 
+import android.app.Instrumentation
+import android.content.Context
 import android.content.Intent
 import android.content.Intent.ACTION_AUTO_REVOKE_PERMISSIONS
 import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
@@ -29,10 +31,10 @@
 import android.support.test.uiautomator.By
 import android.support.test.uiautomator.BySelector
 import android.support.test.uiautomator.UiObject2
-import android.test.InstrumentationTestCase
 import android.view.accessibility.AccessibilityNodeInfo
 import android.widget.Switch
-import com.android.compatibility.common.util.textAsString
+import androidx.test.InstrumentationRegistry
+import androidx.test.runner.AndroidJUnit4
 import com.android.compatibility.common.util.MatcherUtils.hasTextThat
 import com.android.compatibility.common.util.SystemUtil
 import com.android.compatibility.common.util.SystemUtil.runShellCommand
@@ -42,11 +44,19 @@
 import com.android.compatibility.common.util.click
 import com.android.compatibility.common.util.depthFirstSearch
 import com.android.compatibility.common.util.lowestCommonAncestor
+import com.android.compatibility.common.util.textAsString
 import com.android.compatibility.common.util.uiDump
 import org.hamcrest.CoreMatchers.containsString
 import org.hamcrest.CoreMatchers.containsStringIgnoringCase
+import org.hamcrest.CoreMatchers.equalTo
 import org.hamcrest.Matcher
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
 import org.junit.Assert.assertThat
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
 import java.lang.reflect.Modifier
 import java.util.concurrent.TimeUnit
 import java.util.concurrent.atomic.AtomicReference
@@ -61,7 +71,11 @@
 /**
  * Test for auto revoke
  */
-class AutoRevokeTest : InstrumentationTestCase() {
+@RunWith(AndroidJUnit4::class)
+class AutoRevokeTest {
+
+    private val context: Context = InstrumentationRegistry.getTargetContext()
+    private val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
 
     private val mPermissionControllerResources: Resources = context.createPackageContext(
             context.packageManager.permissionControllerPackageName, 0).resources
@@ -70,9 +84,27 @@
         const val LOG_TAG = "AutoRevokeTest"
     }
 
+    @Before
+    fun setup() {
+        // Kill Permission Controller
+        assertThat(
+                runShellCommand("killall " +
+                        context.packageManager.permissionControllerPackageName),
+                equalTo(""))
+
+        // Collapse notifications
+        assertThat(
+                runShellCommand("cmd statusbar collapse"),
+                equalTo(""))
+
+        // Wake up the device
+        runShellCommand("input keyevent KEYCODE_WAKEUP")
+        runShellCommand("input keyevent 82")
+    }
+
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testUnusedApp_getsPermissionRevoked() {
-        wakeUpScreen()
         withUnusedThresholdMs(3L) {
             withDummyApp {
                 // Setup
@@ -103,8 +135,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testUsedApp_doesntGetPermissionRevoked() {
-        wakeUpScreen()
         withUnusedThresholdMs(100_000L) {
             withDummyApp {
                 // Setup
@@ -127,8 +159,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testPreRUnusedApp_doesntGetPermissionRevoked() {
-        wakeUpScreen()
         withUnusedThresholdMs(3L) {
             withDummyApp(APK_PATH_2, APK_PACKAGE_NAME_2) {
                 withDummyApp {
@@ -168,8 +200,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testAutoRevoke_userWhitelisting() {
-        wakeUpScreen()
         withUnusedThresholdMs(4L) {
             withDummyApp {
                 // Setup
@@ -205,8 +237,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testInstallGrants_notRevokedImmediately() {
-        wakeUpScreen()
         withUnusedThresholdMs(TimeUnit.DAYS.toMillis(30)) {
             withDummyApp {
                 // Setup
@@ -231,6 +263,7 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testAutoRevoke_whitelistingApis() {
         withDummyApp {
             val pm = context.packageManager
@@ -258,11 +291,6 @@
         }
     }
 
-    private fun wakeUpScreen() {
-        runShellCommand("input keyevent KEYCODE_WAKEUP")
-        runShellCommand("input keyevent 82")
-    }
-
     private fun runAutoRevoke() {
         runShellCommand("cmd jobscheduler run -u 0 " +
                 "-f ${context.packageManager.permissionControllerPackageName} 2")
diff --git a/tests/tests/os/src/android/os/cts/TaggedPointerTest.java b/tests/tests/os/src/android/os/cts/TaggedPointerTest.java
index c4cee84..aabcb49 100644
--- a/tests/tests/os/src/android/os/cts/TaggedPointerTest.java
+++ b/tests/tests/os/src/android/os/cts/TaggedPointerTest.java
@@ -28,7 +28,9 @@
     }
 
     public void testHasTaggedPointer() {
-        if (!CpuFeatures.isArm64Cpu()) {
+        // Tagged pointers are only supported on arm64. But if CPU is native bridged then the host
+        // CPU is not arm64, so there is no tagged pointers support either.
+        if (!CpuFeatures.isArm64Cpu() || CpuFeatures.isNativeBridgedCpu()) {
             return;
         }
         assertTrue("Machine does not support tagged pointers", TaggedPointer.hasTaggedPointer());
diff --git a/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt b/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt
index ba9212b..d293c70 100644
--- a/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt
+++ b/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt
@@ -25,6 +25,7 @@
 import android.os.Process
 import android.support.test.uiautomator.By
 import android.support.test.uiautomator.UiDevice
+import android.support.test.uiautomator.UiObject2
 import android.support.test.uiautomator.UiObjectNotFoundException
 import androidx.test.platform.app.InstrumentationRegistry
 import com.android.compatibility.common.util.SystemUtil
@@ -34,6 +35,7 @@
 import org.junit.Assert
 import org.junit.Before
 import org.junit.Test
+import java.util.regex.Pattern
 
 /**
  * Tests that the permissioncontroller behaves normally when an app defines a permission in the
@@ -44,11 +46,12 @@
     private var mUiDevice: UiDevice? = null
     private var mContext: Context? = null
     private var mPm: PackageManager? = null
+    private var mAllowButtonText: Pattern? = null
 
     @Before
     fun install() {
         SystemUtil.runShellCommand("pm install -r " +
-                "$TEST_APP_DEFINES_UNDEFINED_PERMISSION_GROUP_ELEMENT_APK")
+                TEST_APP_DEFINES_UNDEFINED_PERMISSION_GROUP_ELEMENT_APK)
     }
 
     @Before
@@ -57,6 +60,14 @@
         mUiDevice = UiDevice.getInstance(mInstrumentation)
         mContext = mInstrumentation?.targetContext
         mPm = mContext?.packageManager
+        val permissionControllerResources = mContext?.createPackageContext(
+                mContext?.packageManager?.permissionControllerPackageName, 0)?.resources
+        mAllowButtonText = Pattern.compile(
+                Pattern.quote(requireNotNull(permissionControllerResources?.getString(
+                        permissionControllerResources.getIdentifier(
+                                "grant_dialog_button_allow", "string",
+                                "com.android.permissioncontroller")))),
+                Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE)
     }
 
     @Before
@@ -94,9 +105,7 @@
         eventually {
             startRequestActivity(arrayOf(TEST))
             mUiDevice!!.waitForIdle()
-            waitFindObject(By.res(
-                    "com.android.permissioncontroller:id/permission_allow_button"),
-                    100).click()
+            findAllowButton().click()
         }
         eventually {
             Assert.assertEquals(mPm!!.checkPermission(CAMERA, APP_PKG_NAME),
@@ -113,6 +122,17 @@
         SystemUtil.runShellCommand("pm uninstall $APP_PKG_NAME")
     }
 
+    fun findAllowButton(): UiObject2 {
+        return if (mContext?.packageManager
+                        ?.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) == true) {
+            waitFindObject(By.text(mAllowButtonText), 100)
+        } else {
+            waitFindObject(By.res(
+                    "com.android.permissioncontroller:id/permission_allow_button"),
+                    100)
+        }
+    }
+
     /**
      * If app has one permission granted, then it can't grant itself another permission for free.
      */
@@ -131,7 +151,12 @@
             startRequestActivity(arrayOf(targetPermission))
             mUiDevice!!.waitForIdle()
             try {
-                waitFindObject(By.res("com.android.permissioncontroller:id/grant_dialog"), 100)
+                if (mContext?.packageManager
+                                ?.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) == true) {
+                    findAllowButton()
+                } else {
+                    waitFindObject(By.res("com.android.permissioncontroller:id/grant_dialog"), 100)
+                }
             } catch (e: UiObjectNotFoundException) {
                 Assert.assertEquals("grant dialog never showed.",
                         mPm!!.checkPermission(targetPermission,
diff --git a/tests/tests/preference/src/android/preference/cts/TestUtils.java b/tests/tests/preference/src/android/preference/cts/TestUtils.java
index 30bd9fc..1992b95 100644
--- a/tests/tests/preference/src/android/preference/cts/TestUtils.java
+++ b/tests/tests/preference/src/android/preference/cts/TestUtils.java
@@ -16,6 +16,7 @@
 
 package android.preference.cts;
 
+import android.app.Activity;
 import android.app.Instrumentation;
 import android.app.UiAutomation;
 import android.app.UiModeManager;
@@ -31,8 +32,6 @@
 import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
 import android.util.DisplayMetrics;
-import android.view.Display;
-import android.view.Window;
 
 import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.rule.ActivityTestRule;
@@ -50,8 +49,7 @@
     private final UiAutomation mAutomation;
     private int mStatusBarHeight = -1;
     private int mNavigationBarHeight = -1;
-    private Display mDisplay;
-    private Window mWindow;
+    private ActivityTestRule<?> mRule;
 
     TestUtils(ActivityTestRule<?> rule) {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -59,8 +57,7 @@
         mPackageName = mContext.getPackageName();
         mDevice = UiDevice.getInstance(mInstrumentation);
         mAutomation = mInstrumentation.getUiAutomation();
-        mDisplay = rule.getActivity().getDisplay();
-        mWindow = rule.getActivity().getWindow();
+        mRule = rule;
     }
 
     void waitForIdle() {
@@ -165,9 +162,10 @@
 
     private boolean hasVerticalNavBar() {
         Rect displayFrame = new Rect();
-        mWindow.getDecorView().getWindowVisibleDisplayFrame(displayFrame);
+        final Activity activity = mRule.getActivity();
+        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(displayFrame);
         DisplayMetrics dm = new DisplayMetrics();
-        mDisplay.getRealMetrics(dm);
+        activity.getDisplay().getRealMetrics(dm);
         return dm.heightPixels == displayFrame.bottom;
     }
 
diff --git a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
index 9d3755a..c3c2cad 100644
--- a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
@@ -69,6 +69,7 @@
 
     private Context mContext;
     private boolean mHasTouchScreen;
+    private boolean mHasBluetooth;
 
     private UiDevice mDevice;
 
@@ -81,6 +82,7 @@
 
         mHasTouchScreen = packageManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
                 || packageManager.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH);
+        mHasBluetooth = packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
 
         Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
         launcherIntent.addCategory(Intent.CATEGORY_HOME);
@@ -133,6 +135,7 @@
     @Test
     public void mediaOutputPanel_withPackageNameExtra_correctPackage() {
         assumeTrue(mHasTouchScreen);
+        assumeTrue(mHasBluetooth);
         launchMediaOutputPanel(TEST_PACKAGE_NAME);
 
         String currentPackage = mDevice.getCurrentPackageName();
@@ -143,6 +146,7 @@
     @Test
     public void mediaOutputPanel_noPutPackageNameExtra_correctPackage() {
         assumeTrue(mHasTouchScreen);
+        assumeTrue(mHasBluetooth);
         launchMediaOutputPanel(null /* packageName */);
 
         String currentPackage = mDevice.getCurrentPackageName();
@@ -162,6 +166,7 @@
     @Test
     public void mediaOutputPanel_correctTitle() {
         assumeTrue(mHasTouchScreen);
+        assumeTrue(mHasBluetooth);
         launchMediaOutputPanel(TEST_PACKAGE_NAME);
 
         final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_HEADER));
@@ -232,6 +237,7 @@
     @Test
     public void mediaOutputPanel_doneClosesPanel() {
         assumeTrue(mHasTouchScreen);
+        assumeTrue(mHasBluetooth);
         // Launch panel
         launchMediaOutputPanel(TEST_PACKAGE_NAME);
         String currentPackage = mDevice.getCurrentPackageName();
@@ -322,6 +328,7 @@
     @Test
     public void mediaOutputPanel_seeMoreButton_doNothing() {
         assumeTrue(mHasTouchScreen);
+        assumeTrue(mHasBluetooth);
         // Launch panel
         launchMediaOutputPanel(TEST_PACKAGE_NAME);
         String currentPackage = mDevice.getCurrentPackageName();
diff --git a/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp b/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp
index 7229574..824cb50 100644
--- a/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp
+++ b/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp
@@ -46,14 +46,17 @@
 }
 
 #ifdef __arm__
-// For ARM32, assemble the 'aese.8' instruction as a .word, since otherwise
+// For ARM32, assemble the 'aese.8' instruction as an .inst, since otherwise
 // clang does not accept it.  It would be allowed in a separate file compiled
-// with -march=armv8, but this way is much easier.  And it's not yet possible to
-// use a target function attribute, because clang doesn't yet support
-// target("fpu=crypto-neon-fp-armv8") like gcc does.
-static void executeAESInstruction(void) {
+// with -march=armv8+crypto, but this way is much easier.  And it's not yet
+// possible to use a target function attribute, because clang doesn't yet
+// support target("fpu=crypto-neon-fp-armv8") like gcc does.
+//
+// We use the ARM encoding of the instruction, not the Thumb encoding.  So make
+// sure to use target("arm") to mark the function as containing ARM code.
+static void __attribute__((target("arm"))) executeAESInstruction(void) {
     // aese.8  q0, q1
-    asm volatile(".word  0xf3b00302" : : : "q0");
+    asm volatile(".inst  0xf3b00302" : : : "q0");
 }
 #elif defined(__aarch64__)
 static void __attribute__((target("crypto"))) executeAESInstruction(void) {
diff --git a/tests/tests/security/src/android/security/cts/MotionEventTest.java b/tests/tests/security/src/android/security/cts/MotionEventTest.java
index 0e39863..f7d3edc 100644
--- a/tests/tests/security/src/android/security/cts/MotionEventTest.java
+++ b/tests/tests/security/src/android/security/cts/MotionEventTest.java
@@ -129,19 +129,21 @@
         WidgetTestUtils.runOnMainAndLayoutSync(mActivityRule, view, null /*runnable*/,
                 true /*forceLayout*/);
 
-	// This ensures the window is visible, where the code above ensures
+        // This ensures the window is visible, where the code above ensures
         // the view is on screen.
         mActivityRule.runOnUiThread(() -> {
             // This will force WindowManager to relayout, ensuring the
-	    // transaction to show the window are sent to the graphics code.
+            // transaction to show the window are sent to the graphics code.
             wm.updateViewLayout(view, wmlp);
         });
 
+        // Find the position inside the main activity and outside of the overlays.
         FutureTask<Point> clickLocationTask = new FutureTask<>(() -> {
             final int[] viewLocation = new int[2];
-            view.getLocationOnScreen(viewLocation);
+            final View decorView = mActivity.getWindow().getDecorView();
+            decorView.getLocationOnScreen(viewLocation);
             // Set y position to the center of the view, to make sure it is away from the status bar
-            return new Point(viewLocation[0], viewLocation[1] + view.getHeight() / 2);
+            return new Point(viewLocation[0], viewLocation[1] + decorView.getHeight() / 2);
         });
         mActivity.runOnUiThread(clickLocationTask);
         Point viewLocation = clickLocationTask.get(5, TimeUnit.SECONDS);
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
index b9138b2..2d63f71 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
@@ -67,7 +67,11 @@
     private TelephonyManager mTelephonyManager;
     private SubscriptionManager mSubscriptionManager;
     private PackageManager mPackageManager;
-    private static final int TOLERANCE = 2000;
+
+    // Use a long timeout to accommodate devices with lower amounts of memory, as it will take
+    // longer for these devices to receive the broadcast (b/161963269). It is expected that all
+    // devices can receive the broadcast in under 5s (most should receive it well before then).
+    private static final int BROADCAST_TIMEOUT_MILLIS = 5000;
     private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);
 
     @Before
@@ -290,9 +294,10 @@
 
         try {
             t.start();
-            boolean didCarrierNameUpdate = COUNT_DOWN_LATCH.await(TOLERANCE, TimeUnit.MILLISECONDS);
+            boolean didCarrierNameUpdate =
+                    COUNT_DOWN_LATCH.await(BROADCAST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
             if (!didCarrierNameUpdate) {
-                fail("CarrierName not overridden in " + TOLERANCE + " ms");
+                fail("CarrierName not overridden in " + BROADCAST_TIMEOUT_MILLIS + " ms");
             }
         } finally {
             mConfigManager.overrideConfig(subId, null);
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/IwlanModeTest.java b/tests/tests/telephony/current/src/android/telephony/cts/IwlanModeTest.java
index 38c80b8..a68ebb5 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/IwlanModeTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/IwlanModeTest.java
@@ -59,13 +59,10 @@
             int id = res.getIdentifier("config_wlan_data_service_package", "string", "android");
             String wlanDataServicePackage = res.getString(id);
             assertNotEquals("", wlanDataServicePackage);
-            assertNotEquals("com.android.phone", wlanDataServicePackage);
 
             id = res.getIdentifier("config_wlan_network_service_package", "string", "android");
             String wlanNetworkServicePackage = res.getString(id);
             assertNotEquals("", wlanNetworkServicePackage);
-            assertNotEquals("com.android.phone", wlanNetworkServicePackage);
-
         }
     }
 }
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 92dd117..174af37 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -39,16 +39,19 @@
 import android.net.Network;
 import android.net.NetworkCapabilities;
 import android.net.NetworkRequest;
+import android.os.Looper;
 import android.os.ParcelUuid;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.SubscriptionPlan;
 import android.telephony.TelephonyManager;
+import android.util.Log;
 
 import androidx.test.InstrumentationRegistry;
 
 import com.android.compatibility.common.util.ShellIdentityUtils;
 import com.android.compatibility.common.util.SystemUtil;
+import com.android.compatibility.common.util.TestThread;
 import com.android.internal.util.ArrayUtils;
 
 import org.junit.AfterClass;
@@ -66,12 +69,14 @@
 import java.util.concurrent.Executor;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Consumer;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
 
 public class SubscriptionManagerTest {
+    private static final String TAG = "SubscriptionManagerTest";
     private SubscriptionManager mSm;
 
     private int mSubId;
@@ -685,12 +690,80 @@
         if (!isSupported()) return;
         boolean enabled = executeWithShellPermissionAndDefault(false, mSm,
                 (sm) -> sm.isSubscriptionEnabled(mSubId));
-        // Enable or disable subscription may require users UX confirmation or may not be supported.
-        // Call APIs to make sure there's no crash.
-        executeWithShellPermissionAndDefault(false, mSm,
-                (sm) -> sm.setSubscriptionEnabled(mSubId, !enabled));
-        executeWithShellPermissionAndDefault(false, mSm,
-                (sm) -> sm.setSubscriptionEnabled(mSubId, enabled));
+
+        AtomicBoolean waitForIsEnabledValue = new AtomicBoolean(!enabled);
+        // wait for the first call to take effect
+        Object lock = new Object();
+        AtomicBoolean setSubscriptionEnabledCallCompleted = new AtomicBoolean(false);
+        TestThread t = new TestThread(new Runnable() {
+            @Override
+            public void run() {
+                Looper.prepare();
+
+                SubscriptionManager.OnSubscriptionsChangedListener listener =
+                        new SubscriptionManager.OnSubscriptionsChangedListener() {
+                            @Override
+                            public void onSubscriptionsChanged() {
+                                boolean waitForValue = waitForIsEnabledValue.get();
+                                if (executeWithShellPermissionAndDefault(!waitForValue, mSm,
+                                        (sm) -> sm.isSubscriptionEnabled(mSubId)) == waitForValue) {
+                                    synchronized (lock) {
+                                        setSubscriptionEnabledCallCompleted.set(true);
+                                        lock.notifyAll();
+                                    }
+                                }
+                            }
+                        };
+                mSm.addOnSubscriptionsChangedListener(listener);
+
+                Looper.loop();
+            }
+        });
+
+        try {
+            t.start();
+            // Enable or disable subscription may require users UX confirmation or may not be
+            // supported. Call APIs to make sure there's no crash.
+            executeWithShellPermissionAndDefault(false, mSm,
+                    (sm) -> sm.setSubscriptionEnabled(mSubId, !enabled));
+
+            synchronized (lock) {
+                if (!setSubscriptionEnabledCallCompleted.get()) {
+                    lock.wait(5000);
+                }
+            }
+            if (!setSubscriptionEnabledCallCompleted.get()) {
+                // not treating this as test failure as it may be due to UX confirmation or may not
+                // be supported
+                Log.e(TAG, "setSubscriptionEnabled() did not complete");
+                return;
+            }
+
+            // switch back to the original value
+            waitForIsEnabledValue.set(enabled);
+            setSubscriptionEnabledCallCompleted.set(false);
+            executeWithShellPermissionAndDefault(false, mSm,
+                    (sm) -> sm.setSubscriptionEnabled(mSubId, enabled));
+
+            // wait to make sure device is left in the same state after the test as it was before
+            // the test
+            synchronized (lock) {
+                if (!setSubscriptionEnabledCallCompleted.get()) {
+                    // longer wait time on purpose as re-enabling can take a longer time
+                    lock.wait(50000);
+                }
+            }
+            if (!setSubscriptionEnabledCallCompleted.get()) {
+                // treat this as failure because it worked the first time
+                fail("setSubscriptionEnabled() did not work second time");
+            }
+        } catch (InterruptedException e) {
+            fail("InterruptedException");
+        }
+
+        // Reset default data subId as it may have been changed as part of the calls above
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mSm,
+                (sm) -> sm.setDefaultDataSubId(mSubId));
     }
 
     @Test
diff --git a/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java b/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java
index 67d5de4..b0ec086 100644
--- a/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java
@@ -139,27 +139,33 @@
 
     // If resampling happened, the coordinates and event time would resample to new position.
     private static void compareEvent(final MotionEvent sentEvent,
-            final ReceivedEvent receivedEvent) {
+            final ReceivedEvent receivedEvent, final int[] offsets) {
         assertEquals(sentEvent.getAction(), receivedEvent.mAction);
-        assertEquals((int) sentEvent.getX(), receivedEvent.mX, 0);
+        assertEquals((int) sentEvent.getX(), receivedEvent.mX + offsets[0]);
+        assertEquals((int) sentEvent.getY(), receivedEvent.mY + offsets[1]);
         assertEquals(sentEvent.getEventTime(), receivedEvent.mEventTime);
         assertEquals(sentEvent.getSource(), receivedEvent.mSource);
     }
 
     private void compareEvents(final BlockingQueue<MotionEvent> sentEvents,
-            final BlockingQueue<ReceivedEvent> receivedEvents) {
+            final BlockingQueue<ReceivedEvent> receivedEvents, final int[] offsets) {
         assertEquals(sentEvents.size(), receivedEvents.size());
 
         for (int i = 0; i < sentEvents.size(); i++) {
             MotionEvent sentEvent = sentEvents.poll();
             ReceivedEvent receivedEvent = receivedEvents.poll();
-            compareEvent(sentEvent, receivedEvent);
+            compareEvent(sentEvent, receivedEvent, offsets);
         }
     }
 
-    private Point getViewCenterOnScreen(View view) {
+    private int[] getViewLocationOnScreen(View view) {
         final int[] xy = new int[2];
         view.getLocationOnScreen(xy);
+        return xy;
+    }
+
+    private Point getViewCenterOnScreen(View view) {
+        final int[] xy = getViewLocationOnScreen(view);
         final int viewWidth = view.getWidth();
         final int viewHeight = view.getHeight();
 
@@ -276,7 +282,7 @@
                 InputDevice.SOURCE_TOUCHSCREEN);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, getViewLocationOnScreen(mView));
     }
 
     // Test view requested touch screen unbuffered from MotionEvent.
@@ -295,7 +301,7 @@
                 InputDevice.SOURCE_TOUCHSCREEN);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, getViewLocationOnScreen(mView));
     }
 
     // Test view requested unbuffered source but reset it later.
@@ -330,7 +336,7 @@
         sendJoystickEvents(0, 0);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, new int[]{0, 0});
     }
 
     // Test view requested joystick unbuffered but no focus.
@@ -362,7 +368,7 @@
                 InputDevice.SOURCE_TOUCHSCREEN);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, getViewLocationOnScreen(mView));
     }
 
     // Test view requested different source unbuffered from the received events.
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
index 596a8c0..6844352 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
@@ -817,8 +817,9 @@
             int securityType = softApConfig.getSecurityType();
             if (securityType == SoftApConfiguration.SECURITY_TYPE_OPEN
                 || securityType == SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) {
-                 assertNotNull(softApConfig.toWifiConfiguration());
-            } else {
+                // TODO: b/165504232, add WPA3_SAE_TRANSITION assert check
+                assertNotNull(softApConfig.toWifiConfiguration());
+            } else if (securityType == SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) {
                 assertNull(softApConfig.toWifiConfiguration());
             }
             if (!hasAutomotiveFeature()) {