Merge "Remove flaky annotation"
diff --git a/apps/CameraITS/pymodules/its/device.py b/apps/CameraITS/pymodules/its/device.py
index 24fae6d..bc1d3a6 100644
--- a/apps/CameraITS/pymodules/its/device.py
+++ b/apps/CameraITS/pymodules/its/device.py
@@ -27,6 +27,7 @@
 
 from collections import namedtuple
 
+
 class ItsSession(object):
     """Controls a device over adb to run ITS scripts.
 
@@ -1108,7 +1109,7 @@
     return device_bfp
 
 def parse_camera_ids(ids):
-    """ Parse the string of camera IDs into array of CameraIdCombo tuples.
+    """Parse the string of camera IDs into array of CameraIdCombo tuples.
     """
     CameraIdCombo = namedtuple('CameraIdCombo', ['id', 'sub_id'])
     id_combos = []
@@ -1122,6 +1123,35 @@
             assert(False), 'Camera id parameters must be either ID, or ID:SUB_ID'
     return id_combos
 
+
+def get_build_sdk_version(device_id=None):
+    """Get the build version of the device."""
+    if not device_id:
+        device_id = get_device_id()
+    cmd = 'adb -s %s shell getprop ro.build.version.sdk' % device_id
+    try:
+        build_sdk_version = int(subprocess.check_output(cmd.split()).rstrip())
+        print 'Build SDK version: %d' % build_sdk_version
+    except (subprocess.CalledProcessError, ValueError):
+        print 'No build_sdk_version.'
+        assert 0
+    return build_sdk_version
+
+
+def get_first_api_level(device_id=None):
+    """Get the first API level for device."""
+    if not device_id:
+        device_id = get_device_id()
+    cmd = 'adb -s %s shell getprop ro.product.first_api_level' % device_id
+    try:
+        first_api_level = int(subprocess.check_output(cmd.split()).rstrip())
+        print 'First API level: %d' % first_api_level
+    except (subprocess.CalledProcessError, ValueError):
+        print 'No first_api_level. Setting to build version.'
+        first_api_level = get_build_sdk_version(device_id)
+    return first_api_level
+
+
 def _run(cmd):
     """Replacement for os.system, with hiding of stdout+stderr messages.
     """
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index a9d7601..c5c8077 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -40,6 +40,7 @@
 CHART_SCALE_STOP = 1.35
 CHART_SCALE_STEP = 0.025
 FACING_EXTERNAL = 2
+NOT_YET_MANDATED_ALL = 100
 NUM_TRYS = 2
 PROC_TIMEOUT_CODE = -101  # terminated process return -process_id
 PROC_TIMEOUT_TIME = 900  # timeout in seconds for a process (15 minutes)
@@ -89,19 +90,20 @@
         'scene5': ['doAF=False']
 }
 
-# Not yet mandated tests
+# Not yet mandated tests ['test', first_api_level mandatory]
+# ie. ['test_test_patterns', 28] is MANDATED for first_api_level >= 28
 NOT_YET_MANDATED = {
         'scene0': [
-                'test_test_patterns',
-                'test_tonemap_curve'
+                ['test_test_patterns', 28],
+                ['test_tonemap_curve', 28]
         ],
         'scene1_1': [
-                'test_ae_precapture_trigger',
-                'test_channel_saturation'
+                ['test_ae_precapture_trigger', 28],
+                ['test_channel_saturation', 29]
         ],
         'scene1_2': [],
         'scene2_a': [
-                'test_auto_per_frame_control'
+                ['test_auto_per_frame_control', NOT_YET_MANDATED_ALL]
         ],
         'scene2_b': [],
         'scene2_c': [],
@@ -165,8 +167,34 @@
 }
 
 
+def determine_not_yet_mandated_tests(device_id):
+    """Determine from NEW_YET_MANDATED & phone info not_yet_mandated tests.
+
+    Args:
+        device_id:      string of device id number
+
+    Returns:
+        dict of not yet mandated tests
+    """
+    # initialize not_yet_mandated
+    not_yet_mandated = {}
+    for scene in ALL_SCENES:
+        not_yet_mandated[scene] = []
+
+    # Determine first API level for device
+    first_api_level = its.device.get_first_api_level(device_id)
+
+    # Determine which scenes are not yet mandated for first api level
+    for scene, tests in NOT_YET_MANDATED.items():
+        for test in tests:
+            if test[1] >= first_api_level:
+                not_yet_mandated[scene].append(test[0])
+    return not_yet_mandated
+
+
 def expand_scene(scene, scenes):
     """Expand a grouped scene and append its sub_scenes to scenes.
+
     Args:
         scene:      scene in GROUPED_SCENES dict
         scenes:     list of scenes to append to
@@ -470,6 +498,7 @@
 
         tot_tests = []
         tot_pass = 0
+        not_yet_mandated = determine_not_yet_mandated_tests(device_id)
         for scene in scenes:
             skip_code = None
             tests = [(s[:-3], os.path.join('tests', scene, s))
@@ -595,7 +624,7 @@
                 elif test_code == SKIP_RET_CODE:
                     retstr = "SKIP "
                     numskip += 1
-                elif test_code != 0 and testname in NOT_YET_MANDATED[scene]:
+                elif test_code != 0 and testname in not_yet_mandated[scene]:
                     retstr = "FAIL*"
                     num_not_mandated_fail += 1
                 else:
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 74c7c80..d752ab6 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -2118,7 +2118,7 @@
 
             <meta-data android:name="test_category" android:value="@string/test_category_notifications" />
             <meta-data android:name="test_excluded_features"
-                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
+                       android:value="android.hardware.type.automotive:android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
         </activity>
 
         <activity android:name=".notifications.AttentionManagementVerifierActivity"
diff --git a/apps/CtsVerifier/proguard.flags b/apps/CtsVerifier/proguard.flags
index 85f378e..a05d149 100644
--- a/apps/CtsVerifier/proguard.flags
+++ b/apps/CtsVerifier/proguard.flags
@@ -19,7 +19,7 @@
 }
 
 # ensure we keep public camera test methods, these are needed at runtime
--keepclassmembers class * extends android.hardware.camera2.cts.testcases.Camera2AndroidTestCase {
+-keepclassmembers class * extends android.hardware.camera2.cts.testcases.Camera2AndroidBasicTestCase {
     public <methods>;
 }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
index f2be547..e89fc94 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
@@ -548,12 +548,12 @@
 
         public void run() {
             Log.i(TAG, "BEGIN mConnectedThread");
-            byte[] buffer = new byte[1024];
             int bytes;
 
             // Keep listening to the InputStream while connected
             while (true) {
                 try {
+                    byte[] buffer = new byte[1024];
                     // Read from the InputStream
                     bytes = mmInStream.read(buffer);
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/performance/CameraPerformanceActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/performance/CameraPerformanceActivity.java
index 5510521..59b7a03 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/performance/CameraPerformanceActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/performance/CameraPerformanceActivity.java
@@ -21,7 +21,7 @@
 import android.app.ProgressDialog;
 import android.content.Context;
 import android.hardware.camera2.cts.PerformanceTest;
-import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
+import android.hardware.camera2.cts.testcases.Camera2AndroidBasicTestCase;
 import android.hardware.cts.CameraTestCase;
 import android.hardware.cts.LegacyCameraPerformanceTest;
 import android.os.Bundle;
@@ -201,8 +201,8 @@
                 Enumeration<Test> tests = ((TestSuite) s).tests();
                 while (tests.hasMoreElements()) {
                     Test test = tests.nextElement();
-                    if (test instanceof Camera2AndroidTestCase) {
-                        Camera2AndroidTestCase testCase = (Camera2AndroidTestCase) test;
+                    if (test instanceof Camera2AndroidBasicTestCase) {
+                        Camera2AndroidBasicTestCase testCase = (Camera2AndroidBasicTestCase) test;
 
                         // The base case class has one internal test that can
                         // be ignored for the purpose of this test activity.
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
index 2a37b5e..7297dbe 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
@@ -42,6 +42,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.provider.Settings;
 import android.provider.Settings.Secure;
@@ -128,8 +129,10 @@
             tests.add(new EnableHintsTest());
             tests.add(new ReceiveAppBlockNoticeTest());
             tests.add(new ReceiveAppUnblockNoticeTest());
-            tests.add(new ReceiveChannelBlockNoticeTest());
-            tests.add(new ReceiveGroupBlockNoticeTest());
+            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+                tests.add(new ReceiveChannelBlockNoticeTest());
+                tests.add(new ReceiveGroupBlockNoticeTest());
+            }
             tests.add(new RequestUnbindTest());
             tests.add(new RequestBindTest());
             tests.add(new MessageBundleTest());
diff --git a/tests/backup/app/permission22/Android.mk b/apps/MainlineModuleDetector/Android.mk
similarity index 71%
copy from tests/backup/app/permission22/Android.mk
copy to apps/MainlineModuleDetector/Android.mk
index 8790e19..b99f8f7 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/apps/MainlineModuleDetector/Android.mk
@@ -1,4 +1,5 @@
-# Copyright (C) 2019 The Android Open Source Project
+#
+# Copyright (C) 2018 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -11,21 +12,21 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+#
 
 LOCAL_PATH:= $(call my-dir)
-
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
+LOCAL_PACKAGE_NAME := MainlineModuleDetector
+
 LOCAL_SDK_VERSION := current
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts sts
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+include $(BUILD_CTS_PACKAGE)
diff --git a/apps/MainlineModuleDetector/AndroidManifest.xml b/apps/MainlineModuleDetector/AndroidManifest.xml
new file mode 100644
index 0000000..9a36cc6
--- /dev/null
+++ b/apps/MainlineModuleDetector/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.cts.mainlinemoduledetector"
+          android:versionCode="1"
+          android:versionName="1.0">
+
+    <application>
+        <activity android:name=".MainlineModuleDetector">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/apps/MainlineModuleDetector/OWNERS b/apps/MainlineModuleDetector/OWNERS
new file mode 100644
index 0000000..8f076a8
--- /dev/null
+++ b/apps/MainlineModuleDetector/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 195645
+manjaepark@google.com
+mspector@google.com
\ No newline at end of file
diff --git a/apps/MainlineModuleDetector/src/com/android/cts/mainlinemoduledetector/MainlineModuleDetector.java b/apps/MainlineModuleDetector/src/com/android/cts/mainlinemoduledetector/MainlineModuleDetector.java
new file mode 100644
index 0000000..5e473d6
--- /dev/null
+++ b/apps/MainlineModuleDetector/src/com/android/cts/mainlinemoduledetector/MainlineModuleDetector.java
@@ -0,0 +1,158 @@
+package com.android.cts.mainlinemoduledetector;
+
+import android.app.Activity;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.util.Log;
+
+import java.security.MessageDigest;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Set;
+
+public class MainlineModuleDetector extends Activity {
+
+    private static final String LOG_TAG = "MainlineModuleDetector";
+
+    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
+
+    enum ModuleType {
+        APEX,
+        APK
+    }
+
+    enum MainlineModule {
+        // Security
+        MEDIA_SOFTWARE_CODEC("com.google.android.media.swcodec",
+                true, ModuleType.APEX,
+                "0C:2B:13:87:6D:E5:6A:E6:4E:D1:DE:93:42:2A:8A:3F:EA:6F:34:C0:FC:5D:7D:A1:BD:CF:EF"
+                        + ":C1:A7:B7:C9:1D"),
+        MEDIA("com.google.android.media",
+                true, ModuleType.APEX,
+                "16:C1:5C:FA:15:D0:FD:D0:7E:BE:CB:5A:76:6B:40:8B:05:DD:92:7E:1F:3A:DD:C5:AB:F6:8E"
+                        + ":E8:B9:98:F9:FD"),
+        DNS_RESOLVER("com.google.android.resolv",
+                true, ModuleType.APEX,
+                "EC:82:21:76:5E:4F:7E:2C:6D:8D:0F:0C:E9:BD:82:5B:98:BE:D2:0C:07:2C:C6:C8:08:DD:E4"
+                        + ":68:5F:EB:A6:FF"),
+        CONSCRYPT("com.google.android.conscrypt",
+                true, ModuleType.APEX,
+                "8C:5D:A9:10:E6:11:21:B9:D6:E0:3B:42:D3:20:6A:7D:AD:29:DD:C1:63:AE:CD:4B:8E:E9:3F"
+                        + ":D3:83:79:CA:2A"),
+        // Privacy
+        PERMISSION_CONTROLLER("com.google.android.permissioncontroller",
+                false, ModuleType.APK,
+                "89:DF:B5:04:7E:E0:19:29:C2:18:4D:68:EF:49:64:F2:A9:0A:F1:24:C3:23:38:28:B8:F6:40"
+                        + ":D9:E6:C0:0F:83"),
+        ANDROID_SERVICES("com.google.android.ext.services",
+                false, ModuleType.APK,
+                "18:46:05:09:5B:E6:CA:22:D0:55:F3:4E:FA:F0:13:44:FD:3A:B3:B5:63:8C:30:62:76:10:EE"
+                        + ":AE:8A:26:0B:29"),
+        DOCUMENTS_UI("com.google.android.documentsui",
+                true, ModuleType.APK,
+                "9A:4B:85:34:44:86:EC:F5:1F:F8:05:EB:9D:23:17:97:79:BE:B7:EC:81:91:93:5A:CA:67:F0"
+                        + ":F4:09:02:52:97"),
+        // Consistency
+        TZDATA("com.google.android.tzdata",
+                true, ModuleType.APEX,
+                "55:93:DD:78:CB:26:EC:9B:00:59:2A:6A:F5:94:E4:16:1F:FD:B5:E9:F3:71:A7:43:54:5F:93"
+                        + ":F2:A0:F6:53:89"),
+        NETWORK_STACK("com.google.android.networkstack",
+                true, ModuleType.APK,
+                "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
+                        + ":F6:0B:F6:2C:1E"),
+        CAPTIVE_PORTAL_LOGIN("com.google.android.captiveportallogin",
+                true, ModuleType.APK,
+                "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
+                        + ":F6:0B:F6:2C:1E"),
+        NETWORK_PERMISSION_CONFIGURATION("com.google.android.networkstack.permissionconfig",
+                true, ModuleType.APK,
+                "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
+                        + ":F6:0B:F6:2C:1E"),
+        MODULE_METADATA("com.google.android.modulemetadata",
+                true, ModuleType.APK,
+                "BF:62:23:1E:28:F0:85:42:75:5C:F3:3C:9D:D8:3C:5D:1D:0F:A3:20:64:50:EF:BC:4C:3F:F3"
+                        + ":D5:FD:A0:33:0F"),
+        ;
+
+        String packageName;
+        boolean isPlayUpdated;
+        ModuleType moduleType;
+        String certSHA256;
+
+        MainlineModule(String packageName, boolean isPlayUpdated, ModuleType moduleType,
+                String certSHA256) {
+            this.packageName = packageName;
+            this.isPlayUpdated = isPlayUpdated;
+            this.moduleType = moduleType;
+            this.certSHA256 = certSHA256;
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        try {
+            String modules = String.join(",", getPlayManagedModules());
+            Log.i(LOG_TAG, "Play managed modules are: <" + modules + ">");
+        } catch (Exception e) {
+            Log.e(LOG_TAG, "Failed to retrieve modules.", e);
+        }
+        this.finish();
+    }
+
+    private Set<String> getPlayManagedModules() throws Exception {
+        Set<String> playManagedModules = new HashSet<>();
+
+        PackageManager pm = getApplicationContext().getPackageManager();
+
+        Set<String> packages = new HashSet<>();
+        for (PackageInfo info : pm.getInstalledPackages(0)) {
+            packages.add(info.packageName);
+        }
+        for (PackageInfo info : pm.getInstalledPackages(PackageManager.MATCH_APEX)) {
+            packages.add(info.packageName);
+        }
+
+        for (MainlineModule module : EnumSet.allOf(MainlineModule.class)) {
+            if (module.isPlayUpdated && packages.contains(module.packageName)
+                    && module.certSHA256.equals(getSignatureDigest(module))) {
+                playManagedModules.add(module.packageName);
+            }
+        }
+        return playManagedModules;
+    }
+
+    private String getSignatureDigest(MainlineModule module) throws Exception {
+        PackageManager pm = getApplicationContext().getPackageManager();
+        int flag = PackageManager.GET_SIGNING_CERTIFICATES;
+        if (module.moduleType == ModuleType.APEX) {
+            flag |= PackageManager.MATCH_APEX;
+        }
+
+        PackageInfo packageInfo = pm.getPackageInfo(module.packageName, flag);
+        MessageDigest messageDigest = MessageDigest.getInstance("SHA256");
+        messageDigest.update(packageInfo.signingInfo.getApkContentsSigners()[0].toByteArray());
+
+        final byte[] digest = messageDigest.digest();
+        final int digestLength = digest.length;
+        final int charCount = 3 * digestLength - 1;
+
+        final char[] chars = new char[charCount];
+        for (int i = 0; i < digestLength; i++) {
+            final int byteHex = digest[i] & 0xFF;
+            chars[i * 3] = HEX_ARRAY[byteHex >>> 4];
+            chars[i * 3 + 1] = HEX_ARRAY[byteHex & 0x0F];
+            if (i < digestLength - 1) {
+                chars[i * 3 + 2] = ':';
+            }
+        }
+
+        String ret = new String(chars);
+        Log.d(LOG_TAG, "Module: " + module.packageName + " has signature: " + ret);
+        return ret;
+    }
+
+}
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/FileUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/FileUtils.java
index 5530ff3..b628bce 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/FileUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/FileUtils.java
@@ -53,6 +53,15 @@
     public static final int S_IWOTH = 00002;
     public static final int S_IXOTH = 00001;
 
+    static {
+        try {
+            // Required only for the native methods.
+            System.loadLibrary("cts_jni");
+        } catch (UnsatisfiedLinkError e) {
+            System.out.println("JNI not loaded");
+        }
+    }
+
     public static class FileStatus {
 
         public int dev;
@@ -89,13 +98,18 @@
      * @param status object to set the fields on
      * @param statLinks or don't stat links (lstat vs stat)
      * @return whether or not we were able to stat the file
+     *
+     * If you call this method, make sure to link in the libcts_jni library.
      */
     public native static boolean getFileStatus(String path, FileStatus status, boolean statLinks);
 
+    /** If you call this method, make sure to link in the libcts_jni library. */
     public native static String getUserName(int uid);
 
+    /** If you call this method, make sure to link in the libcts_jni library. */
     public native static String getGroupName(int gid);
 
+    /** If you call this method, make sure to link in the libcts_jni library. */
     public native static int setPermissions(String file, int mode);
 
     /**
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
index 3e9e2df..19e1215 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
@@ -314,16 +314,16 @@
             return false;
         }
 
-	if (rate == 0.0) {
+        if (rate == 0.0) {
             return true;
-	}
+        }
 
         // before Q, we always said yes once we found a decoder for the format.
         if (ApiLevelUtil.isBefore(Build.VERSION_CODES.Q)) {
             return true;
-	}
+        }
 
-	// we care about speed of decoding
+        // we care about speed of decoding
         Log.d(TAG, "checking for decoding " + format + " at " +
                    rate + " fps with " + decoder);
 
@@ -353,7 +353,9 @@
             return false;
         }
 
-        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.Q) && mci.isHardwareAccelerated()) {
+        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.Q)
+                && PropertyUtil.isVendorApiLevelAtLeast(Build.VERSION_CODES.Q)
+                && mci.isHardwareAccelerated()) {
             MediaCodecInfo.VideoCapabilities caps =
                             mci.getCapabilitiesForType(mime).getVideoCapabilities();
             List<MediaCodecInfo.VideoCapabilities.PerformancePoint> pp =
@@ -369,7 +371,7 @@
             }
             Log.i(TAG, "NOT covered by any hardware performance point");
             return false;
-	} else {
+        } else {
             String verified = MediaPerfUtils.areAchievableFrameRates(
                               decoder, mime, width, height, rate);
             if (verified == null) {
@@ -378,7 +380,7 @@
             }
             Log.d(TAG, "achieveable framerates says: " + verified);
             return false;
-	}
+        }
     }
 
     public static boolean supports(String codecName, String mime, int w, int h) {
@@ -631,7 +633,7 @@
 
     // checks format, does not address actual speed of decoding
     public static boolean canDecodeVideo(String mime, int width, int height, float rate) {
-	return canDecodeVideo(mime, width, height, rate, (float)0.0);
+        return canDecodeVideo(mime, width, height, rate, (float)0.0);
     }
 
     // format + decode rate
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java
index 28d8f0d..728cbc6 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java
@@ -97,12 +97,18 @@
         }
     }
 
-    /** Returns the version code for the package name, or null if the package can't be found */
+    /**
+     * Returns the version code for the package name, or null if the package can't be found.
+     * If before API Level 28, return a long version of the (otherwise deprecated) versionCode.
+     */
     public static Long getLongVersionCode(String packageName) {
         try {
             PackageInfo info = getPackageManager().getPackageInfo(packageName,
                     PackageManager.GET_META_DATA);
-            return info.getLongVersionCode();
+            // Make no assumptions about the device's API level, and use the (now deprecated)
+            // versionCode for older devices.
+            return (ApiLevelUtil.isAtLeast(28)) ?
+                    info.getLongVersionCode() : (long) info.versionCode;
         } catch (PackageManager.NameNotFoundException | NullPointerException e) {
             Log.w(TAG, "Could not find version string for package " + packageName);
             return null;
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 b87e88b..fb25dd7 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
@@ -88,6 +88,20 @@
     }
 
     /**
+     * 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;
+    }
+
+    /**
      * Return the manufacturer of this product. If unset, return null.
      */
     public static String getManufacturer() {
diff --git a/hostsidetests/angle/Android.mk b/hostsidetests/angle/Android.mk
index e54985d..a564b77 100644
--- a/hostsidetests/angle/Android.mk
+++ b/hostsidetests/angle/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsAngleIntegrationHostTestCases
 
diff --git a/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/AngleIntegrationTestActivity.java b/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/AngleIntegrationTestActivity.java
deleted file mode 100644
index e167176..0000000
--- a/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/AngleIntegrationTestActivity.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.angleIntegrationTest.common;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.util.Log;
-
-import java.lang.Override;
-
-public class AngleIntegrationTestActivity extends Activity {
-
-    private final String TAG = this.getClass().getSimpleName();
-
-    private GlesView mGlesView;
-
-    @Override
-    public void onCreate(Bundle icicle) {
-        super.onCreate(icicle);
-
-        mGlesView = new GlesView(this);
-        setContentView(mGlesView);
-
-        Log.i(TAG, "ANGLE Manifest activity complete");
-    }
-
-    public GlesView getGlesView() {
-        return mGlesView;
-    }
-}
diff --git a/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/GlesView.java b/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/GlesView.java
index d0fbe58..f1c053f 100644
--- a/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/GlesView.java
+++ b/hostsidetests/angle/app/common/src/com/android/angleIntegrationTest/common/GlesView.java
@@ -19,14 +19,10 @@
 import static javax.microedition.khronos.egl.EGL10.EGL_STENCIL_SIZE;
 
 import android.annotation.TargetApi;
-import android.content.Context;
 import android.opengl.EGL14;
 import android.opengl.GLES20;
-import android.opengl.GLSurfaceView;
 import android.os.Build.VERSION_CODES;
 import android.util.Log;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
 import javax.microedition.khronos.egl.EGL10;
 import javax.microedition.khronos.egl.EGLConfig;
 import javax.microedition.khronos.egl.EGLContext;
@@ -38,28 +34,21 @@
  */
 
 @TargetApi(VERSION_CODES.GINGERBREAD)
-public class GlesView extends SurfaceView implements SurfaceHolder.Callback2 {
+public class GlesView {
 
     private static final EGL10 EGL = (EGL10) EGLContext.getEGL();
-    private EGLConfig eglConfig;
-    private EGLDisplay display;
-    private SurfaceHolder mSurfaceHolder;
     private String mRenderer = "";
 
     private final String TAG = this.getClass().getSimpleName();
 
-    public GlesView(Context context) {
-      super(context);
-      this.setWillNotDraw(false);
-      getHolder().addCallback(this);
-      createEGL();
-      getHolder().getSurface();
+    public GlesView() {
+        createEGL();
     }
 
     @TargetApi(VERSION_CODES.JELLY_BEAN_MR1)
     private void createEGL() {
         int[] version = new int[2];
-        display = EGL.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
+        EGLDisplay display = EGL.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
         EGL.eglInitialize(display, version);
 
         int[] numConfigs = new int[1];
@@ -68,7 +57,7 @@
         EGL.eglGetConfigs(display, allConfigs, numConfigs[0], numConfigs);
 
         int[] configAttrib =
-            new int[] {
+            new int[]{
                 EGL10.EGL_RENDERABLE_TYPE,
                 EGL14.EGL_OPENGL_ES2_BIT,
                 EGL10.EGL_SURFACE_TYPE,
@@ -90,6 +79,7 @@
 
         EGLConfig[] selectedConfig = new EGLConfig[1];
         EGL.eglChooseConfig(display, configAttrib, selectedConfig, 1, numConfigs);
+        EGLConfig eglConfig;
         if (selectedConfig[0] != null) {
             eglConfig = selectedConfig[0];
             Log.i(TAG, "Found matching EGL config");
@@ -97,33 +87,35 @@
             Log.e(TAG, "Could not find matching EGL config");
             throw new RuntimeException("No Matching EGL Config Found");
         }
-    }
 
-    @TargetApi(VERSION_CODES.JELLY_BEAN_MR1)
-    @Override
-    public void surfaceCreated(SurfaceHolder holder) {
-      EGLSurface surface = EGL.eglCreateWindowSurface(display, eglConfig, this, null);
-        int[] contextAttribs = new int[] {EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE};
-      EGLContext context = EGL
-          .eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, contextAttribs);
+        EGLSurface surface = EGL.eglCreatePbufferSurface(display, eglConfig, null);
+        int[] contextAttribs = new int[]{EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE};
+        EGLContext context = EGL
+            .eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, contextAttribs);
         EGL.eglMakeCurrent(display, surface, surface, context);
 
         Log.i(TAG, "CTS ANGLE Test :: GLES GL_VENDOR   : " + GLES20.glGetString(GLES20.GL_VENDOR));
         Log.i(TAG, "CTS ANGLE Test :: GLES GL_VERSION  : " + GLES20.glGetString(GLES20.GL_VERSION));
-        Log.i(TAG, "CTS ANGLE Test :: GLES GL_RENDERER : " + GLES20.glGetString(GLES20.GL_RENDERER));
+        Log.i(TAG,
+            "CTS ANGLE Test :: GLES GL_RENDERER : " + GLES20.glGetString(GLES20.GL_RENDERER));
         mRenderer = GLES20.glGetString(GLES20.GL_RENDERER);
     }
 
-    @Override
-    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
-
-    @Override
-    public void surfaceDestroyed(SurfaceHolder holder) {}
-
-    @Override
-    public void surfaceRedrawNeeded(SurfaceHolder holder) {}
-
     public String getRenderer() {
         return mRenderer;
     }
+
+    public boolean validateDeveloperOption(boolean angleEnabled)  {
+        if (angleEnabled) {
+            if (!mRenderer.toLowerCase().contains("angle")) {
+                return false;
+            }
+        } else {
+            if (mRenderer.toLowerCase().contains("angle")) {
+                return false;
+            }
+        }
+
+        return true;
+    }
 }
diff --git a/hostsidetests/angle/app/driverTest/Android.mk b/hostsidetests/angle/app/driverTest/Android.mk
index 68a1191..130f6b1 100644
--- a/hostsidetests/angle/app/driverTest/Android.mk
+++ b/hostsidetests/angle/app/driverTest/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts
 
 LOCAL_MULTILIB := both
 
diff --git a/hostsidetests/angle/app/driverTest/src/com/android/angleIntegrationTest/driverTest/AngleDriverTestActivity.java b/hostsidetests/angle/app/driverTest/src/com/android/angleIntegrationTest/driverTest/AngleDriverTestActivity.java
index bb98488..450461a 100644
--- a/hostsidetests/angle/app/driverTest/src/com/android/angleIntegrationTest/driverTest/AngleDriverTestActivity.java
+++ b/hostsidetests/angle/app/driverTest/src/com/android/angleIntegrationTest/driverTest/AngleDriverTestActivity.java
@@ -18,13 +18,10 @@
 
 import static org.junit.Assert.fail;
 
-import androidx.test.rule.ActivityTestRule;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.angleIntegrationTest.common.AngleIntegrationTestActivity;
 import com.android.angleIntegrationTest.common.GlesView;
 
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -33,29 +30,18 @@
 
     private final String TAG = this.getClass().getSimpleName();
 
-    @Rule
-    public ActivityTestRule<AngleIntegrationTestActivity> rule =
-            new ActivityTestRule<>(AngleIntegrationTestActivity.class);
-
     private void validateDeveloperOption(boolean angleEnabled) throws Exception {
-        AngleIntegrationTestActivity activity = rule.getActivity();
-        GlesView glesView = activity.getGlesView();
-        String renderer = glesView.getRenderer();
+        GlesView glesView = new GlesView();
 
-        while(renderer.length() == 0) {
-            renderer = glesView.getRenderer();
-        }
-
-        if (angleEnabled) {
-            if (!renderer.toLowerCase().contains("ANGLE".toLowerCase())) {
+        if (!glesView.validateDeveloperOption(angleEnabled)) {
+            if (angleEnabled) {
+                String renderer = glesView.getRenderer();
                 fail("Failure - ANGLE was not loaded: '" + renderer + "'");
-            }
-        } else {
-            if (renderer.toLowerCase().contains("ANGLE".toLowerCase())) {
+            } else {
+                String renderer = glesView.getRenderer();
                 fail("Failure - ANGLE was loaded: '" + renderer + "'");
             }
         }
-
     }
 
     @Test
diff --git a/hostsidetests/angle/app/driverTestSecondary/Android.mk b/hostsidetests/angle/app/driverTestSecondary/Android.mk
index e3ba621..fc1bbd7 100644
--- a/hostsidetests/angle/app/driverTestSecondary/Android.mk
+++ b/hostsidetests/angle/app/driverTestSecondary/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts
 
 LOCAL_MULTILIB := both
 
diff --git a/hostsidetests/angle/app/driverTestSecondary/src/com/android/angleIntegrationTest/driverTestSecondary/AngleDriverTestActivity.java b/hostsidetests/angle/app/driverTestSecondary/src/com/android/angleIntegrationTest/driverTestSecondary/AngleDriverTestActivity.java
index ce7e5e8..7b25c39 100644
--- a/hostsidetests/angle/app/driverTestSecondary/src/com/android/angleIntegrationTest/driverTestSecondary/AngleDriverTestActivity.java
+++ b/hostsidetests/angle/app/driverTestSecondary/src/com/android/angleIntegrationTest/driverTestSecondary/AngleDriverTestActivity.java
@@ -18,13 +18,10 @@
 
 import static org.junit.Assert.fail;
 
-import androidx.test.rule.ActivityTestRule;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.angleIntegrationTest.common.AngleIntegrationTestActivity;
 import com.android.angleIntegrationTest.common.GlesView;
 
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -33,25 +30,18 @@
 
     private final String TAG = this.getClass().getSimpleName();
 
-    @Rule
-    public ActivityTestRule<AngleIntegrationTestActivity> rule =
-            new ActivityTestRule<>(AngleIntegrationTestActivity.class);
-
     private void validateDeveloperOption(boolean angleEnabled) throws Exception {
-        AngleIntegrationTestActivity activity = rule.getActivity();
-        GlesView glesView = activity.getGlesView();
-        String renderer = glesView.getRenderer();
+        GlesView glesView = new GlesView();
 
-        if (angleEnabled) {
-            if (!renderer.toLowerCase().contains("ANGLE".toLowerCase())) {
+        if (!glesView.validateDeveloperOption(angleEnabled)) {
+            if (angleEnabled) {
+                String renderer = glesView.getRenderer();
                 fail("Failure - ANGLE was not loaded: '" + renderer + "'");
-            }
-        } else {
-            if (renderer.toLowerCase().contains("ANGLE".toLowerCase())) {
+            } else {
+                String renderer = glesView.getRenderer();
                 fail("Failure - ANGLE was loaded: '" + renderer + "'");
             }
         }
-
     }
 
     @Test
diff --git a/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java b/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java
index 85841af..c576253 100644
--- a/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java
+++ b/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java
@@ -24,6 +24,11 @@
 class CtsAngleCommon {
     private static final int TEST_WAIT_TIME_MS = 1000;
 
+    // General
+    static final int NUM_ATTEMPTS = 5;
+    static final int APPLY_SLEEP_MSEC = 500;
+    static final int REATTEMPT_SLEEP_MSEC = 5000;
+
     // Settings.Global
     static final String SETTINGS_GLOBAL_ALL_USE_ANGLE = "angle_gl_driver_all_angle";
     static final String SETTINGS_GLOBAL_DRIVER_PKGS = "angle_gl_driver_selection_pkgs";
diff --git a/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java b/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java
index 5373a3b..5cff73c 100644
--- a/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java
+++ b/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java
@@ -45,12 +45,38 @@
         setGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_PKGS, pkgName);
         setGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_VALUES, driverValue);
 
+        // SETTINGS_GLOBAL_DRIVER_PKGS
+        for (int i = 0; i < NUM_ATTEMPTS; i++)
+        {
+            setGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_PKGS, pkgName);
+            Thread.sleep(APPLY_SLEEP_MSEC);
+            String devOption = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_PKGS);
+            if (devOption.equals(pkgName))
+            {
+                break;
+            }
+            Thread.sleep(REATTEMPT_SLEEP_MSEC);
+        }
+
         String devOption = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_PKGS);
         Assert.assertEquals(
                 "Developer option '" + SETTINGS_GLOBAL_DRIVER_PKGS +
                         "' was not set correctly: '" + devOption + "'",
                 pkgName, devOption);
 
+        // SETTINGS_GLOBAL_DRIVER_VALUES
+        for (int i = 0; i < NUM_ATTEMPTS; i++)
+        {
+            setGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_VALUES, driverValue);
+            Thread.sleep(APPLY_SLEEP_MSEC);
+            devOption = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_VALUES);
+            if (devOption.equals(driverValue))
+            {
+                break;
+            }
+            Thread.sleep(REATTEMPT_SLEEP_MSEC);
+        }
+
         devOption = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_DRIVER_VALUES);
         Assert.assertEquals(
                 "Developer option '" + SETTINGS_GLOBAL_DRIVER_VALUES +
@@ -72,6 +98,18 @@
                 sDriverTestMethodMap.get(driver));
     }
 
+    private void installApp(String appName) throws Exception {
+        for (int i = 0; i < NUM_ATTEMPTS; i++)
+        {
+            try {
+                installPackage(appName);
+                return;
+            } catch(Exception e) {
+                Thread.sleep(REATTEMPT_SLEEP_MSEC);
+            }
+        }
+    }
+
     @Before
     public void setUp() throws Exception {
         clearSettings(getDevice());
@@ -92,8 +130,8 @@
     public void testEnableAngleForAll() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
-        installPackage(ANGLE_DRIVER_TEST_SEC_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_SEC_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.DEFAULT));
@@ -117,7 +155,7 @@
     public void testUseDefaultDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.DEFAULT));
@@ -134,7 +172,7 @@
     public void testUseAngleDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.ANGLE));
@@ -151,7 +189,7 @@
     public void testUseNativeDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.NATIVE));
@@ -168,8 +206,8 @@
     public void testSettingsLengthMismatch() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
-        installPackage(ANGLE_DRIVER_TEST_SEC_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_SEC_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG + "," +
                         ANGLE_DRIVER_TEST_SEC_PKG,
@@ -191,7 +229,7 @@
     public void testUseInvalidDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG, "timtim");
 
@@ -207,7 +245,7 @@
     public void testUpdateDriverValues() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
 
         for (OpenGlDriverChoice firstDriver : OpenGlDriverChoice.values()) {
             for (OpenGlDriverChoice secondDriver : OpenGlDriverChoice.values()) {
@@ -229,8 +267,8 @@
     public void testMultipleDevOptionsAngleNative() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
-        installPackage(ANGLE_DRIVER_TEST_SEC_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_SEC_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG + "," +
                         ANGLE_DRIVER_TEST_SEC_PKG,
@@ -253,8 +291,8 @@
     public void testMultipleUpdateDriverValues() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
-        installPackage(ANGLE_DRIVER_TEST_SEC_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_SEC_APP);
 
         // Set the first PKG to always use ANGLE
         setAndValidatePkgDriver(ANGLE_DRIVER_TEST_PKG, OpenGlDriverChoice.ANGLE);
@@ -316,7 +354,7 @@
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
         // Install the package so the setting isn't removed because the package isn't present.
-        installPackage(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.DEFAULT));
@@ -376,8 +414,8 @@
     public void testMultipleDevOptionsAngleDefault() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_APP);
-        installPackage(ANGLE_DRIVER_TEST_SEC_APP);
+        installApp(ANGLE_DRIVER_TEST_APP);
+        installApp(ANGLE_DRIVER_TEST_SEC_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG + "," + ANGLE_DRIVER_TEST_SEC_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.ANGLE) + "," +
@@ -408,7 +446,7 @@
     public void testMultipleDevOptionsAngleNativeUninstall() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
 
-        installPackage(ANGLE_DRIVER_TEST_SEC_APP);
+        installApp(ANGLE_DRIVER_TEST_SEC_APP);
 
         setAndValidateAngleDevOptionPkgDriver(ANGLE_DRIVER_TEST_PKG + "," + ANGLE_DRIVER_TEST_SEC_PKG,
                 sDriverGlobalSettingMap.get(OpenGlDriverChoice.ANGLE) + "," +
diff --git a/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java b/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java
index 596630b..50f55b0 100644
--- a/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java
+++ b/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java
@@ -61,22 +61,42 @@
         setProperty(getDevice(), PROPERTY_TEMP_RULES_FILE, DEVICE_TEMP_RULES_FILE_PATH);
     }
 
+    private void setAndValidateAngleDevOptionWhitelist(String whiteList) throws Exception {
+        // SETTINGS_GLOBAL_WHITELIST
+        for (int i = 0; i < NUM_ATTEMPTS; i++)
+        {
+            setGlobalSetting(getDevice(), SETTINGS_GLOBAL_WHITELIST, whiteList);
+            Thread.sleep(APPLY_SLEEP_MSEC);
+            String devOption = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_WHITELIST);
+            if (devOption.equals(whiteList))
+            {
+                break;
+            }
+            Thread.sleep(REATTEMPT_SLEEP_MSEC);
+        }
+
+        String devOption = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_WHITELIST);
+        Assert.assertEquals(
+            "Developer option '" + SETTINGS_GLOBAL_WHITELIST +
+                "' was not set correctly: '" + devOption + "'",
+            whiteList, devOption);
+    }
+
     @Before
     public void setUp() throws Exception {
         clearSettings(getDevice());
 
         mWhiteList = getGlobalSetting(getDevice(), SETTINGS_GLOBAL_WHITELIST);
 
-        // Application must be whitelisted to load temp rules
-        setGlobalSetting(getDevice(), SETTINGS_GLOBAL_WHITELIST,
-                ANGLE_DRIVER_TEST_PKG + "," + ANGLE_DRIVER_TEST_SEC_PKG);
+        final String whitelist = ANGLE_DRIVER_TEST_PKG + "," + ANGLE_DRIVER_TEST_SEC_PKG;
+        setAndValidateAngleDevOptionWhitelist(whitelist);
     }
 
     @After
     public void tearDown() throws Exception {
         clearSettings(getDevice());
 
-        setGlobalSetting(getDevice(), SETTINGS_GLOBAL_WHITELIST, mWhiteList);
+        setAndValidateAngleDevOptionWhitelist(mWhiteList);
 
         FileUtil.deleteFile(mRulesFile);
     }
diff --git a/hostsidetests/apex/Android.bp b/hostsidetests/apex/Android.bp
index 5b1f436a5..33194a1 100644
--- a/hostsidetests/apex/Android.bp
+++ b/hostsidetests/apex/Android.bp
@@ -15,6 +15,6 @@
 java_test_host {
     name: "CtsApexTestCases",
     srcs: ["src/**/*.java"],
-    test_suites: ["cts", "general-tests"],
+    test_suites: ["cts", "general-tests", "mts"],
     libs: ["cts-tradefed", "tradefed"],
 }
diff --git a/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk b/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk
index c9882b8..dc6a27c 100644
--- a/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_DEX_PREOPT := false
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp
new file mode 100644
index 0000000..6b08f1d
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp
@@ -0,0 +1,67 @@
+///////////////////////////////////////////////////////////
+// Variant: Privileged app upgrade
+
+android_test_import {
+    name: "CtsShimPrivUpgradePrebuilt",
+
+    // The 'arm' apk has both arm and arm64 so's. Same for x86/x86_64.
+    arch: {
+        arm: {
+            apk: "apk/arm/CtsShimPrivUpgrade.apk",
+        },
+        arm64: {
+            apk: "apk/arm/CtsShimPrivUpgrade.apk",
+        },
+        x86: {
+            apk: "apk/x86/CtsShimPrivUpgrade.apk",
+        },
+        x86_64: {
+            apk: "apk/x86/CtsShimPrivUpgrade.apk",
+        },
+    },
+
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    // Make sure the build system doesn't try to resign the APK
+    presigned: true,
+    dex_preopt: {
+        enabled: false,
+    },
+}
+
+///////////////////////////////////////////////////////////
+// Variant: Privileged app upgrade (wrong SHA)
+
+android_test_import {
+    name: "CtsShimPrivUpgradeWrongSHAPrebuilt",
+
+    // The 'arm' apk has both arm and arm64 so's. Same for x86/x86_64.
+    arch: {
+        arm: {
+            apk: "apk/arm/CtsShimPrivUpgradeWrongSHA.apk",
+        },
+        arm64: {
+            apk: "apk/arm/CtsShimPrivUpgradeWrongSHA.apk",
+        },
+        x86: {
+            apk: "apk/x86/CtsShimPrivUpgradeWrongSHA.apk",
+        },
+        x86_64: {
+            apk: "apk/x86/CtsShimPrivUpgradeWrongSHA.apk",
+        },
+    },
+
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    // Make sure the build system doesn't try to resign the APK
+    presigned: true,
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
index 4c8dcd5..4978441 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
@@ -34,43 +34,3 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
-
-
-###########################################################
-# Variant: Privileged app upgrade
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CtsShimPrivUpgradePrebuilt
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE_CLASS := APPS
-LOCAL_BUILT_MODULE_STEM := package.apk
-# Make sure the build system doesn't try to resign the APK
-LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-# The 'arm' apk has both arm and arm64 so's. Same for x86/x86_64.
-my_apk_dir := $(subst arm64,arm,$(TARGET_ARCH))
-my_apk_dir := $(subst x86_64,x86,$(my_apk_dir))
-LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/$(my_apk_dir)/CtsShimPrivUpgrade.apk
-
-include $(BUILD_PREBUILT)
-
-###########################################################
-# Variant: Privileged app upgrade (wrong SHA)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CtsShimPrivUpgradeWrongSHAPrebuilt
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE_CLASS := APPS
-LOCAL_BUILT_MODULE_STEM := package.apk
-# Make sure the build system doesn't try to resign the APK
-LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/$(my_apk_dir)/CtsShimPrivUpgradeWrongSHA.apk
-
-include $(BUILD_PREBUILT)
-
-my_apk_dir :=
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
index db47656..0a8a99a 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_USE_AAPT2 := true
 LOCAL_APK_LIBRARIES := CtsSplitApp
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
index e2e059c..5337057 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
index ff827b9..7fceede 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
index 29bc859..9149930 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
index 3c6cc22..95d02d0 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
index acb545f..ad10be0 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
index 8f3b381..f008564 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
index 76ef050..ded5b29 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
index e08bcf0..2ec3002 100755
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
@@ -492,6 +492,11 @@
             return null;
         }
         List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByText(text);
+        PackageManager packageManager = InstrumentationRegistry.getTargetContext().getPackageManager();
+        boolean isWatch = packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH);
+        if (isWatch) {
+            return findByTextForWatch(root, text);
+        }
         for (AccessibilityNodeInfo node : nodes) {
             if (node.getText().toString().equals(text)) {
                 return node;
@@ -500,6 +505,21 @@
         return null;
     }
 
+    private static AccessibilityNodeInfo findByTextForWatch(AccessibilityNodeInfo root, String text) {
+        String trimmedText = trimText(text);
+        List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByText(trimmedText);
+        for (AccessibilityNodeInfo node : nodes) {
+            if (trimText(node.getText().toString()).equals(trimmedText)) {
+                return node;
+            }
+        }
+        return null;
+    }
+
+    private static String trimText(String text) {
+        return text != null ? text.substring(0, Math.min(text.length(), 20)) : null;
+    }
+
     private static AccessibilityNodeInfo findByTextInCollection(AccessibilityNodeInfo root,
             String text)  throws Exception {
         AccessibilityNodeInfo result;
diff --git a/hostsidetests/backup/OWNERS b/hostsidetests/backup/OWNERS
index c28c4d8..e0e5e22 100644
--- a/hostsidetests/backup/OWNERS
+++ b/hostsidetests/backup/OWNERS
@@ -2,6 +2,7 @@
 # Use this reviewer by default.
 br-framework-team+reviews@google.com
 
+alsutton@google.com
 anniemeng@google.com
 brufino@google.com
 nathch@google.com
diff --git a/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java b/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java
index d9a3975..a14f0f0 100644
--- a/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java
+++ b/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.fail;
 
 import com.android.compatibility.common.util.BackupHostSideUtils;
+import com.android.compatibility.common.util.BackupUtils;
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.config.Option;
 import com.android.tradefed.config.OptionClass;
@@ -31,6 +32,7 @@
 import com.android.tradefed.targetprep.TargetSetupError;
 
 import java.io.IOException;
+import java.util.Optional;
 import java.util.concurrent.Callable;
 import java.util.concurrent.CompletionException;
 import java.util.concurrent.TimeUnit;
@@ -60,17 +62,20 @@
 
     private static final String LOCAL_TRANSPORT =
             "com.android.localtransport/.LocalTransport";
+    private final int USER_SYSTEM = 0;
 
     private boolean mIsBackupSupported;
     private boolean mWasBackupEnabled;
+    private Optional<Boolean> mWasBackupActivated = Optional.empty();
     private String mOldTransport;
     private ITestDevice mDevice;
+    private BackupUtils mBackupUtils;
 
     @Override
     public void setUp(ITestDevice device, IBuildInfo buildInfo)
             throws TargetSetupError, BuildError, DeviceNotAvailableException {
         mDevice = device;
-
+        mBackupUtils = BackupHostSideUtils.createBackupUtils(mDevice);
         mIsBackupSupported = mDevice.hasFeature("feature:" + FEATURE_BACKUP);
 
         // In case the device was just rebooted, wait for the broadcast queue to get idle to avoid
@@ -78,6 +83,9 @@
         waitForBroadcastIdle();
 
         if (mIsBackupSupported) {
+            CLog.i("Activating backup on %s", mDevice.getSerialNumber());
+            mWasBackupActivated = Optional.of(setBackupActive(true));
+
             // Enable backup and select local backup transport
             waitForTransport(LOCAL_TRANSPORT);
 
@@ -91,7 +99,7 @@
                     CLog.d("Old transport : %s", mOldTransport);
                 }
                 try {
-                    BackupHostSideUtils.createBackupUtils(mDevice).waitForBackupInitialization();
+                    mBackupUtils.waitForBackupInitialization();
                 } catch (IOException e) {
                     throw new TargetSetupError("Backup not initialized", e);
                 }
@@ -105,13 +113,18 @@
         mDevice = device;
 
         if (mIsBackupSupported) {
-            if (mEnableBackup) {
-                CLog.i("Returning backup to it's previous state on %s", mDevice.getSerialNumber());
-                enableBackup(mWasBackupEnabled);
-                if (mSelectLocalTransport) {
-                    CLog.i("Returning selected transport to it's previous value on %s",
+            if (mWasBackupActivated.isPresent()) {
+                setBackupActive(mWasBackupActivated.get());
+
+                if (mEnableBackup) {
+                    CLog.i("Returning backup to it's previous state on %s",
                             mDevice.getSerialNumber());
-                    setBackupTransport(mOldTransport);
+                    enableBackup(mWasBackupEnabled);
+                    if (mSelectLocalTransport) {
+                        CLog.i("Returning selected transport to it's previous value on %s",
+                                mDevice.getSerialNumber());
+                        setBackupTransport(mOldTransport);
+                    }
                 }
             }
         }
@@ -215,6 +228,18 @@
         }
     }
 
+    private boolean setBackupActive(boolean active) {
+        boolean wasBackupActive;
+        try {
+            wasBackupActive  = mBackupUtils.isBackupActivatedForUser(USER_SYSTEM);
+            mBackupUtils.activateBackupForUser(active, USER_SYSTEM);
+        } catch (IOException e) {
+            throw new RuntimeException("Failed set backup active status");
+        }
+
+        return wasBackupActive;
+    }
+
     private static <T> T uncheck(Callable<T> callable) {
         try {
             return callable.call();
diff --git a/hostsidetests/checkpoint/Android.mk b/hostsidetests/checkpoint/Android.mk
new file mode 100644
index 0000000..fc66d79
--- /dev/null
+++ b/hostsidetests/checkpoint/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2019 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Only compile source java files in this apk.
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE := CtsCheckpointTestCases
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
+
+LOCAL_CTS_TEST_PACKAGE := android.checkpoint
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
+
+# Build the test APKs using their own makefiles
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/checkpoint/AndroidTest.xml b/hostsidetests/checkpoint/AndroidTest.xml
new file mode 100644
index 0000000..54aeaa8
--- /dev/null
+++ b/hostsidetests/checkpoint/AndroidTest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<configuration description="Config for the CTS Checkpoint host tests">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsCheckpointTestCases.jar" />
+        <option name="runtime-hint" value="1m" />
+    </test>
+</configuration>
diff --git a/hostsidetests/checkpoint/OWNERS b/hostsidetests/checkpoint/OWNERS
new file mode 100644
index 0000000..6b12108
--- /dev/null
+++ b/hostsidetests/checkpoint/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 30545
+paullawrence@google.com
+drosen@google.com
diff --git a/hostsidetests/checkpoint/src/android/checkpoint/cts/CheckpointHostTest.java b/hostsidetests/checkpoint/src/android/checkpoint/cts/CheckpointHostTest.java
new file mode 100644
index 0000000..3426443
--- /dev/null
+++ b/hostsidetests/checkpoint/src/android/checkpoint/cts/CheckpointHostTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2019 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.checkpoint.cts;
+
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.DeviceTestCase;
+import junit.framework.Assert;
+
+
+/**
+ * Test to validate that the checkpoint failures in b/138952436 are properly patched
+ */
+public class CheckpointHostTest extends DeviceTestCase {
+    private static final String TAG = "CheckpointHostTest";
+
+    public void testLogEntries() throws Exception {
+        // Clear buffer to make it easier to find new logs
+        getDevice().executeShellCommand("logcat --clear");
+
+        // reboot device
+        getDevice().rebootUntilOnline();
+        waitForBootCompleted();
+
+        // wait for logs to post
+        Thread.sleep(10000);
+
+        final String amLog = getDevice().executeShellCommand("logcat -d -s ActivityManager");
+        int counterNameIndex = amLog.indexOf("ActivityManager: About to commit checkpoint");
+        Assert.assertTrue("did not find commit checkpoint in boot logs", counterNameIndex != -1);
+
+        final String checkpointLog = getDevice().executeShellCommand("logcat -d -s Checkpoint");
+        counterNameIndex = checkpointLog.indexOf(
+            "Checkpoint: cp_prepareCheckpoint called");
+        Assert.assertTrue("did not find prepare checkpoint in boot logs", counterNameIndex != -1);
+    }
+
+    private boolean isBootCompleted() throws Exception {
+        return "1".equals(getDevice().executeShellCommand("getprop sys.boot_completed").trim());
+    }
+
+    private void waitForBootCompleted() throws Exception {
+        for (int i = 0; i < 45; i++) {
+            if (isBootCompleted()) {
+                return;
+            }
+            Thread.sleep(1000);
+        }
+        throw new AssertionError("System failed to become ready!");
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAdmin/src/com.android.cts.deviceadmin/DeviceOwnerPasswordTest.java b/hostsidetests/devicepolicy/app/DeviceAdmin/src/com.android.cts.deviceadmin/DeviceOwnerPasswordTest.java
index 5892c5c..1fae525 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdmin/src/com.android.cts.deviceadmin/DeviceOwnerPasswordTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAdmin/src/com.android.cts.deviceadmin/DeviceOwnerPasswordTest.java
@@ -60,10 +60,9 @@
         assertEquals(10, dpm.getPasswordMinimumLength(mAdminComponent));
         assertPasswordSufficiency(true); // length not checked for this quality
 
-        // TODO(ascull): fix resetPassword() logic so these succeed
-        assertPasswordFails("1234", caseDescription);
-        assertPasswordFails("abcd", caseDescription);
-        assertPasswordFails("abcd1234", caseDescription);
+        assertPasswordSucceeds("1234", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+        assertPasswordSucceeds("abcd1234", caseDescription);
 
         dpm.setPasswordMinimumLength(mAdminComponent, 4);
         caseDescription = "minimum password length = 4";
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DevicePolicyLoggingTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DevicePolicyLoggingTest.java
index d6856a9..4e58d92 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DevicePolicyLoggingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DevicePolicyLoggingTest.java
@@ -50,7 +50,7 @@
 
     public void testPasswordMethodsLogged() {
         mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
-                DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
+                DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
         mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 13);
         mDevicePolicyManager.setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, 14);
         mDevicePolicyManager.setPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT, 15);
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PasswordRequirementsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PasswordRequirementsTest.java
new file mode 100644
index 0000000..f9ce726
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PasswordRequirementsTest.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2019 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 com.android.cts.deviceandprofileowner;
+
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+
+import static org.testng.Assert.assertThrows;
+
+/**
+ * Class that tests password constraints API preconditions.
+ */
+public class PasswordRequirementsTest extends BaseDeviceAdminTest {
+    private static final int TEST_VALUE = 5;
+    private static final int DEFAULT_NUMERIC = 1;
+    private static final int DEFAULT_LETTERS = 1;
+    private static final int DEFAULT_UPPERCASE = 0;
+    private static final int DEFAULT_LOWERCASE = 0;
+    private static final int DEFAULT_NON_LETTER = 0;
+    private static final int DEFAULT_SYMBOLS = 1;
+    private static final int DEFAULT_LENGTH = 0;
+
+    public void testPasswordConstraintsDoesntThrowAndPreservesValuesPreR() {
+        // Pre-R password restrictions can be set in any order.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_SOMETHING);
+        // These shouldn't throw.
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+
+        // Make sure these values are preserved and not reset when quality is set low.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_UNSPECIFIED);
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT));
+    }
+
+    public void testSettingConstraintsWithLowQualityThrowsOnRPlus() {
+        // On R and above quality should be set first.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_SOMETHING);
+
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+    }
+
+    public void testSettingConstraintsWithNumericQualityOnlyLengthAllowedOnRPlus() {
+        // On R and above quality should be set first.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_NUMERIC);
+
+        // This should be allowed now.
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+
+        // These are still not allowed.
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+        assertThrows(IllegalStateException.class, () -> mDevicePolicyManager
+                .setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, TEST_VALUE));
+    }
+
+    public void testSettingConstraintsWithComplexQualityAndResetWithLowerQuality() {
+        // On R and above when quality is lowered, irrelevant requirements are getting reset.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_COMPLEX);
+        // These shouldn't throw anymore
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+        mDevicePolicyManager.setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, TEST_VALUE);
+
+        // Downgrade to NUMERIC, only length makes sense after that.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_NUMERIC);
+
+        // Length shouldn't be reset
+        assertEquals(TEST_VALUE,
+                mDevicePolicyManager.getPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT));
+
+        // But other requirements should.
+        assertEquals(DEFAULT_NUMERIC,
+                mDevicePolicyManager.getPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(DEFAULT_LETTERS,
+                mDevicePolicyManager.getPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(DEFAULT_UPPERCASE,
+                mDevicePolicyManager.getPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(DEFAULT_LOWERCASE,
+                mDevicePolicyManager.getPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(DEFAULT_NON_LETTER,
+                mDevicePolicyManager.getPasswordMinimumNonLetter(ADMIN_RECEIVER_COMPONENT));
+        assertEquals(DEFAULT_SYMBOLS,
+                mDevicePolicyManager.getPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT));
+
+        // Downgrade to SOMETHING.
+        mDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_SOMETHING);
+
+        // Now length should also be reset.
+        assertEquals(DEFAULT_LENGTH,
+                mDevicePolicyManager.getPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT));
+
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java
index 72f01aa..7ab2e9d 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java
@@ -154,26 +154,6 @@
         assertPasswordSucceeds("1234", caseDescription);
         assertPasswordSucceeds("abcd", caseDescription); // can't change.
         assertPasswordSucceeds("abcd1234", caseDescription);
-
-        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 10);
-        caseDescription = "minimum password length = 10";
-        assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT));
-        assertPasswordSufficiency(true); // length not checked for this quality
-
-        // TODO(ascull): fix resetPassword() logic so these succeed
-        assertPasswordFails("1234", caseDescription);
-        assertPasswordFails("abcd", caseDescription);
-        assertPasswordFails("abcd1234", caseDescription);
-
-        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 4);
-        caseDescription = "minimum password length = 4";
-        assertEquals(4, mDevicePolicyManager.getPasswordMinimumLength(
-                ADMIN_RECEIVER_COMPONENT));
-        assertPasswordSufficiency(true);
-
-        assertPasswordSucceeds("1234", caseDescription);
-        assertPasswordSucceeds("abcd", caseDescription);
-        assertPasswordSucceeds("abcd1234", caseDescription);
     }
 
     public void testPasswordQuality_numeric() {
@@ -527,7 +507,6 @@
         // First remove device lock
         mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
                 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
-        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 0);
         assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, null,
                 TOKEN0, 0));
 
@@ -557,7 +536,14 @@
     }
 
     private void resetComplexPasswordRestrictions() {
+        final int quality = mDevicePolicyManager.getPasswordQuality(ADMIN_RECEIVER_COMPONENT);
+        if (quality < PASSWORD_QUALITY_NUMERIC) {
+            return;
+        }
         mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 0);
+        if (quality < PASSWORD_QUALITY_COMPLEX) {
+            return;
+        }
         mDevicePolicyManager.setPasswordMinimumUpperCase(ADMIN_RECEIVER_COMPONENT, 0);
         mDevicePolicyManager.setPasswordMinimumLowerCase(ADMIN_RECEIVER_COMPONENT, 0);
         mDevicePolicyManager.setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, 0);
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/Android.bp b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp
similarity index 88%
rename from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/Android.bp
rename to hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp
index f0f4716..8dc698e 100644
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp
@@ -13,7 +13,7 @@
 // limitations under the License.
 
 android_test_helper_app {
-    name: "CtsNoLaunchableActivityApp",
+    name: "CtsHasLauncherActivityApp",
     // Don't include this package in any target
     // When built, explicitly put it in the data partition.
     dex_preopt: {
@@ -29,14 +29,13 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "current",
 }
 
-// Build for no component app
+// Build for no launcher activity app
 android_test_helper_app {
-    name: "CtsNoComponentApp",
+    name: "CtsNoLauncherActivityApp",
     dex_preopt: {
         enabled: false,
     },
@@ -50,9 +49,8 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
-    manifest: "no_component_AndroidManifest.xml",
+    manifest: "no_launcher_activity_AndroidManifest.xml",
     sdk_version: "current",
 }
 
@@ -72,7 +70,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     manifest: "no_permission_AndroidManifest.xml",
     sdk_version: "current",
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/AndroidManifest.xml
similarity index 69%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/AndroidManifest.xml
copy to hostsidetests/devicepolicy/app/HasLauncherActivityApp/AndroidManifest.xml
index 59f3767..760b31f 100755
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/AndroidManifest.xml
@@ -16,9 +16,15 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nolaunchableactivityapp">
+    package="com.android.cts.haslauncheractivityapp">
     <uses-permission android:name="android.permission.INTERNET" />
-    <application>
+    <application android:testOnly="true">
+        <activity android:name="com.android.cts.haslauncheractivityapp.MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
         <service android:name=".EmptyService" android:enabled="true"></service>
     </application>
 
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/no_launcher_activity_AndroidManifest.xml
similarity index 71%
rename from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/AndroidManifest.xml
rename to hostsidetests/devicepolicy/app/HasLauncherActivityApp/no_launcher_activity_AndroidManifest.xml
index 59f3767..ae2249a 100755
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/no_launcher_activity_AndroidManifest.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2019 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.
@@ -16,9 +16,14 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nolaunchableactivityapp">
+    package="com.android.cts.nolauncheractivityapp">
     <uses-permission android:name="android.permission.INTERNET" />
     <application>
+        <activity android:name="com.android.cts.haslauncheractivityapp.MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW" />
+            </intent-filter>
+        </activity>
         <service android:name=".EmptyService" android:enabled="true"></service>
     </application>
 
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_permission_AndroidManifest.xml b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/no_permission_AndroidManifest.xml
similarity index 100%
rename from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_permission_AndroidManifest.xml
rename to hostsidetests/devicepolicy/app/HasLauncherActivityApp/no_permission_AndroidManifest.xml
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/src/com/android/cts/nolaunchableactivityapp/EmptyService.java b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/src/com/android/cts/haslauncheractivityapp/EmptyService.java
similarity index 94%
rename from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/src/com/android/cts/nolaunchableactivityapp/EmptyService.java
rename to hostsidetests/devicepolicy/app/HasLauncherActivityApp/src/com/android/cts/haslauncheractivityapp/EmptyService.java
index 6cd0da6..80f9ee5 100644
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/src/com/android/cts/nolaunchableactivityapp/EmptyService.java
+++ b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/src/com/android/cts/haslauncheractivityapp/EmptyService.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.android.cts.nolaunchableactivityapp;
+package com.android.cts.haslaunchableactivityapp;
 
 import android.app.Service;
 import android.content.Intent;
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/src/com/android/cts/haslauncheractivityapp/MainActivity.java
old mode 100755
new mode 100644
similarity index 63%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to hostsidetests/devicepolicy/app/HasLauncherActivityApp/src/com/android/cts/haslauncheractivityapp/MainActivity.java
index a48cb1d..1f2b2cb
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/src/com/android/cts/haslauncheractivityapp/MainActivity.java
@@ -1,6 +1,5 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2019 The Android Open Source Project
+/*
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -13,13 +12,11 @@
  * 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 com.android.cts.haslaunchableactivityapp;
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
+import android.app.Activity;
 
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
-
-</manifest>
+public class MainActivity extends Activity {
+}
 
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
index 45032a4..cade532 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
+++ b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
@@ -42,7 +42,9 @@
 import android.test.AndroidTestCase;
 
 import androidx.test.InstrumentationRegistry;
+import com.android.compatibility.common.util.SystemUtil;
 
+import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
@@ -53,12 +55,14 @@
 public class LauncherAppsTests extends AndroidTestCase {
 
     public static final String SIMPLE_APP_PACKAGE = "com.android.cts.launcherapps.simpleapp";
-    private static final String NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE =
-            "com.android.cts.nolaunchableactivityapp";
-    private static final String NO_COMPONENT_APP_PACKAGE =
-            "com.android.cts.nocomponentapp";
+    private static final String HAS_LAUNCHER_ACTIVITY_APP_PACKAGE =
+            "com.android.cts.haslauncheractivityapp";
+    private static final String NO_LAUNCHER_ACTIVITY_APP_PACKAGE =
+            "com.android.cts.nolauncheractivityapp";
     private static final String NO_PERMISSION_APP_PACKAGE =
             "com.android.cts.nopermissionapp";
+    private static final String LAUNCHER_ACTIVITY_COMPONENT =
+            "com.android.cts.haslauncheractivityapp/.MainActivity";
 
     private static final String SYNTHETIC_APP_DETAILS_ACTIVITY = "android.app.AppDetailsActivity";
 
@@ -216,15 +220,17 @@
         assertFalse(mLauncherApps.isPackageEnabled("android", mUser));
     }
 
-    public void testNoLaunchableActivityAppHasAppDetailsActivityInjected() throws Exception {
-        // NoLaunchableActivityApp is installed for duration of this test - make sure
+    public void testHasLauncherActivityAppHasAppDetailsActivityInjected() throws Exception {
+        // HasLauncherActivityApp is installed for duration of this test - make sure
         // it's present on the activity list, has the synthetic activity generated, and it's
         // enabled and exported
-        assertActivityInjected(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE);
+        disableLauncherActivity();
+        assertActivityInjected(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE);
     }
 
     public void testGetSetSyntheticAppDetailsActivityEnabled() throws Exception {
-        assertActivityInjected(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE);
+        disableLauncherActivity();
+        assertActivityInjected(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE);
         PackageManager pm = mInstrumentation.getContext().getPackageManager();
         try {
             pm.setSyntheticAppDetailsActivityEnabled(mContext.getPackageName(), false);
@@ -233,7 +239,7 @@
             // Expected: No permission
         }
         try {
-            pm.setSyntheticAppDetailsActivityEnabled(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE, false);
+            pm.setSyntheticAppDetailsActivityEnabled(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE, false);
             fail("Should not able to change other app's app details activity state");
         } catch (SecurityException e) {
             // Expected: No permission
@@ -241,17 +247,17 @@
         mInstrumentation.getUiAutomation().adoptShellPermissionIdentity();
         try {
             assertTrue(
-                    pm.getSyntheticAppDetailsActivityEnabled(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE));
+                    pm.getSyntheticAppDetailsActivityEnabled(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE));
             // Disable app details activity and assert if the change is applied
-            pm.setSyntheticAppDetailsActivityEnabled(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE, false);
+            pm.setSyntheticAppDetailsActivityEnabled(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE, false);
             assertFalse(
-                    pm.getSyntheticAppDetailsActivityEnabled(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE));
-            assertInjectedActivityNotFound(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE);
+                    pm.getSyntheticAppDetailsActivityEnabled(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE));
+            assertInjectedActivityNotFound(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE);
             // Enable app details activity and assert if the change is applied
-            pm.setSyntheticAppDetailsActivityEnabled(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE, true);
+            pm.setSyntheticAppDetailsActivityEnabled(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE, true);
             assertTrue(
-                    pm.getSyntheticAppDetailsActivityEnabled(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE));
-            assertActivityInjected(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE);
+                    pm.getSyntheticAppDetailsActivityEnabled(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE));
+            assertActivityInjected(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE);
         } finally {
             mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
         }
@@ -262,10 +268,10 @@
         assertActivityInjected(MANAGED_PROFILE_PKG);
     }
 
-    public void testNoComponentAppNotInjected() throws Exception {
-        // NoComponentApp is installed for duration of this test - make sure
+    public void testNoLauncherActivityAppNotInjected() throws Exception {
+        // NoLauncherActivityApp is installed for duration of this test - make sure
         // it's NOT present on the activity list
-        assertInjectedActivityNotFound(NO_COMPONENT_APP_PACKAGE);
+        assertInjectedActivityNotFound(NO_LAUNCHER_ACTIVITY_APP_PACKAGE);
     }
 
     public void testNoPermissionAppNotInjected() throws Exception {
@@ -275,10 +281,11 @@
     }
 
     public void testDoPoNoTestAppInjectedActivityFound() throws Exception {
-        // NoLaunchableActivityApp is installed for duration of this test - make sure
+        // HasLauncherActivityApp is installed for duration of this test - make sure
         // it's NOT present on the activity list For example, DO / PO mode won't show icons.
         // This test is being called by DeviceOwnerTest.
-        assertInjectedActivityNotFound(NO_LAUNCHABLE_ACTIVITY_APP_PACKAGE);
+        disableLauncherActivity();
+        assertInjectedActivityNotFound(HAS_LAUNCHER_ACTIVITY_APP_PACKAGE);
     }
 
     public void testProfileOwnerInjectedActivityNotFound() throws Exception {
@@ -305,6 +312,11 @@
         }
     }
 
+    private void disableLauncherActivity() throws IOException {
+        SystemUtil.runShellCommand(mInstrumentation,
+                "pm disable --user " + mUser.getIdentifier() + " " + LAUNCHER_ACTIVITY_COMPONENT);
+    }
+
     private void expectSecurityException(ExceptionRunnable action, String failMessage)
             throws Exception {
         try {
@@ -336,7 +348,7 @@
             if (compName.getPackageName().equals(targetPackage)) {
                 noLaunchableActivityAppFound = true;
                 // make sure it points to the synthetic app details activity
-                assertEquals(activity.getName(), SYNTHETIC_APP_DETAILS_ACTIVITY);
+                assertEquals(SYNTHETIC_APP_DETAILS_ACTIVITY, activity.getName());
                 // make sure it's both exported and enabled
                 try {
                     PackageManager pm = mInstrumentation.getContext().getPackageManager();
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileCalendarTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileCalendarTest.java
index 083848d..5ced0e6 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileCalendarTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileCalendarTest.java
@@ -102,9 +102,6 @@
     private static final long TEST_VIEW_EVENT_END = 10000;
     private static final boolean TEST_VIEW_EVENT_ALL_DAY = false;
     private static final int TEST_VIEW_EVENT_FLAG = Intent.FLAG_ACTIVITY_NEW_TASK;
-    private static final int TIMEOUT_SEC = 10;
-    private static final String ID_TEXTVIEW =
-            "com.android.cts.managedprofile:id/view_event_text";
 
     private ContentResolver mResolver;
     private DevicePolicyManager mDevicePolicyManager;
@@ -335,29 +332,6 @@
         assertThat(cursor.getCount()).isEqualTo(1);
     }
 
-    // This test should be run when the test package is whitelisted.
-    public void testViewEventCrossProfile_intentReceivedWhenWhitelisted() throws Exception {
-        requireRunningOnPrimaryProfile();
-
-        // Get UiDevice and start view event activity.
-        final UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
-        device.wakeUp();
-
-        assertThat(CalendarContract.startViewCalendarEventInManagedProfile(mContext,
-                TEST_VIEW_EVENT_ID, TEST_VIEW_EVENT_START, TEST_VIEW_EVENT_END,
-                TEST_VIEW_EVENT_ALL_DAY, TEST_VIEW_EVENT_FLAG)).isTrue();
-        final String textviewString = getViewEventCrossProfileString(TEST_VIEW_EVENT_ID,
-                TEST_VIEW_EVENT_START, TEST_VIEW_EVENT_END, TEST_VIEW_EVENT_ALL_DAY,
-                TEST_VIEW_EVENT_FLAG);
-
-        // Look for the text view to verify that activity is started in work profile.
-        UiObject2 textView = device.wait(
-                Until.findObject(By.res(ID_TEXTVIEW)),
-                TIMEOUT_SEC);
-        assertThat(textView).isNotNull();
-        assertThat(textView.getText()).isEqualTo(textviewString);
-    }
-
     // This test should be run when the test package is whitelisted and cross-profile calendar
     // is enabled in settings.
     public void testPrimaryProfile_getExceptionWhenQueryNonWhitelistedColumns() {
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ParentProfileTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ParentProfileTest.java
index 17cea9b..6cce328 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ParentProfileTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ParentProfileTest.java
@@ -78,6 +78,7 @@
             .add("getRequiredStrongAuthTimeout")
             .add("setRequiredStrongAuthTimeout")
             .add("isDeviceIdAttestationSupported")
+            .add("isUniqueDeviceAttestationSupported")
             .build();
 
     private static final String LOG_TAG = "ParentProfileTest";
diff --git a/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/src/com/android/cts/transferowner/TransferProfileOwnerIncomingTest.java b/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/src/com/android/cts/transferowner/TransferProfileOwnerIncomingTest.java
index 4dc9a5b..92c63c0 100644
--- a/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/src/com/android/cts/transferowner/TransferProfileOwnerIncomingTest.java
+++ b/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/src/com/android/cts/transferowner/TransferProfileOwnerIncomingTest.java
@@ -36,9 +36,13 @@
         assertTrue(mDevicePolicyManager.getCameraDisabled(mIncomingComponentName));
         assertTrue(mDevicePolicyManager.getCrossProfileCallerIdDisabled(mIncomingComponentName));
         assertEquals(
+                DevicePolicyManager.PASSWORD_QUALITY_NUMERIC,
+                mDevicePolicyManager.getPasswordQuality(mIncomingComponentName));
+        assertEquals(
                 passwordLength,
                 mDevicePolicyManager.getPasswordMinimumLength(mIncomingComponentName));
 
+
         DevicePolicyManager targetParentProfileInstance =
                 mDevicePolicyManager.getParentProfileInstance(mIncomingComponentName);
         if (mHasSecureLockScreen) {
diff --git a/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/src/com/android/cts/transferowner/TransferProfileOwnerOutgoingTest.java b/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/src/com/android/cts/transferowner/TransferProfileOwnerOutgoingTest.java
index 157e840..cebeaf1 100644
--- a/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/src/com/android/cts/transferowner/TransferProfileOwnerOutgoingTest.java
+++ b/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/src/com/android/cts/transferowner/TransferProfileOwnerOutgoingTest.java
@@ -43,6 +43,8 @@
         DevicePolicyManager parentDevicePolicyManager =
                 mDevicePolicyManager.getParentProfileInstance(mOutgoingComponentName);
         mDevicePolicyManager.setCameraDisabled(mOutgoingComponentName, true);
+        mDevicePolicyManager.setPasswordQuality(
+                mOutgoingComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
         mDevicePolicyManager.setPasswordMinimumLength(mOutgoingComponentName, passwordLength);
         mDevicePolicyManager.setCrossProfileCallerIdDisabled(mOutgoingComponentName, true);
         parentDevicePolicyManager.setPasswordExpirationTimeout(
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index 7b0a5bbe..5aead23 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -155,7 +155,7 @@
         "cmd netpolicy set restrict-background false";
 
     // The following constants were copied from DevicePolicyManager
-    private static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
+    private static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
     private static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
     private static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
     private static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
@@ -1216,6 +1216,7 @@
         }
     }
 
+    @FlakyTest(bugId = 141314026)
     public void testSuspendPackage() throws Exception {
         if (!mHasFeature) {
             return;
@@ -1243,6 +1244,7 @@
         executeDeviceTestMethod(".SuspendPackageTest", "testSuspendNotSuspendablePackages");
     }
 
+    @FlakyTest(bugId = 141314026)
     public void testSuspendPackageWithPackageManager() throws Exception {
         if (!mHasFeature) {
             return;
@@ -1268,6 +1270,7 @@
         executeDeviceTestClass(".TrustAgentInfoTest");
     }
 
+    @FlakyTest(bugId = 141161038)
     public void testCannotRemoveUserIfRestrictionSet() throws Exception {
         // Outside of the primary user, setting DISALLOW_REMOVE_USER would not work.
         if (!mHasFeature || !canCreateAdditionalUsers(1) || mUserId != getPrimaryUser()) {
@@ -1360,6 +1363,19 @@
         executeDeviceTestClass(".PasswordSufficientInitiallyTest");
     }
 
+    public void testPasswordRequirementsApi() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+
+        executeDeviceTestMethod(".PasswordRequirementsTest",
+                "testSettingConstraintsWithLowQualityThrowsOnRPlus");
+        executeDeviceTestMethod(".PasswordRequirementsTest",
+                "testSettingConstraintsWithNumericQualityOnlyLengthAllowedOnRPlus");
+        executeDeviceTestMethod(".PasswordRequirementsTest",
+                "testSettingConstraintsWithComplexQualityAndResetWithLowerQuality");
+    }
+
     public void testGetCurrentFailedPasswordAttempts() throws Exception {
         if (!mHasFeature || !mHasSecureLockScreen) {
             return;
@@ -1609,7 +1625,7 @@
             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testPasswordMethodsLogged");
         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_QUALITY_VALUE)
                     .setAdminPackageName(DEVICE_ADMIN_PKG)
-                    .setInt(PASSWORD_QUALITY_SOMETHING)
+                    .setInt(PASSWORD_QUALITY_COMPLEX)
                     .setBoolean(false)
                     .build(),
             new DevicePolicyEventWrapper.Builder(EventId.SET_PASSWORD_MINIMUM_LENGTH_VALUE)
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTestApi25.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTestApi25.java
index cacb226..0ee24a6 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTestApi25.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTestApi25.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.devicepolicy;
 
+import android.platform.test.annotations.FlakyTest;
 import android.platform.test.annotations.RequiresDevice;
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
@@ -72,6 +73,7 @@
     }
 
     /** Additional test for resetPassword for FBE-enabled devices. */
+    @FlakyTest(bugId = 141161690)
     public void testResetPasswordFbe() throws Exception {
         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
             return;
@@ -95,6 +97,15 @@
         executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantStateAppPreMDeviceAdminPreQ");
     }
 
+    public void testPasswordRequirementsApi() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+
+        executeDeviceTestMethod(".PasswordRequirementsTest",
+                "testPasswordConstraintsDoesntThrowAndPreservesValuesPreR");
+    }
+
     protected void executeDeviceTestClass(String className) throws Exception {
         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, mUserId);
     }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerPlusProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerPlusProfileOwnerTest.java
index 42b1135..103fd96 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerPlusProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerPlusProfileOwnerTest.java
@@ -237,6 +237,7 @@
         assertTrue(getDevice().removeUser(profileUserId));
     }
 
+    @FlakyTest(bugId = 141161038)
     public void testCannotRemoveUserIfRestrictionSet() throws Exception {
         if (!mHasFeature || !canCreateAdditionalUsers(1)) {
             return;
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index 91a09d0..22c0d02 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -74,8 +74,8 @@
     private static final String ARG_NETWORK_LOGGING_BATCH_COUNT = "batchCount";
     private static final String TEST_UPDATE_LOCATION = "/data/local/tmp/cts/deviceowner";
 
-    private static final String LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK =
-            "CtsNoLaunchableActivityApp.apk";
+    private static final String LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK =
+            "CtsHasLauncherActivityApp.apk";
 
     /**
      * Copied from {@link android.app.admin.DevicePolicyManager
@@ -1018,7 +1018,7 @@
             // Install app to primary user
             installAppAsUser(BaseLauncherAppsTest.LAUNCHER_TESTS_APK, mPrimaryUserId);
             installAppAsUser(BaseLauncherAppsTest.LAUNCHER_TESTS_SUPPORT_APK, mPrimaryUserId);
-            installAppAsUser(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK, mPrimaryUserId);
+            installAppAsUser(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK, mPrimaryUserId);
 
             // Run test to check if launcher api shows hidden app
             String mSerialNumber = Integer.toString(getUserSerialNumber(USER_SYSTEM));
@@ -1028,7 +1028,7 @@
                     mPrimaryUserId, Collections.singletonMap(BaseLauncherAppsTest.PARAM_TEST_USER,
                             mSerialNumber));
         } finally {
-            getDevice().uninstallPackage(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK);
+            getDevice().uninstallPackage(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK);
             getDevice().uninstallPackage(BaseLauncherAppsTest.LAUNCHER_TESTS_SUPPORT_APK);
             getDevice().uninstallPackage(BaseLauncherAppsTest.LAUNCHER_TESTS_APK);
         }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
index bf2f6d4..2b6c245 100755
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
@@ -31,8 +31,8 @@
     private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk";
     private static final String ADMIN_RECEIVER_TEST_CLASS =
             MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver";
-    private static final String LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK =
-            "CtsNoLaunchableActivityApp.apk";
+    private static final String LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK =
+            "CtsHasLauncherActivityApp.apk";
 
     private int mProfileUserId;
     private int mParentUserId;
@@ -65,7 +65,7 @@
         if (mHasFeature) {
             removeUser(mProfileUserId);
             uninstallTestApps();
-            getDevice().uninstallPackage(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK);
+            getDevice().uninstallPackage(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK);
         }
         super.tearDown();
     }
@@ -122,15 +122,15 @@
             return;
         }
         // Install app for all users.
-        installAppAsUser(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK, mParentUserId);
-        installAppAsUser(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK, mProfileUserId);
+        installAppAsUser(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK, mParentUserId);
+        installAppAsUser(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK, mProfileUserId);
 
         // Run tests to check SimpleApp exists in both profile and main user.
         runDeviceTestsAsUser(LAUNCHER_TESTS_PKG,
                 LAUNCHER_TESTS_CLASS, "testDoPoNoTestAppInjectedActivityFound",
                 mParentUserId, Collections.singletonMap(PARAM_TEST_USER, mProfileSerialNumber));
         runDeviceTestsAsUser(LAUNCHER_TESTS_PKG,
-                LAUNCHER_TESTS_CLASS, "testNoLaunchableActivityAppHasAppDetailsActivityInjected",
+                LAUNCHER_TESTS_CLASS, "testHasLauncherActivityAppHasAppDetailsActivityInjected",
                 mParentUserId, Collections.singletonMap(PARAM_TEST_USER, mMainUserSerialNumber));
     }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LimitAppIconHidingTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LimitAppIconHidingTest.java
index 09d2541..fa92065 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LimitAppIconHidingTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LimitAppIconHidingTest.java
@@ -23,10 +23,10 @@
  */
 public class LimitAppIconHidingTest extends BaseLauncherAppsTest {
 
-    private static final String LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK =
-            "CtsNoLaunchableActivityApp.apk";
-    private static final String LAUNCHER_TESTS_NO_COMPONENT_APK =
-            "CtsNoComponentApp.apk";
+    private static final String LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK =
+            "CtsHasLauncherActivityApp.apk";
+    private static final String LAUNCHER_TESTS_NO_LAUNCHER_ACTIVITY_APK =
+            "CtsNoLauncherActivityApp.apk";
     private static final String LAUNCHER_TESTS_NO_PERMISSION_APK =
             "CtsNoPermissionApp.apk";
 
@@ -58,8 +58,8 @@
     @Override
     protected void installTestApps(int userId) throws Exception {
         super.installTestApps(mCurrentUserId);
-        installAppAsUser(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK, mCurrentUserId);
-        installAppAsUser(LAUNCHER_TESTS_NO_COMPONENT_APK, mCurrentUserId);
+        installAppAsUser(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK, mCurrentUserId);
+        installAppAsUser(LAUNCHER_TESTS_NO_LAUNCHER_ACTIVITY_APK, mCurrentUserId);
         installAppAsUser(LAUNCHER_TESTS_NO_PERMISSION_APK, mCurrentUserId);
     }
 
@@ -67,16 +67,16 @@
     protected void uninstallTestApps() throws Exception {
         super.uninstallTestApps();
         getDevice().uninstallPackage(LAUNCHER_TESTS_NO_PERMISSION_APK);
-        getDevice().uninstallPackage(LAUNCHER_TESTS_NO_COMPONENT_APK);
-        getDevice().uninstallPackage(LAUNCHER_TESTS_NO_LAUNCHABLE_ACTIVITY_APK);
+        getDevice().uninstallPackage(LAUNCHER_TESTS_NO_LAUNCHER_ACTIVITY_APK);
+        getDevice().uninstallPackage(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK);
     }
 
-    public void testNoLaunchableActivityAppHasAppDetailsActivityInjected() throws Exception {
+    public void testHasLauncherActivityAppHasAppDetailsActivityInjected() throws Exception {
         if (!mHasLauncherApps) {
             return;
         }
         runDeviceTestsAsUser(LAUNCHER_TESTS_PKG,
-                LAUNCHER_TESTS_CLASS, "testNoLaunchableActivityAppHasAppDetailsActivityInjected",
+                LAUNCHER_TESTS_CLASS, "testHasLauncherActivityAppHasAppDetailsActivityInjected",
                 mCurrentUserId, Collections.singletonMap(PARAM_TEST_USER, mSerialNumber));
     }
 
@@ -89,12 +89,12 @@
                 mCurrentUserId, Collections.singletonMap(PARAM_TEST_USER, mSerialNumber));
     }
 
-    public void testNoComponentAppNotInjected() throws Exception {
+    public void testNoLauncherActivityAppNotInjected() throws Exception {
         if (!mHasLauncherApps) {
             return;
         }
         runDeviceTestsAsUser(LAUNCHER_TESTS_PKG,
-                LAUNCHER_TESTS_CLASS, "testNoComponentAppNotInjected",
+                LAUNCHER_TESTS_CLASS, "testNoLauncherActivityAppNotInjected",
                 mCurrentUserId, Collections.singletonMap(PARAM_TEST_USER, mSerialNumber));
     }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileCrossProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileCrossProfileTest.java
index 83bcf5b..be2ce33 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileCrossProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileCrossProfileTest.java
@@ -368,8 +368,6 @@
                     "testPrimaryProfile_canAccessWorkInstancesSearchByDay", mParentUserId);
             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
                     "testPrimaryProfile_getExceptionWhenQueryNonWhitelistedColumns", mParentUserId);
-            runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
-                    "testViewEventCrossProfile_intentReceivedWhenWhitelisted", mParentUserId);
         } finally {
             // Cleanup.
             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
@@ -411,8 +409,6 @@
                     "testPrimaryProfile_canAccessWorkInstancesSearchByDay", mParentUserId);
             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
                     "testPrimaryProfile_getExceptionWhenQueryNonWhitelistedColumns", mParentUserId);
-            runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
-                    "testViewEventCrossProfile_intentReceivedWhenWhitelisted", mParentUserId);
         } finally {
             // Cleanup.
             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileProvisioningTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileProvisioningTest.java
index 93a17e0..9734f97 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileProvisioningTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileProvisioningTest.java
@@ -15,6 +15,8 @@
  */
 package com.android.cts.devicepolicy;
 
+import android.platform.test.annotations.FlakyTest;
+
 public class ManagedProfileProvisioningTest extends BaseDevicePolicyTest {
     private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile";
     private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk";
@@ -61,6 +63,7 @@
                 "testIsManagedProfile", mProfileUserId);
     }
 
+    @FlakyTest(bugId = 127275983)
     public void testEXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE() throws Exception {
         if (!mHasFeature) {
             return;
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
index 0b837de..3e3a723 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
@@ -108,7 +108,7 @@
         super.testCaCertManagement();
     }
 
-    @FlakyTest
+    @FlakyTest(bugId = 141161038)
     @Override
     public void testCannotRemoveUserIfRestrictionSet() throws Exception {
         super.testCannotRemoveUserIfRestrictionSet();
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java
index 74f9c21..8e26ae4 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.devicepolicy;
 
+import android.platform.test.annotations.FlakyTest;
 import android.platform.test.annotations.LargeTest;
 
 import com.android.cts.devicepolicy.annotations.PermissionsTest;
@@ -79,6 +80,7 @@
      */
     @Override
     @LargeTest
+    @FlakyTest(bugId = 141161690)
     public void testResetPasswordFbe() throws Exception {
         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
             return;
diff --git a/hostsidetests/edi/Android.bp b/hostsidetests/edi/Android.bp
index d9a907e..2a8ac6e 100644
--- a/hostsidetests/edi/Android.bp
+++ b/hostsidetests/edi/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     libs: [
         "cts-tradefed",
diff --git a/hostsidetests/inputmethodservice/common/Android.bp b/hostsidetests/inputmethodservice/common/Android.bp
index feb59a3..6480839 100644
--- a/hostsidetests/inputmethodservice/common/Android.bp
+++ b/hostsidetests/inputmethodservice/common/Android.bp
@@ -22,7 +22,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp
index 7139b91..30bf5cb 100644
--- a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp
@@ -30,7 +30,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
     min_sdk_version: "19",
diff --git a/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp b/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp
index fce63b4..e2f7105 100644
--- a/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp
@@ -22,7 +22,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
     min_sdk_version: "28",
diff --git a/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp b/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp
index 765fe2d..43ce201 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp
@@ -25,7 +25,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
     min_sdk_version: "19",
diff --git a/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp b/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp
index e8f865f..61480a2 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp
@@ -25,7 +25,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
     min_sdk_version: "19",
diff --git a/hostsidetests/inputmethodservice/deviceside/provider/Android.bp b/hostsidetests/inputmethodservice/deviceside/provider/Android.bp
index d9363e8..3d5a727 100644
--- a/hostsidetests/inputmethodservice/deviceside/provider/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/provider/Android.bp
@@ -25,7 +25,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
     min_sdk_version: "26",
diff --git a/hostsidetests/inputmethodservice/hostside/Android.bp b/hostsidetests/inputmethodservice/hostside/Android.bp
index 5e99fdf..35bec6d 100644
--- a/hostsidetests/inputmethodservice/hostside/Android.bp
+++ b/hostsidetests/inputmethodservice/hostside/Android.bp
@@ -21,7 +21,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     libs: [
         "compatibility-host-util",
diff --git a/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java b/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java
index aa8a5ed..ea4f0c2 100644
--- a/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java
+++ b/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java
@@ -64,7 +64,6 @@
               DataOutputStream dos = new DataOutputStream(ls.getOutputStream());
               dos.writeUTF(s);
               dos.flush();
-              ls.shutdownOutput();
               // Wait for the other end to close the connection.
               while (-1 != ls.getInputStream().read()) {}
           } catch (IOException e) {
diff --git a/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java b/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
index 059091f..662efa6 100644
--- a/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
+++ b/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
@@ -254,16 +254,16 @@
                     + "/android.jvmti.JvmtiActivity";
 
             // Don't try to parse the output. We'll get data from the socket or a timeout if it
-            // didn't start.
+            // didn't start. For some reason this command sometimes fails. Retry up to ten times to
+            // make the test less flaky.
             device.executeShellCommand(attachCmd, NullOutputReceiver.getReceiver(), 10,
-                  TimeUnit.SECONDS, 1);
+                  TimeUnit.SECONDS, 10);
             // Wait for startup up to 30 seconds.
             ss.setSoTimeout(30000);
             try (Socket s = ss.accept()) {
                 DataInputStream dis = new DataInputStream(s.getInputStream());
                 String res = dis.readUTF();
                 s.shutdownInput();
-                s.shutdownOutput();
                 if (!res.trim().equals("SUCCESS")) {
                     throw new RuntimeException("Failed test due to remote error: " + res);
                 }
diff --git a/hostsidetests/media/Android.bp b/hostsidetests/media/Android.bp
index e6b114a..b6b1a32 100644
--- a/hostsidetests/media/Android.bp
+++ b/hostsidetests/media/Android.bp
@@ -26,7 +26,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     libs: [
diff --git a/hostsidetests/media/app/MediaSessionTest/Android.bp b/hostsidetests/media/app/MediaSessionTest/Android.bp
index 07d1c35..3b2e94c 100644
--- a/hostsidetests/media/app/MediaSessionTest/Android.bp
+++ b/hostsidetests/media/app/MediaSessionTest/Android.bp
@@ -19,7 +19,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     srcs: [
         "src/**/*.java",
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/Android.bp b/hostsidetests/media/app/MediaSessionTestHelper/Android.bp
index 31e2d54..8645ab0 100644
--- a/hostsidetests/media/app/MediaSessionTestHelper/Android.bp
+++ b/hostsidetests/media/app/MediaSessionTestHelper/Android.bp
@@ -24,7 +24,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "current",
 }
diff --git a/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/ReportProcessor.java b/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/ReportProcessor.java
index 9553928..b334b0b 100644
--- a/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/ReportProcessor.java
+++ b/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/ReportProcessor.java
@@ -16,6 +16,7 @@
 
 package android.media.cts.bitstreams;
 
+import com.android.tradefed.config.Configuration;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
@@ -156,6 +157,9 @@
         for (Entry<String, String> e : getArgs().entrySet()) {
             instrTest.addInstrumentationArg(e.getKey(), e.getValue());
         }
+        // AndroidJUnitTest requires a IConfiguration to work properly, add a stub to this
+        // implementation to avoid an NPE.
+        instrTest.setConfiguration(new Configuration("stub", "stub"));
         instrTest.run(new MediaBitstreamsListener());
 
         return checkFile(reportKey);
diff --git a/hostsidetests/multiuser/Android.bp b/hostsidetests/multiuser/Android.bp
index cc4bd81..ce653dd 100644
--- a/hostsidetests/multiuser/Android.bp
+++ b/hostsidetests/multiuser/Android.bp
@@ -21,6 +21,7 @@
         "cts-tradefed",
         "tradefed",
         "platform-test-annotations-host",
+	"compatibility-host-util",
     ],
     // tag this module as a cts test artifact
     test_suites: [
diff --git a/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersPermissionTest.java b/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersPermissionTest.java
index 41cbeab..fc385b1 100644
--- a/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersPermissionTest.java
+++ b/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersPermissionTest.java
@@ -17,6 +17,7 @@
 
 import static com.android.tradefed.log.LogUtil.CLog;
 
+import com.android.compatibility.common.util.CddTest;
 import com.android.ddmlib.Log;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
@@ -69,6 +70,7 @@
                 + "command output: " + output, isErrorOutput);
     }
 
+    @CddTest(requirement="9.5/A-1-3")
     @Test
     public void testCanCreateGuestUserWhenUserLimitReached() throws Exception {
         if (!isAutomotiveDevice()) {
diff --git a/hostsidetests/multiuser/src/android/host/multiuser/SecondaryUsersTest.java b/hostsidetests/multiuser/src/android/host/multiuser/SecondaryUsersTest.java
index 1f4ab36..d4a6ef2 100644
--- a/hostsidetests/multiuser/src/android/host/multiuser/SecondaryUsersTest.java
+++ b/hostsidetests/multiuser/src/android/host/multiuser/SecondaryUsersTest.java
@@ -15,6 +15,7 @@
  */
 package android.host.multiuser;
 
+import com.android.compatibility.common.util.CddTest;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import java.util.concurrent.TimeUnit;
@@ -31,6 +32,7 @@
 
     private static final long POLL_INTERVAL_MS = 100;
 
+    @CddTest(requirement="9.5/A-1-2")
     @Test
     public void testSwitchToSecondaryUserBeforeBootComplete() throws Exception {
         if (!isAutomotiveDevice() || !mSupportsMultiUser) {
@@ -58,4 +60,4 @@
         }
         Assert.assertTrue("Must switch to secondary user before boot complete", isUserSecondary);
     }
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/os/Android.bp b/hostsidetests/os/Android.bp
index c359656..bd2d63e 100644
--- a/hostsidetests/os/Android.bp
+++ b/hostsidetests/os/Android.bp
@@ -27,6 +27,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/app/Android.bp b/hostsidetests/os/app/Android.bp
index 384ab55..f8881a1 100644
--- a/hostsidetests/os/app/Android.bp
+++ b/hostsidetests/os/app/Android.bp
@@ -22,6 +22,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/app/AndroidManifest.xml b/hostsidetests/os/app/AndroidManifest.xml
index fa9d9ae..88791ea 100755
--- a/hostsidetests/os/app/AndroidManifest.xml
+++ b/hostsidetests/os/app/AndroidManifest.xml
@@ -19,9 +19,16 @@
     package="android.os.app"
     android:targetSandboxVersion="2">
 
+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+
     <application>
         <activity android:name=".TestNonExported"
                 android:exported="false" />
+
+        <service android:name=".TestFgService"
+                android:exported="true" />
+
     </application>
+
 </manifest>
 
diff --git a/hostsidetests/os/app/src/android/os/app/TestFgService.java b/hostsidetests/os/app/src/android/os/app/TestFgService.java
new file mode 100644
index 0000000..3548105
--- /dev/null
+++ b/hostsidetests/os/app/src/android/os/app/TestFgService.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2019 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.os.app;
+
+import android.app.Notification;
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.Process;
+import android.util.Log;
+
+public class TestFgService extends Service {
+    private static final String TAG = "TestFgService";
+
+    // intentionally invalid resource configuration
+    private static final int NOTIFICATION_ID = 5038;
+    private static final String CHANNEL = "fgservice";
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        Log.i(TAG, "onStartCommand() called");
+        Notification notification = new Notification.Builder(this, CHANNEL)
+                .setContentTitle("Foreground service")
+                .setContentText("Ongoing test app foreground service is live")
+                .setSmallIcon(NOTIFICATION_ID)
+                .build();
+
+        Log.i(TAG, "TestFgService starting foreground: pid=" + Process.myPid());
+        startForeground(NOTIFICATION_ID, notification);
+
+        return START_NOT_STICKY;
+    }
+}
\ No newline at end of file
diff --git a/hostsidetests/os/src/android/os/cts/OsHostTests.java b/hostsidetests/os/src/android/os/cts/OsHostTests.java
index c557c9e..8e3f5c5 100644
--- a/hostsidetests/os/src/android/os/cts/OsHostTests.java
+++ b/hostsidetests/os/src/android/os/cts/OsHostTests.java
@@ -22,14 +22,17 @@
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.InputStreamSource;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IAbi;
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
 import com.android.tradefed.util.AbiUtils;
 
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.InputStreamReader;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Scanner;
@@ -38,12 +41,19 @@
 
 public class OsHostTests extends DeviceTestCase implements IBuildReceiver, IAbiReceiver {
     private static final String TEST_APP_PACKAGE = "android.os.app";
-    private static final String TEST_NON_EXPORTED_ACTIVITY_CLASS = "TestNonExported";
 
+    private static final String TEST_NON_EXPORTED_ACTIVITY_CLASS = "TestNonExported";
     private static final String START_NON_EXPORTED_ACTIVITY_COMMAND = String.format(
             "am start -n %s/%s.%s",
             TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_NON_EXPORTED_ACTIVITY_CLASS);
 
+    private static final String TEST_FG_SERVICE_CLASS = "TestFgService";
+    private static final String START_FG_SERVICE_COMMAND = String.format(
+            "am start-foreground-service -n %s/%s.%s",
+            TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_FG_SERVICE_CLASS);
+    private static final String FILTER_FG_SERVICE_REGEXP =
+            "TestFgService starting foreground: pid=([0-9]*)";
+
     // Testing the intent filter verification mechanism
     private static final String HOST_VERIFICATION_APK = "CtsHostLinkVerificationApp.apk";
     private static final String HOST_VERIFICATION_PKG = "com.android.cts.openlinksskeleton";
@@ -104,6 +114,40 @@
         }
     }
 
+    /**
+     * Test behavior of malformed Notifications w.r.t. foreground services
+     * @throws Exception
+     */
+    @AppModeFull(reason = "Instant apps may not start foreground services")
+    public void testForegroundServiceBadNotification() throws Exception {
+        final Pattern pattern = Pattern.compile(FILTER_FG_SERVICE_REGEXP);
+
+        mDevice.clearLogcat();
+        mDevice.executeShellCommand(START_FG_SERVICE_COMMAND);
+        Thread.sleep(2500);
+
+        String pid = null;
+        try (InputStreamSource logSource = mDevice.getLogcat()) {
+            InputStreamReader streamReader = new InputStreamReader(logSource.createInputStream());
+            BufferedReader logReader = new BufferedReader(streamReader);
+
+            String line;
+            while ((line = logReader.readLine()) != null) {
+                Matcher matcher = pattern.matcher(line);
+                if (matcher.find()) {
+                    pid = matcher.group(1);
+                    break;
+                }
+            }
+        }
+        assertTrue("Didn't find test service statement in logcat", pid != null);
+
+        final String procStr = "/proc/" + pid;
+        final String lsOut = mDevice.executeShellCommand("ls -d " + procStr).trim();
+        assertTrue("Looking for nonexistence of service process " + pid,
+                lsOut.contains("No such file"));
+    }
+
     public void testIntentFilterHostValidation() throws Exception {
         String line = null;
         try {
diff --git a/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp b/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp
index fb22fad..36f2605 100644
--- a/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp
+++ b/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp
@@ -23,6 +23,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/test-apps/PowerManagerTestApp/Android.mk b/hostsidetests/os/test-apps/PowerManagerTestApp/Android.mk
index 3c6371f..e58a3d2 100644
--- a/hostsidetests/os/test-apps/PowerManagerTestApp/Android.mk
+++ b/hostsidetests/os/test-apps/PowerManagerTestApp/Android.mk
@@ -26,6 +26,6 @@
 LOCAL_PACKAGE_NAME := CtsHostPowerManagerTestApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp b/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp
index df61619..990a95d 100644
--- a/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp
+++ b/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp
@@ -24,6 +24,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp
index 1e78ba5..c7d2556 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp
@@ -28,6 +28,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp
index b4537c4..080fddf 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp
@@ -24,6 +24,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp
index 4d4f7c9..175f5c4 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp
@@ -24,6 +24,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp
index 1a9c933..be8f65d 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp
@@ -24,7 +24,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     optimize: {
         enabled: false,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp
index 0904361..bc4a2e1 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     aaptflags: ["--shared-lib"],
     export_package_resources: true,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp
index c866c6f..e578b5d 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp
@@ -22,7 +22,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     aaptflags: ["--shared-lib"],
     export_package_resources: true,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp
index 8989e22..c46e35c 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     optimize: {
         enabled: false,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp
index d77f030..a3b5b5b 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     aaptflags: ["--shared-lib"],
     export_package_resources: true,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp
index 9048774..6d42bb0 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     aaptflags: ["--shared-lib"],
     export_package_resources: true,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp
index 253aa34..1ecd6c4 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp
@@ -25,7 +25,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     optimize: {
         enabled: false,
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp
index 0812dc0..88c0fb8 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     optimize: {
         enabled: false,
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp b/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp
index 578c338..97195fb 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp
@@ -26,7 +26,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
 
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp
index c76e6d8..5c6e58a 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     optimize: {
         enabled: false,
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp
index 005553b..8a44700 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp
@@ -23,7 +23,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     optimize: {
         enabled: false,
diff --git a/hostsidetests/rollback/Android.bp b/hostsidetests/rollback/Android.bp
index 817a339..99ac9310 100644
--- a/hostsidetests/rollback/Android.bp
+++ b/hostsidetests/rollback/Android.bp
@@ -27,6 +27,7 @@
     static_libs: ["androidx.test.rules", "cts-rollback-lib", "cts-install-lib"],
     manifest : "app/AndroidManifest.xml",
     java_resources:  [
+        ":ApexKeyRotationTestV2_SignedBobRot",
         ":StagedInstallTestApexV2",
         ":StagedInstallTestApexV3",
     ],
diff --git a/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java b/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java
index 8baf21f..5c8f759 100644
--- a/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java
+++ b/hostsidetests/rollback/app/src/com/android/cts/rollback/host/app/HostTestHelper.java
@@ -42,6 +42,9 @@
  */
 @RunWith(JUnit4.class)
 public class HostTestHelper {
+    private static final TestApp Apex2SignedBobRot = new TestApp(
+            "Apex2SignedBobRot", TestApp.Apex, 2, /*isApex*/true,
+            "com.android.apex.cts.shim.v2_signed_bob_rot.apex");
 
     /**
      * Adopts common permissions needed to test rollbacks.
@@ -369,4 +372,41 @@
         assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(3);
         assertThat(RollbackUtils.getAvailableRollback(TestApp.Apex)).isNull();
     }
+
+    /**
+     * Test rollback with key downgrade for apex only
+     */
+    @Test
+    public void testApexKeyRotation_EnableRollback() throws Exception {
+        assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+        Install.single(Apex2SignedBobRot).setStaged().setEnableRollback().commit();
+    }
+
+    @Test
+    public void testApexKeyRotation_CommitRollback() throws Exception {
+        assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(2);
+        RollbackInfo available = RollbackUtils.getAvailableRollback(TestApp.Apex);
+        assertThat(available).isStaged();
+        assertThat(available).packagesContainsExactly(
+                Rollback.from(Apex2SignedBobRot).to(TestApp.Apex1));
+
+        RollbackUtils.rollback(available.getRollbackId(), Apex2SignedBobRot);
+        RollbackInfo committed = RollbackUtils.getCommittedRollbackById(available.getRollbackId());
+        assertThat(committed).isNotNull();
+        assertThat(committed).isStaged();
+        assertThat(committed).packagesContainsExactly(
+                Rollback.from(Apex2SignedBobRot).to(TestApp.Apex1));
+        assertThat(committed).causePackagesContainsExactly(Apex2SignedBobRot);
+        assertThat(committed.getCommittedSessionId()).isNotEqualTo(-1);
+
+        // Note: The app is not rolled back until after the rollback is staged
+        // and the device has been rebooted.
+        InstallUtils.waitForSessionReady(committed.getCommittedSessionId());
+        assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(2);
+    }
+
+    @Test
+    public void testApexKeyRotation_CofirmRollback() throws Exception {
+        assertThat(InstallUtils.getInstalledVersion(TestApp.Apex)).isEqualTo(1);
+    }
 }
diff --git a/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java b/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java
index 736b47c..9f6238f 100644
--- a/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java
+++ b/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java
@@ -20,6 +20,7 @@
 
 import static org.junit.Assume.assumeTrue;
 
+import com.android.ddmlib.Log;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
@@ -35,6 +36,8 @@
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class RollbackManagerHostTest extends BaseHostJUnit4Test {
 
+    private static final String TAG = "RollbackManagerHostTest";
+
     private static final String SHIM_APEX_PACKAGE_NAME = "com.android.apex.cts.shim";
     private static final String TEST_APK_PACKAGE_NAME = "com.android.cts.install.lib.testapp.A";
 
@@ -68,17 +71,16 @@
             // Device doesn't support updating apex. Nothing to uninstall.
             return;
         }
-        final ITestDevice.ApexInfo shimApex = getShimApex();
-        if (shimApex.versionCode == 1) {
-            // System version is active, skipping uninstalling active apex and rebooting the device.
-            return;
-        }
-        // Non system version is active, need to uninstall it and reboot the device.
         final String errorMessage = getDevice().uninstallPackage(SHIM_APEX_PACKAGE_NAME);
-        if (errorMessage != null) {
-            throw new AssertionError("Failed to uninstall " + shimApex);
+        if (errorMessage == null) {
+            Log.i(TAG, "Uninstalling shim apex");
+            getDevice().reboot();
+        } else {
+            // Most likely we tried to uninstall system version and failed. It should be fine to
+            // continue tests.
+            // TODO(b/140813980): use ApexInfo.sourceDir to decide whenever to issue an uninstall.
+            Log.w(TAG, "Failed to uninstall shim APEX : " + errorMessage);
         }
-        getDevice().reboot();
         assertThat(getShimApex().versionCode).isEqualTo(1L);
     }
 
@@ -177,4 +179,18 @@
         run("testApexRollbackExpirationConfirmExpiration");
     }
 
+    /**
+     * Tests staged rollbacks involving apex with rotated keys.
+     */
+    @Test
+    public void testApexKeyRotationStagedRollback() throws Exception {
+        assumeTrue("Device does not support updating APEX", isApexUpdateSupported());
+
+        run("testApexKeyRotation_EnableRollback");
+        getDevice().reboot();
+        run("testApexKeyRotation_CommitRollback");
+        getDevice().reboot();
+        run("testApexKeyRotation_CofirmRollback");
+    }
+
 }
diff --git a/hostsidetests/sample/Android.bp b/hostsidetests/sample/Android.bp
index 489bedc..72c1b0d 100644
--- a/hostsidetests/sample/Android.bp
+++ b/hostsidetests/sample/Android.bp
@@ -21,7 +21,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     libs: [
         "cts-tradefed",
diff --git a/hostsidetests/securitybulletin/AndroidTest.xml b/hostsidetests/securitybulletin/AndroidTest.xml
index 44eedc1..5fbfbd5 100644
--- a/hostsidetests/securitybulletin/AndroidTest.xml
+++ b/hostsidetests/securitybulletin/AndroidTest.xml
@@ -43,6 +43,12 @@
         <option name="push" value="CVE-2016-8432->/data/local/tmp/CVE-2016-8432" />
         <option name="push" value="CVE-2016-8434->/data/local/tmp/CVE-2016-8434" />
 
+        <!--__________________-->
+        <!-- Bulletin 2016-02 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-0811->/data/local/tmp/CVE-2016-0811" />
+
+        <!--__________________-->
         <!-- Bulletin 2016-04 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
         <option name="push" value="CVE-2016-2412->/data/local/tmp/CVE-2016-2412" />
@@ -200,6 +206,7 @@
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="OomCatcher.apk" />
+        <option name="test-file-name" value="MainlineModuleDetector.apk" />
     </target_preparer>
 
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/Android.mk
new file mode 100644
index 0000000..6a0317b
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/Android.mk
@@ -0,0 +1,36 @@
+# Copyright (C) 2019 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2016-0811
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_SHARED_LIBRARIES := \
+    libbinder \
+    libutils \
+    libmedia \
+    libmediadrm \
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts sts vts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS += -Wall -Werror
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/poc.cpp
new file mode 100644
index 0000000..b34166f
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/poc.cpp
@@ -0,0 +1,73 @@
+/**
+ * Copyright (C) 2019 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.
+ */
+#include <binder/IServiceManager.h>
+#include <binder/MemoryDealer.h>
+#include <media/ICrypto.h>
+#include <media/IDrm.h>
+#include <media/IMediaDrmService.h>
+
+using namespace android;
+
+template <typename T>
+void mediaPoc(BpInterface<T> *sit) {
+  Parcel data, reply;
+  data.writeInterfaceToken(sit->getInterfaceDescriptor());
+  data.writeInt32(0);
+  data.writeInt32(0);
+  static const uint8_t kDummy[16] = {0};
+  data.write(kDummy, 16);
+  data.write(kDummy, 16);
+  const int wsize = 16 * 1024;
+  sp<MemoryDealer> dealer = new MemoryDealer(wsize);
+  sp<IMemory> memory = dealer->allocate(wsize);
+  data.writeInt32(wsize);
+  data.writeStrongBinder(IInterface::asBinder(memory));
+  const int ss = 0x1;
+  data.writeInt32(0xffffff00);
+  data.writeInt32(ss);
+  CryptoPlugin::SubSample samples[ss];
+  for (int i = 0; i < ss; i++) {
+    samples[i].mNumBytesOfEncryptedData = 0;
+    samples[i].mNumBytesOfClearData = wsize;
+  }
+  data.write(samples, sizeof(CryptoPlugin::SubSample) * ss);
+  char out[wsize] = {0};
+  reply.read(out, wsize);
+}
+
+static const uint8_t kClearKeyUUID[16] = {0x10, 0x77, 0xEF, 0xEC, 0xC0, 0xB2,
+                                          0x4D, 0x02, 0xAC, 0xE3, 0x3C, 0x1E,
+                                          0x52, 0xE2, 0xFB, 0x4B};
+
+int main(void) {
+  status_t st;
+  sp<ICrypto> crypto =
+      interface_cast<IMediaDrmService>(
+          defaultServiceManager()->getService(String16("media.drm")))
+          ->makeCrypto();
+
+  sp<IDrm> drm = interface_cast<IMediaDrmService>(
+                     defaultServiceManager()->getService(String16("media.drm")))
+                     ->makeDrm();
+
+  Vector<uint8_t> sess;
+  st = drm->createPlugin(kClearKeyUUID, (String8) "test");
+  st = drm->openSession(DrmPlugin::kSecurityLevelMax, sess);
+  st = crypto->createPlugin(kClearKeyUUID, sess.array(), sess.size());
+  BpInterface<ICrypto> *sit = static_cast<BpInterface<ICrypto> *>(crypto.get());
+  mediaPoc(sit);
+  return 0;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/poc.cpp
index 7b67095..1e55834 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/poc.cpp
@@ -80,7 +80,7 @@
   sp<MemoryDealer> dealerIn = new MemoryDealer(inSize);
   IOMX::buffer_id inBufferId = 0;
   memory = dealerIn->allocate(inSize);
-  if (memory.get() == nullptr || memory->pointer() == nullptr) {
+  if (memory.get() == nullptr || memory->unsecurePointer() == nullptr) {
     ALOGE("memory allocate failed for port index 0, err: %d", err);
     mOMXNode->freeNode();
     client.disconnect();
@@ -93,7 +93,7 @@
    */
 
   OMXBuffer omxInBuf(memory);
-  memset(memory->pointer(), 0xCF, inSize);
+  memset(memory->unsecurePointer(), 0xCF, inSize);
   err = mOMXNode->useBuffer(0, omxInBuf, &inBufferId);
   ALOGI("useBuffer, port index 0, err: %d", err);
 
@@ -106,7 +106,7 @@
   sp<MemoryDealer> dealerOut = new MemoryDealer(outSize);
   IOMX::buffer_id outBufferId = 0;
   memory = dealerOut->allocate(outSize);
-  if (memory.get() == nullptr || memory->pointer() == nullptr) {
+  if (memory.get() == nullptr || memory->unsecurePointer() == nullptr) {
     ALOGE("memory allocate failed for port index 1, err: %d", err);
     mOMXNode->freeNode();
     client.disconnect();
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/HostsideMainlineModuleDetector.java b/hostsidetests/securitybulletin/src/android/security/cts/HostsideMainlineModuleDetector.java
new file mode 100644
index 0000000..e62a7b3
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/HostsideMainlineModuleDetector.java
@@ -0,0 +1,44 @@
+package android.security.cts;
+
+import com.android.ddmlib.Log;
+
+import com.google.common.collect.ImmutableSet;
+
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class HostsideMainlineModuleDetector {
+    private static final String LOG_TAG = "MainlineModuleDetector";
+
+    private SecurityTestCase context;
+
+    private static ImmutableSet<String> playManagedModules;
+
+    HostsideMainlineModuleDetector(SecurityTestCase context) {
+        this.context = context;
+    }
+
+    synchronized Set<String> getPlayManagedModules() throws Exception {
+        if (playManagedModules == null) {
+            AdbUtils.runCommandLine("logcat -c", context.getDevice());
+            String output = AdbUtils.runCommandLine(
+                    "am start com.android.cts.mainlinemoduledetector/.MainlineModuleDetector",
+                    context.getDevice());
+            Log.logAndDisplay(Log.LogLevel.INFO, LOG_TAG,
+                    "am output: " + output);
+            Thread.sleep(5 * 1000L);
+            String logcat = AdbUtils.runCommandLine("logcat -d -s MainlineModuleDetector:I",
+                    context.getDevice());
+            Log.logAndDisplay(Log.LogLevel.INFO, LOG_TAG,
+                    "Found logcat output: " + logcat);
+            Matcher matcher = Pattern.compile("Play managed modules are: <(.*?)>").matcher(logcat);
+            if (matcher.find()) {
+                playManagedModules = ImmutableSet.copyOf(matcher.group(1).split(","));
+            } else {
+                playManagedModules = ImmutableSet.of();
+            }
+        }
+        return playManagedModules;
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_02.java
old mode 100755
new mode 100644
similarity index 61%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to hostsidetests/securitybulletin/src/android/security/cts/Poc16_02.java
index a48cb1d..4a638a9
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_02.java
@@ -1,5 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
+/**
  * Copyright (C) 2019 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,13 +12,18 @@
  * 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.
- -->
+ */
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
+package android.security.cts;
 
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
+import android.platform.test.annotations.SecurityTest;
 
-</manifest>
-
+public class Poc16_02 extends SecurityTestCase {
+    /**
+     *  b/25800375
+     */
+    @SecurityTest(minPatchLevel = "2016-02")
+    public void testPocCVE_2016_0811() throws Exception {
+        AdbUtils.runPocAssertNoCrashes("CVE-2016-0811", getDevice(), "mediaserver");
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
index 95a7162..b270c69 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
@@ -37,21 +37,11 @@
   }
 
   /**
-   * CVE-2018-5892
+   *  b/73172817
    */
-  @SecurityTest(minPatchLevel = "2018-06")
-  public void testPocCVE_2018_5892() throws Exception {
-    String result = AdbUtils.runCommandLine(
-        "pm list package com.emoji.keyboard.touchpal", getDevice());
-    assertFalse(result.contains("com.emoji.keyboard.touchpal"));
+  @SecurityTest
+  public void testPocCVE_2018_9344() throws Exception {
+      AdbUtils.runPocAssertNoCrashes(
+          "CVE-2018-9344", getDevice(), "android\\.hardware\\.drm@\\d\\.\\d-service");
   }
-
-    /**
-     *  b/73172817
-     */
-    @SecurityTest
-    public void testPocCVE_2018_9344() throws Exception {
-        AdbUtils.runPocAssertNoCrashes(
-            "CVE-2018-9344", getDevice(), "android\\.hardware\\.drm@\\d\\.\\d-service");
-    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java
index 796119d..1615947 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java
@@ -50,4 +50,15 @@
         int code = AdbUtils.runProxyAutoConfig("CVE-2019-2047", getDevice());
         assertTrue(code != 139); // 128 + signal 11
     }
+
+    /**
+     * CVE-2019-2257
+     */
+    @SecurityTest(minPatchLevel = "2019-05")
+    public void testPocCVE_2019_2257() throws Exception {
+        String result = AdbUtils.runCommandLine(
+                                "dumpsys package com.qualcomm.qti.telephonyservice", getDevice());
+        assertFalse(result.contains(
+                            "permission com.qualcomm.permission.USE_QTI_TELEPHONY_SERVICE"));
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
index 479f18d..0939627 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
@@ -36,6 +36,7 @@
     private long kernelStartTime;
 
     private HostsideOomCatcher oomCatcher = new HostsideOomCatcher(this);
+    private HostsideMainlineModuleDetector mainlineModuleDetector = new HostsideMainlineModuleDetector(this);
 
     /**
      * Waits for device to be online, marks the most recent boottime of the device
@@ -210,4 +211,21 @@
     public HostsideOomCatcher getOomCatcher() {
         return oomCatcher;
     }
+
+    /**
+     * Return true if a module is play managed.
+     *
+     * Example of skipping a test based on mainline modules:
+     *  <pre>
+     *  @Test
+     *  public void testPocCVE_1234_5678() throws Exception {
+     *      // This will skip the test if MODULE_METADATA mainline module is play managed.
+     *      assumeFalse(moduleIsPlayManaged("com.google.android.captiveportallogin"));
+     *      // Do testing...
+     *  }
+     *  * </pre>
+     */
+    boolean moduleIsPlayManaged(String modulePackageName) throws Exception {
+        return mainlineModuleDetector.getPlayManagedModules().contains(modulePackageName);
+    }
 }
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp
index 81276ff..ee3ca9b 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp
@@ -25,7 +25,7 @@
         "general-tests",
     ],
     static_libs: [
-        "CtsShortcutBackupPublisher4oldLib",
+        "CtsShortcutBackupLauncher4oldLib",
         "compatibility-device-util-axt",
     ],
 }
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp
index 89a4ab9..22b4be5 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp
@@ -26,13 +26,14 @@
         "general-tests",
     ],
     static_libs: [
-        "CtsShortcutBackupPublisher4oldLib",
+        "CtsShortcutBackupLauncher4oldLib",
         "compatibility-device-util-axt",
     ],
 }
 
 android_library {
     name: "CtsShortcutBackupLauncher4oldLib",
+    manifest: "AndroidManifest-lib.xml",
     defaults: [
         "cts_defaults",
         "hostsidetests-shortcuts-deviceside-defaults",
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/hostsidetests/shortcuts/deviceside/backup/launcher4old/AndroidManifest-lib.xml
old mode 100755
new mode 100644
similarity index 77%
rename from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
rename to hostsidetests/shortcuts/deviceside/backup/launcher4old/AndroidManifest-lib.xml
index a48cb1d..034ad97
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher4old/AndroidManifest-lib.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2017 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.
@@ -16,10 +16,7 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
-
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
-
+    package="android.content.pm.cts.shortcut.backup.launcher4"
+    android:versionCode="10">
 </manifest>
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp
index 1a8929e..9906d30 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp
@@ -33,6 +33,7 @@
 
 android_library {
     name: "CtsShortcutBackupPublisher4oldLib",
+    manifest: "AndroidManifest-lib.xml",
     srcs: ["src/**/*.java"],
     defaults: [
         "cts_defaults",
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/hostsidetests/shortcuts/deviceside/backup/publisher4old/AndroidManifest-lib.xml
old mode 100755
new mode 100644
similarity index 77%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to hostsidetests/shortcuts/deviceside/backup/publisher4old/AndroidManifest-lib.xml
index a48cb1d..0556f32
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4old/AndroidManifest-lib.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2017 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.
@@ -14,12 +14,8 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  -->
-
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
-
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
-
+    package="android.content.pm.cts.shortcut.backup.publisher4"
+    android:versionCode="10">
 </manifest>
 
diff --git a/hostsidetests/stagedinstall/Android.bp b/hostsidetests/stagedinstall/Android.bp
index 585a26a..b3c2bfa 100644
--- a/hostsidetests/stagedinstall/Android.bp
+++ b/hostsidetests/stagedinstall/Android.bp
@@ -32,7 +32,8 @@
 
     test_suites: [
         "cts",
-        "general-tests"
+        "general-tests",
+        "mts",
     ],
 }
 
@@ -46,6 +47,7 @@
     java_resources:  [
         ":ApexKeyRotationTestV2_SignedBob",
         ":ApexKeyRotationTestV2_SignedBobRot",
+        ":ApexKeyRotationTestV2_SignedEve",
         ":ApexKeyRotationTestV3_SignedBob",
         ":ApexKeyRotationTestV3_SignedBobRot",
         ":StagedInstallTestApexV1_NotPreInstalled",
@@ -94,6 +96,13 @@
 }
 
 prebuilt_apex {
+    name: "ApexKeyRotationTestV2_SignedEve",
+    src: "testdata/apex/com.android.apex.cts.shim.v2_signed_eve.apex",
+    filename: "com.android.apex.cts.shim.v2_signed_eve.apex",
+    installable: false,
+}
+
+prebuilt_apex {
     name: "ApexKeyRotationTestV3_SignedBob",
     src: "testdata/apex/com.android.apex.cts.shim.v3_signed_bob.apex",
     filename: "com.android.apex.cts.shim.v3_signed_bob.apex",
diff --git a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
index cde5dcd..748e45e 100644
--- a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
@@ -110,6 +110,9 @@
     private static final TestApp Apex2SignedBobRot = new TestApp(
             "Apex2SignedBobRot", SHIM_PACKAGE_NAME, 2, /*isApex*/true,
                     "com.android.apex.cts.shim.v2_signed_bob_rot.apex");
+    private static final TestApp Apex2SignedEve = new TestApp(
+            "Apex2SignedEve", SHIM_PACKAGE_NAME, 2, /*isApex*/true,
+            "com.android.apex.cts.shim.v2_signed_eve.apex");
     private static final TestApp Apex3SignedBob = new TestApp(
             "Apex3SignedBob", SHIM_PACKAGE_NAME, 3, /*isApex*/true,
                     "com.android.apex.cts.shim.v3_signed_bob.apex");
@@ -498,6 +501,21 @@
     }
 
     @Test
+    public void testInstallV3SignedBobApex_Commit() throws Exception {
+        int sessionId = stageSingleApk(Apex2SignedBobRot).assertSuccessful().getSessionId();
+        waitForIsReadyBroadcast(sessionId);
+        assertSessionReady(sessionId);
+        storeSessionId(sessionId);
+    }
+
+    @Test
+    public void testInstallV3SignedBobApex_VerifyPostReboot() throws Exception {
+        int sessionId = retrieveLastSessionId();
+        assertSessionApplied(sessionId);
+        assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(2);
+    }
+
+    @Test
     public void testStagedInstallDowngradeApex_DowngradeNotRequested_Fails_Commit()
             throws Exception {
         assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(3);
@@ -728,7 +746,6 @@
     // Once updated with a new rotated key (bob), further updates with old key (alice) should fail
     @Test
     public void testAfterRotationOldKeyIsRejected() throws Exception {
-        // Assume updateWithDifferentKey_Commit has been run already
         assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(2);
         int sessionId = stageSingleApk(TestApp.Apex3).assertSuccessful().getSessionId();
         PackageInstaller.SessionInfo info =
@@ -740,7 +757,6 @@
     // Once updated with a new rotated key (bob), further updates with new key (bob) should pass
     @Test
     public void testAfterRotationNewKeyCanUpdateFurther_CommitPostReboot() throws Exception {
-        // Assume updateWithDifferentKey_Commit has been run already
         assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(2);
         int sessionId = stageSingleApk(Apex3SignedBobRot).assertSuccessful().getSessionId();
         PackageInstaller.SessionInfo info =
@@ -758,7 +774,6 @@
     @Test
     public void testAfterRotationNewKeyCanUpdateFurtherWithoutLineage()
             throws Exception {
-        // Assume updateWithDifferentKey_Commit has been run already
         assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(2);
         int sessionId = stageSingleApk(Apex3SignedBob).assertSuccessful().getSessionId();
         PackageInstaller.SessionInfo info =
@@ -767,6 +782,20 @@
         assertThat(info).isStagedSessionReady();
     }
 
+    // Key downgrade should fail if new key is not ancestor of current key
+    @Test
+    public void testKeyDowngradeFailIfMismatch()
+            throws Exception {
+        assertThat(getInstalledVersion(TestApp.Apex)).isEqualTo(2);
+        int sessionId = stageDowngradeSingleApk(Apex2SignedEve).assertSuccessful().getSessionId();
+        PackageInstaller.SessionInfo info =
+                SessionUpdateBroadcastReceiver.sessionBroadcasts.poll(60, TimeUnit.SECONDS);
+        assertThat(info.getSessionId()).isEqualTo(sessionId);
+        assertThat(info).isStagedSessionFailed();
+        assertThat(info.getStagedSessionErrorMessage()).contains("is not compatible with the one "
+                + "currently installed on device");
+    }
+
     @Test
     public void testSamegradeSystemApex_Commit() throws Exception {
         final PackageInfo shim = InstrumentationRegistry.getInstrumentation().getContext()
diff --git a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
index 7999e34..2f421c3 100644
--- a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
@@ -303,6 +303,12 @@
         runPhase("testInstallV3Apex_VerifyPostReboot");
     }
 
+    private void installV3SignedBobApex() throws Exception {
+        runPhase("testInstallV3SignedBobApex_Commit");
+        getDevice().reboot();
+        runPhase("testInstallV3SignedBobApex_VerifyPostReboot");
+    }
+
     @Test
     public void testFailsInvalidApexInstall() throws Exception {
         assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
@@ -310,7 +316,6 @@
         runPhase("testFailsInvalidApexInstall_AbandonSessionIsNoop");
     }
 
-
     @Test
     public void testStagedApkSessionCallbacks() throws Exception {
         runPhase("testStagedApkSessionCallbacks");
@@ -386,6 +391,15 @@
 
     @Test
     @LargeTest
+    public void testKeyDowngradeFailIfMismatch() throws Exception {
+        assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
+
+        installV3SignedBobApex();
+        runPhase("testKeyDowngradeFailIfMismatch");
+    }
+
+    @Test
+    @LargeTest
     public void testSamegradeSystemApex() throws Exception {
         assumeTrue("Device does not support updating APEX", isUpdatingApexSupported());
 
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v1.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v1.apex
index 6ce5185..efa3d87 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v1.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v1.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2.apex
index 58b7a8e..6f3bc3c 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_file.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_file.apex
index 53f0ed1..f6bb67a 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_file.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_file.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_folder.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_folder.apex
index a1ece1a..a99d938 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_folder.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_additional_folder.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_different_certificate.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_different_certificate.apex
index 6365654..117cbda 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_different_certificate.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_different_certificate.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob.apex
index 95fa522..72d22e8 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob_rot.apex
index fb1f45b..bdca0e5 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_eve.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_eve.apex
new file mode 100644
index 0000000..2cf3d09
--- /dev/null
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_signed_eve.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_post_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_post_install_hook.apex
index 437f7a8..3c5aad1 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_post_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_post_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_pre_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
index 0e92266..a5512ef 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_wrong_sha.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_wrong_sha.apex
index b1c77fa..21b282d 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_wrong_sha.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v2_wrong_sha.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3.apex
index 5c54d73..d3575f4 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob.apex
index cf3e3eb..2a68a26 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob_rot.apex
index 7c59900..abd87a7 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim.v3_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim_not_pre_installed.apex b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim_not_pre_installed.apex
index 788f475..b11deee 100644
--- a/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim_not_pre_installed.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/com.android.apex.cts.shim_not_pre_installed.apex
Binary files differ
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 c679341..fc1b57e 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
@@ -18,7 +18,7 @@
 
 import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.accounts.Account;
 import android.accounts.AccountManager;
@@ -325,7 +325,7 @@
 
         Context context = InstrumentationRegistry.getContext();
         JobScheduler js = context.getSystemService(JobScheduler.class);
-        assertTrue("JobScheduler service not available", js != null);
+        assertWithMessage("JobScheduler service not available").that(js).isNotNull();
 
         JobInfo.Builder builder = new JobInfo.Builder(1, name);
         builder.setOverrideDeadline(0);
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java
index 1db1c0a..3728cef 100644
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java
+++ b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java
@@ -16,7 +16,7 @@
 
 package com.android.server.cts.device.statsd;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.net.wifi.WifiManager;
 import android.os.Vibrator;
@@ -34,12 +34,12 @@
     @Test
     public void checkVibratorSupported() {
         Vibrator v = InstrumentationRegistry.getContext().getSystemService(Vibrator.class);
-        assertTrue(v.hasVibrator());
+        assertThat(v.hasVibrator()).isTrue();
     }
 
     @Test
     public void checkWifiEnhancedPowerReportingSupported() {
         WifiManager wm = InstrumentationRegistry.getContext().getSystemService(WifiManager.class);
-        assertTrue(wm.isEnhancedPowerReportingSupported());
+        assertThat(wm.isEnhancedPowerReportingSupported()).isTrue();
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java b/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java
index 4983d06..00930cd 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.alarm;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import android.cts.statsd.atom.AtomTestCase;
 
 import com.android.internal.os.StatsdConfigProto;
@@ -59,7 +61,7 @@
         String markTime = getCurrentLogcatDate();
         Thread.sleep(9_000);
 
-        if (INCIDENTD_TESTS_ENABLED) assertTrue("No incident", didIncidentdFireSince(markTime));
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
     }
 
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java b/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java
index 3109138..5e9eac6 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java
@@ -15,6 +15,9 @@
  */
 package android.cts.statsd.alert;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.cts.statsd.atom.AtomTestCase;
 
 import com.android.internal.os.StatsdConfigProto;
@@ -94,29 +97,28 @@
         // count(label=6) -> 1 (not an anomaly, since not "greater than 2")
         doAppBreadcrumbReportedStart(6);
         Thread.sleep(500);
-        assertEquals("Premature anomaly", 0, getEventMetricDataList().size());
-        if (INCIDENTD_TESTS_ENABLED) assertFalse("Incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
 
         // count(label=6) -> 2 (not an anomaly, since not "greater than 2")
         doAppBreadcrumbReportedStart(6);
         Thread.sleep(500);
-        assertEquals("Premature anomaly", 0, getEventMetricDataList().size());
-        if (INCIDENTD_TESTS_ENABLED) assertFalse("Incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
 
         // count(label=12) -> 1 (not an anomaly, since not "greater than 2")
         doAppBreadcrumbReportedStart(12);
         Thread.sleep(1000);
-        assertEquals("Premature anomaly", 0, getEventMetricDataList().size());
-        if (INCIDENTD_TESTS_ENABLED) assertFalse("Incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
 
         doAppBreadcrumbReportedStart(6); // count(label=6) -> 3 (anomaly, since "greater than 2"!)
         Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
 
         List<EventMetricData> data = getEventMetricDataList();
-        assertEquals("Expected 1 anomaly", 1, data.size());
-        AnomalyDetected a = data.get(0).getAtom().getAnomalyDetected();
-        assertEquals("Wrong alert_id", ALERT_ID, a.getAlertId());
-        if (INCIDENTD_TESTS_ENABLED) assertTrue("No incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Expected anomaly").that(data).hasSize(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
     }
 
     // Tests that anomaly detection for duration works.
@@ -149,18 +151,18 @@
         String markTime = getCurrentLogcatDate();
         doAppBreadcrumbReportedStart(1);
         Thread.sleep(6_000);  // Recorded duration at end: 6s
-        assertEquals("Premature anomaly,", 0, getEventMetricDataList().size());
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
 
         doAppBreadcrumbReportedStop(1);
         Thread.sleep(4_000);  // Recorded duration at end: 6s
-        assertEquals("Premature anomaly,", 0, getEventMetricDataList().size());
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
 
         // Test that alarm does fire when it is supposed to (after 4s, plus up to 5s alarm delay).
         doAppBreadcrumbReportedStart(1);
         Thread.sleep(9_000);  // Recorded duration at end: 13s
         List<EventMetricData> data = getEventMetricDataList();
-        assertEquals("Expected an anomaly,", 1, data.size());
-        assertEquals(ALERT_ID, data.get(0).getAtom().getAnomalyDetected().getAlertId());
+        assertWithMessage("Expected anomaly").that(data).hasSize(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
 
         // Now test that the refractory period is obeyed.
         markTime = getCurrentLogcatDate();
@@ -168,7 +170,7 @@
         doAppBreadcrumbReportedStart(1);
         Thread.sleep(3_000);  // Recorded duration at end: 13s
         // NB: the previous getEventMetricDataList also removes the report, so size is back to 0.
-        assertEquals("Expected only 1 anomaly,", 0, getEventMetricDataList().size());
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
 
         // Test that detection works again after refractory period finishes.
         doAppBreadcrumbReportedStop(1);
@@ -177,9 +179,9 @@
         Thread.sleep(15_000);  // Recorded duration at end: 15s
         // We can do an incidentd test now that all the timing issues are done.
         data = getEventMetricDataList();
-        assertEquals("Expected another anomaly,", 1, data.size());
-        assertEquals(ALERT_ID, data.get(0).getAtom().getAnomalyDetected().getAlertId());
-        if (INCIDENTD_TESTS_ENABLED) assertTrue("No incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Expected anomaly").that(data).hasSize(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
 
         doAppBreadcrumbReportedStop(1);
     }
@@ -212,7 +214,7 @@
         Thread.sleep(5_000);
         doAppBreadcrumbReportedStop(1);
         Thread.sleep(2_000);
-        assertEquals("Premature anomaly,", 0, getEventMetricDataList().size());
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
 
         // Test that alarm does fire when it is supposed to.
         // The anomaly occurs in 1s, but alarms won't fire that quickly.
@@ -228,9 +230,8 @@
             // Although we expect that the alarm won't fire, we certainly cannot demand that.
             CLog.w(TAG, "The anomaly was detected twice. Presumably the alarm did manage to fire.");
         }
-        assertTrue("Expected 1 (or possibly 2) anomalies, instead of " + data.size(),
-                1 == data.size() || 2 == data.size());
-        assertEquals(ALERT_ID, data.get(0).getAtom().getAnomalyDetected().getAlertId());
+        assertThat(data.size()).isAnyOf(1, 2);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
     }
 
     // Tests that anomaly detection for value works.
@@ -256,17 +257,16 @@
         String markTime = getCurrentLogcatDate();
         doAppBreadcrumbReportedStart(6); // value = 6, which is NOT > trigger
         Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-        assertEquals("Premature anomaly", 0, getEventMetricDataList().size());
-        if (INCIDENTD_TESTS_ENABLED) assertFalse("Incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
 
         doAppBreadcrumbReportedStart(14); // value = 14 > trigger
         Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
 
         List<EventMetricData> data = getEventMetricDataList();
-        assertEquals("Expected 1 anomaly", 1, data.size());
-        AnomalyDetected a = data.get(0).getAtom().getAnomalyDetected();
-        assertEquals("Wrong alert_id", ALERT_ID, a.getAlertId());
-        if (INCIDENTD_TESTS_ENABLED) assertTrue("No incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Expected anomaly").that(data).hasSize(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
     }
 
     // Test that anomaly detection integrates with perfetto properly.
@@ -306,17 +306,28 @@
         String markTime = getCurrentLogcatDate();
         doAppBreadcrumbReportedStart(6); // value = 6, which is NOT > trigger
         Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-        assertEquals("Premature anomaly", 0, getEventMetricDataList().size());
-        if (PERFETTO_TESTS_ENABLED) assertFalse(isSystemTracingEnabled());
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
+        if (PERFETTO_TESTS_ENABLED) assertThat(isSystemTracingEnabled()).isFalse();
 
         doAppBreadcrumbReportedStart(14); // value = 14 > trigger
         Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
 
         List<EventMetricData> data = getEventMetricDataList();
-        assertEquals("Expected 1 anomaly", 1, data.size());
-        AnomalyDetected a = data.get(0).getAtom().getAnomalyDetected();
-        assertEquals("Wrong alert_id", ALERT_ID, a.getAlertId());
-        if (PERFETTO_TESTS_ENABLED) assertTrue(isSystemTracingEnabled());
+        assertWithMessage("Expected anomaly").that(data).hasSize(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
+
+        // Pool a few times to allow for statsd <-> traced <-> traced_probes communication to happen.
+        if (PERFETTO_TESTS_ENABLED) {
+                boolean tracingEnabled = false;
+                for (int i = 0; i < 5; i++) {
+                        if (isSystemTracingEnabled()) {
+                                tracingEnabled = true;
+                                break;
+                        }
+                        Thread.sleep(1000);
+                }
+                assertThat(tracingEnabled).isTrue();
+        }
     }
 
     // Tests that anomaly detection for gauge works.
@@ -343,18 +354,17 @@
         String markTime = getCurrentLogcatDate();
         doAppBreadcrumbReportedStart(6); // gauge = 6, which is NOT > trigger
         Thread.sleep(Math.max(WAIT_AFTER_BREADCRUMB_MS, 1_100)); // Must be >1s to push next bucket.
-        assertEquals("Premature anomaly", 0, getEventMetricDataList().size());
-        if (INCIDENTD_TESTS_ENABLED) assertFalse("Incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
 
         // We waited for >1s above, so we are now in the next bucket (which is essential).
         doAppBreadcrumbReportedStart(14); // gauge = 14 > trigger
         Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
 
         List<EventMetricData> data = getEventMetricDataList();
-        assertEquals("Expected 1 anomaly", 1, data.size());
-        AnomalyDetected a = data.get(0).getAtom().getAnomalyDetected();
-        assertEquals("Wrong alert_id", ALERT_ID, a.getAlertId());
-        if (INCIDENTD_TESTS_ENABLED) assertTrue("No incident", didIncidentdFireSince(markTime));
+        assertWithMessage("Expected anomaly").that(data).hasSize(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
+        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
     }
 
     // Test that anomaly detection for pulled metrics work.
@@ -399,9 +409,8 @@
 
         List<EventMetricData> data = getEventMetricDataList();
         // There will likely be many anomalies (one for each dimension). There must be at least one.
-        assertTrue("Expected >=1 anomaly", data.size() >= 1);
-        AnomalyDetected a = data.get(0).getAtom().getAnomalyDetected();
-        assertEquals("Wrong alert_id", ALERT_ID, a.getAlertId());
+        assertThat(data.size()).isAtLeast(1);
+        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
     }
 
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
index 5b5711c..4ec6142 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
@@ -18,6 +18,9 @@
 import static android.cts.statsd.atom.DeviceAtomTestCase.DEVICE_SIDE_TEST_APK;
 import static android.cts.statsd.atom.DeviceAtomTestCase.DEVICE_SIDE_TEST_PACKAGE;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.os.BatteryStatsProto;
 import android.os.StatsDataDumpProto;
 import android.service.battery.BatteryServiceDumpProto;
@@ -54,6 +57,7 @@
 import com.android.tradefed.util.CommandResult;
 import com.android.tradefed.util.CommandStatus;
 
+import com.google.common.collect.Range;
 import com.google.common.io.Files;
 import com.google.protobuf.ByteString;
 
@@ -255,7 +259,7 @@
      */
     protected List<EventMetricData> getEventMetricDataList(ConfigMetricsReportList reportList)
             throws Exception {
-        assertTrue("Expected one report", reportList.getReportsCount() == 1);
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
         ConfigMetricsReport report = reportList.getReports(0);
 
         List<EventMetricData> data = new ArrayList<>();
@@ -273,15 +277,16 @@
 
     protected List<Atom> getGaugeMetricDataList() throws Exception {
         ConfigMetricsReportList reportList = getReportList();
-        assertTrue("Expected one report.", reportList.getReportsCount() == 1);
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
+
         // only config
         ConfigMetricsReport report = reportList.getReports(0);
-        assertEquals("Expected one metric in the report.", 1, report.getMetricsCount());
+        assertThat(report.getMetricsCount()).isEqualTo(1);
 
         List<Atom> data = new ArrayList<>();
         for (GaugeMetricData gaugeMetricData :
                 report.getMetrics(0).getGaugeMetrics().getDataList()) {
-            assertTrue("Expected one bucket.", gaugeMetricData.getBucketInfoCount() == 1);
+            assertThat(gaugeMetricData.getBucketInfoCount()).isEqualTo(1);
             for (Atom atom : gaugeMetricData.getBucketInfo(0).getAtomList()) {
                 data.add(atom);
             }
@@ -300,7 +305,7 @@
      */
     protected List<DurationMetricData> getDurationMetricDataList() throws Exception {
         ConfigMetricsReportList reportList = getReportList();
-        assertTrue("Expected one report", reportList.getReportsCount() == 1);
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
         ConfigMetricsReport report = reportList.getReports(0);
 
         List<DurationMetricData> data = new ArrayList<>();
@@ -321,7 +326,7 @@
      */
     protected List<CountMetricData> getCountMetricDataList() throws Exception {
         ConfigMetricsReportList reportList = getReportList();
-        assertTrue("Expected one report", reportList.getReportsCount() == 1);
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
         ConfigMetricsReport report = reportList.getReports(0);
 
         List<CountMetricData> data = new ArrayList<>();
@@ -342,7 +347,7 @@
      */
     protected List<ValueMetricData> getValueMetricDataList() throws Exception {
         ConfigMetricsReportList reportList = getReportList();
-        assertTrue("Expected one report", reportList.getReportsCount() == 1);
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
         ConfigMetricsReport report = reportList.getReports(0);
 
         List<ValueMetricData> data = new ArrayList<>();
@@ -359,14 +364,14 @@
 
     protected StatsLogReport getStatsLogReport() throws Exception {
         ConfigMetricsReport report = getConfigMetricsReport();
-        assertTrue(report.hasUidMap());
-        assertEquals(1, report.getMetricsCount());
+        assertThat(report.hasUidMap()).isTrue();
+        assertThat(report.getMetricsCount()).isEqualTo(1);
         return report.getMetrics(0);
     }
 
     protected ConfigMetricsReport getConfigMetricsReport() throws Exception {
         ConfigMetricsReportList reportList = getReportList();
-        assertEquals(1, reportList.getReportsCount());
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
         return reportList.getReports(0);
     }
 
@@ -624,7 +629,7 @@
             int wait, Function<Atom, Integer> getStateFromAtom) {
         // Sometimes, there are more events than there are states.
         // Eg: When the screen turns off, it may go into OFF and then DOZE immediately.
-        assertTrue("Too few states found (" + data.size() + ")", data.size() >= stateSets.size());
+        assertWithMessage("Too few states found").that(data.size()).isAtLeast(stateSets.size());
         int stateSetIndex = 0; // Tracks which state set we expect the data to be in.
         for (int dataIndex = 0; dataIndex < data.size(); dataIndex++) {
             Atom atom = data.get(dataIndex).getAtom();
@@ -641,19 +646,18 @@
                 LogUtil.CLog.i("Assert that the following atom at dataIndex=" + dataIndex + " is"
                         + " in stateSetIndex " + stateSetIndex + ":\n"
                         + data.get(dataIndex).getAtom().toString());
-                assertTrue("Missed first state", dataIndex != 0); // should not be on first data
-                assertTrue("Too many states (" + (stateSetIndex + 1) + ")",
-                        stateSetIndex < stateSets.size());
-                assertTrue("Is in wrong state (" + state + ")",
-                        stateSets.get(stateSetIndex).contains(state));
+                assertWithMessage("Missed first state").that(dataIndex).isNotEqualTo(0); 
+                assertWithMessage("Too many states").that(stateSetIndex)
+                    .isLessThan(stateSets.size());
+                assertWithMessage(String.format("Is in wrong state (%d)", state))
+                    .that(stateSets.get(stateSetIndex)).contains(state);
                 if (wait > 0) {
                     assertTimeDiffBetween(data.get(dataIndex - 1), data.get(dataIndex),
                             wait / 2, wait * 5);
                 }
             }
         }
-        assertTrue("Too few states (" + (stateSetIndex + 1) + ")",
-                stateSetIndex == stateSets.size() - 1);
+        assertWithMessage("Too few states").that(stateSetIndex).isEqualTo(stateSets.size() - 1);
     }
 
     /**
@@ -899,8 +903,8 @@
     public static void assertTimeDiffBetween(EventMetricData d0, EventMetricData d1,
             int minDiffMs, int maxDiffMs) {
         long diffMs = (d1.getElapsedTimestampNanos() - d0.getElapsedTimestampNanos()) / 1_000_000;
-        assertTrue("Illegal time difference (" + diffMs + "ms)", minDiffMs <= diffMs);
-        assertTrue("Illegal time difference (" + diffMs + "ms)", diffMs <= maxDiffMs);
+        assertWithMessage("Illegal time difference")
+            .that(diffMs).isIn(Range.closed((long) minDiffMs, (long) maxDiffMs));
     }
 
     protected String getCurrentLogcatDate() throws Exception {
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java
index 94d5fdc..b110fff 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java
@@ -16,6 +16,9 @@
 
 package android.cts.statsd.atom;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.cts.statsd.validation.ValidationTestUtil;
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
@@ -52,7 +55,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        assertNotNull(mCtsBuild);
+        assertThat(mCtsBuild).isNotNull();
     }
 
     @Override
@@ -104,7 +107,8 @@
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
         final String result = getDevice().installPackage(
                 buildHelper.getTestFile(appFileName), true, grantPermissions);
-        assertNull("Failed to install " + appFileName + ": " + result, result);
+        assertWithMessage(String.format("Failed to install %s: %s", appFileName, result))
+            .that(result).isNull();
     }
 
     protected CompatibilityBuildHelper getBuildHelper() {
@@ -135,7 +139,7 @@
         }
 
         CollectingTestListener listener = new CollectingTestListener();
-        assertTrue(getDevice().runInstrumentationTests(testRunner, listener));
+        assertThat(getDevice().runInstrumentationTests(testRunner, listener)).isTrue();
 
         final TestRunResult result = listener.getCurrentRunResults();
         if (result.isRunFailure()) {
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
index ec6291d..8394006 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
@@ -15,6 +15,9 @@
  */
 package android.cts.statsd.atom;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
 import com.android.internal.os.StatsdConfigProto.MessageMatcher;
 import com.android.internal.os.StatsdConfigProto.Position;
@@ -80,9 +83,9 @@
         List<EventMetricData> data = doDeviceMethod(methodName, conf);
 
         if (demandExactlyTwo) {
-            assertEquals(2, data.size());
+            assertThat(data).hasSize(2);
         } else {
-            assertTrue("data.size() [" + data.size() + "] should be >= 2", data.size() >= 2);
+            assertThat(data.size()).isAtLeast(2);
         }
         assertTimeDiffBetween(data.get(0), data.get(1), minTimeDiffMs, maxTimeDiffMs);
         return data;
@@ -165,9 +168,9 @@
                 + currentUser + " " + DEVICE_SIDE_TEST_PACKAGE);
         String[] uidLineParts = uidLine.split(":");
         // 3rd entry is package uid
-        assertTrue(uidLineParts.length > 2);
+        assertThat(uidLineParts.length).isGreaterThan(2);
         int uid = Integer.parseInt(uidLineParts[2].trim());
-        assertTrue(uid > 10000);
+        assertThat(uid).isGreaterThan(10000);
         return uid;
     }
 
@@ -287,8 +290,10 @@
     protected void rebootDeviceAndWaitUntilReady() throws Exception {
         rebootDevice();
         // Wait for 2 mins.
-        assertTrue("Device failed to boot", getDevice().waitForBootComplete(120_000));
-        assertTrue("Stats service failed to start", waitForStatsServiceStart(60_000));
+        assertWithMessage("Device failed to boot")
+            .that(getDevice().waitForBootComplete(120_000)).isTrue();
+        assertWithMessage("Stats service failed to start")
+            .that(waitForStatsServiceStart(60_000)).isTrue();
         Thread.sleep(2_000);
     }
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
index c22fd8b..1bdaf7c 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
@@ -16,6 +16,7 @@
 package android.cts.statsd.atom;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.os.BatteryPluggedStateEnum;
 import android.os.BatteryStatusEnum;
@@ -32,6 +33,8 @@
 import com.android.os.StatsLog.ConfigMetricsReportList;
 import com.android.os.StatsLog.EventMetricData;
 
+import com.google.common.collect.Range;
+
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
@@ -349,11 +352,12 @@
 
         List<Atom> data = getGaugeMetricDataList();
 
-        assertTrue(data.size() > 0);
+        assertThat(data).isNotEmpty();
         Atom atom = data.get(0);
-        assertTrue(atom.getRemainingBatteryCapacity().hasChargeMicroAmpereHour());
+        assertThat(atom.getRemainingBatteryCapacity().hasChargeMicroAmpereHour()).isTrue();
         if (hasBattery()) {
-            assertTrue(atom.getRemainingBatteryCapacity().getChargeMicroAmpereHour() > 0);
+            assertThat(atom.getRemainingBatteryCapacity().getChargeMicroAmpereHour())
+                .isGreaterThan(0);
         }
     }
 
@@ -375,11 +379,11 @@
 
         List<Atom> data = getGaugeMetricDataList();
 
-        assertTrue(data.size() > 0);
+        assertThat(data).isNotEmpty();
         Atom atom = data.get(0);
-        assertTrue(atom.getFullBatteryCapacity().hasCapacityMicroAmpereHour());
+        assertThat(atom.getFullBatteryCapacity().hasCapacityMicroAmpereHour()).isTrue();
         if (hasBattery()) {
-            assertTrue(atom.getFullBatteryCapacity().getCapacityMicroAmpereHour() > 0);
+            assertThat(atom.getFullBatteryCapacity().getCapacityMicroAmpereHour()).isGreaterThan(0);
         }
     }
 
@@ -399,11 +403,11 @@
 
         List<Atom> data = getGaugeMetricDataList();
 
-        assertTrue(data.size() > 0);
+        assertThat(data).isNotEmpty();
         Atom atom = data.get(0);
-        assertTrue(atom.getBatteryVoltage().hasVoltageMillivolt());
+        assertThat(atom.getBatteryVoltage().hasVoltageMillivolt()).isTrue();
         if (hasBattery()) {
-            assertTrue(atom.getBatteryVoltage().getVoltageMillivolt() > 0);
+            assertThat(atom.getBatteryVoltage().getVoltageMillivolt()).isGreaterThan(0);
         }
     }
 
@@ -424,12 +428,11 @@
 
         List<Atom> data = getGaugeMetricDataList();
 
-        assertTrue(data.size() > 0);
+        assertThat(data).isNotEmpty();
         Atom atom = data.get(0);
-        assertTrue(atom.getBatteryLevel().hasBatteryLevel());
+        assertThat(atom.getBatteryLevel().hasBatteryLevel()).isTrue();
         if (hasBattery()) {
-            assertTrue(atom.getBatteryLevel().getBatteryLevel() > 0);
-            assertTrue(atom.getBatteryLevel().getBatteryLevel() <= 100);
+            assertThat(atom.getBatteryLevel().getBatteryLevel()).isIn(Range.openClosed(0, 100));
         }
     }
 
@@ -450,11 +453,11 @@
 
         List<Atom> data = getGaugeMetricDataList();
 
-        assertTrue(data.size() > 0);
+        assertThat(data).isNotEmpty();
         Atom atom = data.get(0);
-        assertTrue(atom.getBatteryCycleCount().hasCycleCount());
+        assertThat(atom.getBatteryCycleCount().hasCycleCount()).isTrue();
         if (hasBattery()) {
-            assertTrue(atom.getBatteryCycleCount().getCycleCount() >= 0);
+            assertThat(atom.getBatteryCycleCount().getCycleCount()).isAtLeast(0);
         }
     }
 
@@ -474,11 +477,11 @@
         List<Atom> data = getGaugeMetricDataList();
 
         Atom atom = data.get(0);
-        assertTrue(!atom.getKernelWakelock().getName().equals(""));
-        assertTrue(atom.getKernelWakelock().hasCount());
-        assertTrue(atom.getKernelWakelock().hasVersion());
-        assertTrue(atom.getKernelWakelock().getVersion() > 0);
-        assertTrue(atom.getKernelWakelock().hasTimeMicros());
+        assertThat(atom.getKernelWakelock().getName()).isNotEmpty();
+        assertThat(atom.getKernelWakelock().hasCount()).isTrue();
+        assertThat(atom.getKernelWakelock().hasVersion()).isTrue();
+        assertThat(atom.getKernelWakelock().getVersion()).isGreaterThan(0);
+        assertThat(atom.getKernelWakelock().hasTimeMicros()).isTrue();
     }
 
     // Returns true iff either |WAKE_LOCK_FILE| or |WAKE_SOURCES_FILE| exists.
@@ -510,12 +513,12 @@
         List<Atom> dataList = getGaugeMetricDataList();
 
         for (Atom atom: dataList) {
-            assertTrue(atom.getWifiActivityInfo().getTimestampMillis() > 0);
-            assertTrue(atom.getWifiActivityInfo().getStackState() >= 0);
-            assertTrue(atom.getWifiActivityInfo().getControllerIdleTimeMillis() > 0);
-            assertTrue(atom.getWifiActivityInfo().getControllerTxTimeMillis() >= 0);
-            assertTrue(atom.getWifiActivityInfo().getControllerRxTimeMillis() >= 0);
-            assertTrue(atom.getWifiActivityInfo().getControllerEnergyUsed() >= 0);
+            assertThat(atom.getWifiActivityInfo().getTimestampMillis()).isGreaterThan(0L);
+            assertThat(atom.getWifiActivityInfo().getStackState()).isAtLeast(0);
+            assertThat(atom.getWifiActivityInfo().getControllerIdleTimeMillis()).isGreaterThan(0L);
+            assertThat(atom.getWifiActivityInfo().getControllerTxTimeMillis()).isAtLeast(0L);
+            assertThat(atom.getWifiActivityInfo().getControllerRxTimeMillis()).isAtLeast(0L);
+            assertThat(atom.getWifiActivityInfo().getControllerEnergyUsed()).isAtLeast(0L);
         }
     }
 
@@ -533,16 +536,17 @@
         Thread.sleep(WAIT_TIME_LONG);
 
         List<Atom> data = getGaugeMetricDataList();
-        assertTrue(data.size() > 0);
+        assertThat(data).isNotEmpty();
         BuildInformation atom = data.get(0).getBuildInformation();
-        assertEquals(getProperty("ro.product.brand"),             atom.getBrand());
-        assertEquals(getProperty("ro.product.name"),              atom.getProduct());
-        assertEquals(getProperty("ro.product.device"),            atom.getDevice());
-        assertEquals(getProperty("ro.build.version.release"),     atom.getVersionRelease());
-        assertEquals(getProperty("ro.build.id"),                  atom.getId());
-        assertEquals(getProperty("ro.build.version.incremental"), atom.getVersionIncremental());
-        assertEquals(getProperty("ro.build.type"),                atom.getType());
-        assertEquals(getProperty("ro.build.tags"),                atom.getTags());
+        assertThat(getProperty("ro.product.brand")).isEqualTo(atom.getBrand());
+        assertThat(getProperty("ro.product.name")).isEqualTo(atom.getProduct());
+        assertThat(getProperty("ro.product.device")).isEqualTo(atom.getDevice());
+        assertThat(getProperty("ro.build.version.release")).isEqualTo(atom.getVersionRelease());
+        assertThat(getProperty("ro.build.id")).isEqualTo(atom.getId());
+        assertThat(getProperty("ro.build.version.incremental"))
+            .isEqualTo(atom.getVersionIncremental());
+        assertThat(getProperty("ro.build.type")).isEqualTo(atom.getType());
+        assertThat(getProperty("ro.build.tags")).isEqualTo(atom.getTags());
     }
 
     public void testOnDevicePowerMeasurement() throws Exception {
@@ -563,8 +567,9 @@
         List<Atom> dataList = getGaugeMetricDataList();
 
         for (Atom atom: dataList) {
-            assertTrue(atom.getOnDevicePowerMeasurement().getMeasurementTimestampMillis() >= 0);
-            assertTrue(atom.getOnDevicePowerMeasurement().getEnergyMicrowattSecs() >= 0);
+            assertThat(atom.getOnDevicePowerMeasurement().getMeasurementTimestampMillis())
+                .isAtLeast(0L);
+            assertThat(atom.getOnDevicePowerMeasurement().getEnergyMicrowattSecs()).isAtLeast(0L);
         }
     }
 
@@ -582,8 +587,8 @@
 
         List<EventMetricData> data = getEventMetricDataList();
         AppBreadcrumbReported atom = data.get(0).getAtom().getAppBreadcrumbReported();
-        assertTrue(atom.getLabel() == 1);
-        assertTrue(atom.getState().getNumber() == AppBreadcrumbReported.State.START_VALUE);
+        assertThat(atom.getLabel()).isEqualTo(1);
+        assertThat(atom.getState().getNumber()).isEqualTo(AppBreadcrumbReported.State.START_VALUE);
     }
 
     // Test dumpsys stats --proto.
@@ -600,7 +605,7 @@
 
         // Get the stats incident section.
         List<ConfigMetricsReportList> listList = getReportsFromStatsDataDumpProto();
-        assertTrue(listList.size() > 0);
+        assertThat(listList).isNotEmpty();
 
         // Extract the relevent report from the incident section.
         ConfigMetricsReportList ourList = null;
@@ -612,14 +617,14 @@
                 break;
             }
         }
-        assertNotNull("Could not find list for uid=" + hostUid
-                + " id=" + CONFIG_ID, ourList);
+        assertWithMessage(String.format("Could not find list for uid=%d id=%d", hostUid, CONFIG_ID))
+            .that(ourList).isNotNull();
 
         // Make sure that the report is correct.
         List<EventMetricData> data = getEventMetricDataList(ourList);
         AppBreadcrumbReported atom = data.get(0).getAtom().getAppBreadcrumbReported();
-        assertTrue(atom.getLabel() == 1);
-        assertTrue(atom.getState().getNumber() == AppBreadcrumbReported.State.START_VALUE);
+        assertThat(atom.getLabel()).isEqualTo(1);
+        assertThat(atom.getState().getNumber()).isEqualTo(AppBreadcrumbReported.State.START_VALUE);
     }
 
     public void testConnectivityStateChange() throws Exception {
@@ -656,6 +661,7 @@
                 foundConnectEvent = true;
             }
         }
-        assertTrue(foundConnectEvent && foundDisconnectEvent);
+        assertThat(foundConnectEvent).isTrue();
+        assertThat(foundDisconnectEvent).isTrue();
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java
index 5fecde5..070d3f4 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.atom;
 
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.app.ProcessStateEnum; // From enums.proto for atoms.proto's UidProcessStateChanged.
 
 import com.android.os.AtomsProto.Atom;
@@ -248,8 +250,8 @@
         if (statsdDisabled()) {
             return;
         }
-        assertFalse("UNKNOWN_TO_PROTO should not be a valid state",
-                ALL_STATES.contains(ProcessStateEnum.PROCESS_STATE_UNKNOWN_TO_PROTO_VALUE));
+        assertWithMessage("UNKNOWN_TO_PROTO should not be a valid state")
+            .that(ALL_STATES).doesNotContain(ProcessStateEnum.PROCESS_STATE_UNKNOWN_TO_PROTO_VALUE);
     }
 
     /** Returns the a set containing elements of a that are not elements of b. */
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index 045b4a1..ffe888d 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -15,6 +15,9 @@
  */
 package android.cts.statsd.atom;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.net.wifi.WifiModeEnum;
 import android.os.WakeLockLevelEnum;
 import android.server.ErrorSource;
@@ -45,6 +48,7 @@
 import com.android.os.AtomsProto.OverlayStateChanged;
 import com.android.os.AtomsProto.PictureInPictureStateChanged;
 import com.android.os.AtomsProto.ProcessMemoryHighWaterMark;
+import com.android.os.AtomsProto.ProcessMemorySnapshot;
 import com.android.os.AtomsProto.ProcessMemoryState;
 import com.android.os.AtomsProto.ScheduledJobStateChanged;
 import com.android.os.AtomsProto.SyncStateChanged;
@@ -58,6 +62,8 @@
 import com.android.os.StatsLog.EventMetricData;
 import com.android.tradefed.log.LogUtil;
 
+import com.google.common.collect.Range;
+
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
@@ -102,12 +108,12 @@
         // Sorted list of events in order in which they occurred.
         List<EventMetricData> data = getEventMetricDataList();
 
-        assertEquals(1, data.size());
-        assertTrue(data.get(0).getAtom().hasLmkKillOccurred());
+        assertThat(data).hasSize(1);
+        assertThat(data.get(0).getAtom().hasLmkKillOccurred()).isTrue();
         LmkKillOccurred atom = data.get(0).getAtom().getLmkKillOccurred();
-        assertEquals(getUid(), atom.getUid());
-        assertEquals(DEVICE_SIDE_TEST_PACKAGE, atom.getProcessName());
-        assertTrue(500 <= atom.getOomAdjScore());
+        assertThat(atom.getUid()).isEqualTo(getUid());
+        assertThat(atom.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+        assertThat(atom.getOomAdjScore()).isAtLeast(500);
     }
 
     public void testAppCrashOccurred() throws Exception {
@@ -125,11 +131,12 @@
         List<EventMetricData> data = getEventMetricDataList();
 
         AppCrashOccurred atom = data.get(0).getAtom().getAppCrashOccurred();
-        assertEquals("crash", atom.getEventType());
-        assertEquals(AppCrashOccurred.InstantApp.FALSE_VALUE, atom.getIsInstantApp().getNumber());
-        assertEquals(AppCrashOccurred.ForegroundState.FOREGROUND_VALUE,
-                atom.getForegroundState().getNumber());
-        assertEquals("com.android.server.cts.device.statsd", atom.getPackageName());
+        assertThat(atom.getEventType()).isEqualTo("crash");
+        assertThat(atom.getIsInstantApp().getNumber())
+            .isEqualTo(AppCrashOccurred.InstantApp.FALSE_VALUE);
+        assertThat(atom.getForegroundState().getNumber())
+            .isEqualTo(AppCrashOccurred.ForegroundState.FOREGROUND_VALUE);
+        assertThat(atom.getPackageName()).isEqualTo("com.android.server.cts.device.statsd");
     }
 
     public void testAppStartOccurred() throws Exception {
@@ -147,12 +154,12 @@
         List<EventMetricData> data = getEventMetricDataList();
 
         AppStartOccurred atom = data.get(0).getAtom().getAppStartOccurred();
-        assertEquals("com.android.server.cts.device.statsd", atom.getPkgName());
-        assertEquals("com.android.server.cts.device.statsd.StatsdCtsForegroundActivity",
-                atom.getActivityName());
-        assertFalse(atom.getIsInstantApp());
-        assertTrue(atom.getActivityStartMillis() > 0);
-        assertTrue(atom.getTransitionDelayMillis() > 0);
+        assertThat(atom.getPkgName()).isEqualTo("com.android.server.cts.device.statsd");
+        assertThat(atom.getActivityName())
+            .isEqualTo("com.android.server.cts.device.statsd.StatsdCtsForegroundActivity");
+        assertThat(atom.getIsInstantApp()).isFalse();
+        assertThat(atom.getActivityStartMillis()).isGreaterThan(0L);
+        assertThat(atom.getTransitionDelayMillis()).isGreaterThan(0);
     }
 
     public void testAudioState() throws Exception {
@@ -204,8 +211,8 @@
 
         BleScanStateChanged a0 = data.get(0).getAtom().getBleScanStateChanged();
         BleScanStateChanged a1 = data.get(1).getAtom().getBleScanStateChanged();
-        assertTrue(a0.getState().getNumber() == stateOn);
-        assertTrue(a1.getState().getNumber() == stateOff);
+        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
+        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
     }
 
     public void testBleUnoptimizedScan() throws Exception {
@@ -225,15 +232,15 @@
                 stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, true);
 
         BleScanStateChanged a0 = data.get(0).getAtom().getBleScanStateChanged();
-        assertTrue(a0.getState().getNumber() == stateOn);
-        assertFalse(a0.getIsFiltered());
-        assertFalse(a0.getIsFirstMatch());
-        assertFalse(a0.getIsOpportunistic());
+        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
+        assertThat(a0.getIsFiltered()).isFalse();
+        assertThat(a0.getIsFirstMatch()).isFalse();
+        assertThat(a0.getIsOpportunistic()).isFalse();
         BleScanStateChanged a1 = data.get(1).getAtom().getBleScanStateChanged();
-        assertTrue(a1.getState().getNumber() == stateOff);
-        assertFalse(a1.getIsFiltered());
-        assertFalse(a1.getIsFirstMatch());
-        assertFalse(a1.getIsOpportunistic());
+        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
+        assertThat(a1.getIsFiltered()).isFalse();
+        assertThat(a1.getIsFirstMatch()).isFalse();
+        assertThat(a1.getIsOpportunistic()).isFalse();
 
 
         // Now repeat the test for opportunistic scanning and make sure it is reported correctly.
@@ -241,15 +248,15 @@
                 stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, true);
 
         a0 = data.get(0).getAtom().getBleScanStateChanged();
-        assertTrue(a0.getState().getNumber() == stateOn);
-        assertFalse(a0.getIsFiltered());
-        assertFalse(a0.getIsFirstMatch());
-        assertTrue(a0.getIsOpportunistic());  // This scan is opportunistic.
+        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
+        assertThat(a0.getIsFiltered()).isFalse();
+        assertThat(a0.getIsFirstMatch()).isFalse();
+        assertThat(a0.getIsOpportunistic()).isTrue();  // This scan is opportunistic.
         a1 = data.get(1).getAtom().getBleScanStateChanged();
-        assertTrue(a1.getState().getNumber() == stateOff);
-        assertFalse(a1.getIsFiltered());
-        assertFalse(a1.getIsFirstMatch());
-        assertTrue(a1.getIsOpportunistic());
+        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
+        assertThat(a1.getIsFiltered()).isFalse();
+        assertThat(a1.getIsFirstMatch()).isFalse();
+        assertThat(a1.getIsOpportunistic()).isTrue();
     }
 
     public void testBleScanResult() throws Exception {
@@ -265,9 +272,9 @@
         addAtomEvent(conf, atom, createFvm(field).setGteInt(0));
         List<EventMetricData> data = doDeviceMethod("testBleScanResult", conf);
 
-        assertTrue(data.size() >= 1);
+        assertThat(data.size()).isAtLeast(1);
         BleScanResultReceived a0 = data.get(0).getAtom().getBleScanResultReceived();
-        assertTrue(a0.getNumResults() >= 1);
+        assertThat(a0.getNumResults()).isAtLeast(1);
     }
 
     public void testHiddenApiUsed() throws Exception {
@@ -289,15 +296,15 @@
 
 
             List<EventMetricData> data = getEventMetricDataList();
-            assertTrue(data.size() == 1);
+            assertThat(data).hasSize(1);
 
             HiddenApiUsed atom = data.get(0).getAtom().getHiddenApiUsed();
 
             int uid = getUid();
-            assertEquals(uid, atom.getUid());
-            assertFalse(atom.getAccessDenied());
-            assertEquals("Landroid/app/Activity;->mWindow:Landroid/view/Window;",
-                    atom.getSignature());
+            assertThat(atom.getUid()).isEqualTo(uid);
+            assertThat(atom.getAccessDenied()).isFalse();
+            assertThat(atom.getSignature())
+                .isEqualTo("Landroid/app/Activity;->mWindow:Landroid/view/Window;");
         } finally {
             if (!oldRate.equals("null")) {
                 getDevice().executeShellCommand(
@@ -359,11 +366,11 @@
         for (Atom atom : atomList) {
             if (atom.getCpuTimePerUid().getUid() == uid) {
                 found = true;
-                assertTrue(atom.getCpuTimePerUid().getUserTimeMicros() > 0);
-                assertTrue(atom.getCpuTimePerUid().getSysTimeMicros() > 0);
+                assertThat(atom.getCpuTimePerUid().getUserTimeMicros()).isGreaterThan(0L);
+                assertThat(atom.getCpuTimePerUid().getSysTimeMicros()).isGreaterThan(0L);
             }
         }
-        assertTrue("found uid " + uid, found);
+        assertWithMessage(String.format("did not find uid %d", uid)).that(found).isTrue();
     }
 
     public void testDeviceCalculatedPowerUse() throws Exception {
@@ -384,7 +391,8 @@
         Thread.sleep(WAIT_TIME_LONG);
 
         Atom atom = getGaugeMetricDataList().get(0);
-        assertTrue(atom.getDeviceCalculatedPowerUse().getComputedPowerNanoAmpSecs() > 0);
+        assertThat(atom.getDeviceCalculatedPowerUse().getComputedPowerNanoAmpSecs())
+            .isGreaterThan(0L);
     }
 
 
@@ -413,13 +421,15 @@
         for (Atom atom : atomList) {
             DeviceCalculatedPowerBlameUid item = atom.getDeviceCalculatedPowerBlameUid();
                 if (item.getUid() == uid) {
-                assertFalse("Found multiple power values for uid " + uid, uidFound);
+                assertWithMessage(String.format("Found multiple power values for uid %d", uid))
+                    .that(uidFound).isFalse();
                 uidFound = true;
                 uidPower = item.getPowerNanoAmpSecs();
             }
         }
-        assertTrue("No power value for uid " + uid, uidFound);
-        assertTrue("Non-positive power value for uid " + uid, uidPower > 0);
+        assertWithMessage(String.format("No power value for uid %d", uid)).that(uidFound).isTrue();
+        assertWithMessage(String.format("Non-positive power value for uid %d", uid))
+            .that(uidPower).isGreaterThan(0L);
     }
 
     public void testDavey() throws Exception {
@@ -435,12 +445,10 @@
         runActivity("DaveyActivity", null, null);
 
         List<EventMetricData> data = getEventMetricDataList();
-        assertTrue(data.size() == 1);
+        assertThat(data).hasSize(1);
         long duration = data.get(0).getAtom().getDaveyOccurred().getJankDurationMillis();
-        assertTrue("Jank duration of " + duration + "ms was less than " + MIN_DURATION + "ms",
-                duration >= MIN_DURATION);
-        assertTrue("Jank duration of " + duration + "ms was longer than " + MAX_DURATION + "ms",
-                duration <= MAX_DURATION);
+        assertWithMessage("Incorrect jank duration")
+            .that(duration).isIn(Range.closed(MIN_DURATION, MAX_DURATION));
     }
 
     public void testFlashlightState() throws Exception {
@@ -526,8 +534,8 @@
 
             GpsScanStateChanged a0 = data.get(0).getAtom().getGpsScanStateChanged();
             GpsScanStateChanged a1 = data.get(1).getAtom().getGpsScanStateChanged();
-            assertTrue(a0.getState().getNumber() == stateOn);
-            assertTrue(a1.getState().getNumber() == stateOff);
+            assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
+            assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
         } finally {
             if ("null".equals(origWhitelist) || "".equals(origWhitelist)) {
                 getDevice().executeShellCommand(
@@ -657,7 +665,8 @@
                 atom -> atom.getScheduledJobStateChanged().getState().getNumber());
 
         for (EventMetricData e : data) {
-            assertTrue(e.getAtom().getScheduledJobStateChanged().getJobName().equals(expectedName));
+            assertThat(e.getAtom().getScheduledJobStateChanged().getJobName())
+                .isEqualTo(expectedName);
         }
     }
 
@@ -783,10 +792,8 @@
         for (EventMetricData event: data) {
             String tag = event.getAtom().getWakelockStateChanged().getTag();
             WakeLockLevelEnum type = event.getAtom().getWakelockStateChanged().getType();
-            assertTrue("Expected tag: " + EXPECTED_TAG + ", but got tag: " + tag,
-                    tag.equals(EXPECTED_TAG));
-            assertTrue("Expected wakelock type: " + EXPECTED_LEVEL  + ", but got level: " + type,
-                    type == EXPECTED_LEVEL);
+            assertThat(tag).isEqualTo(EXPECTED_TAG);
+            assertThat(type).isEqualTo(EXPECTED_LEVEL);
         }
     }
 
@@ -803,11 +810,11 @@
         addAtomEvent(config, atomTag, true);  // True: uses attribution.
 
         List<EventMetricData> data = doDeviceMethod("testWakeupAlarm", config);
-        assertTrue(data.size() >= 1);
+        assertThat(data.size()).isAtLeast(1);
         for (int i = 0; i < data.size(); i++) {
             WakeupAlarmOccurred wao = data.get(i).getAtom().getWakeupAlarmOccurred();
-            assertEquals("*walarm*:android.cts.statsd.testWakeupAlarm", wao.getTag());
-            assertEquals(DEVICE_SIDE_TEST_PACKAGE, wao.getPackageName());
+            assertThat(wao.getTag()).isEqualTo("*walarm*:android.cts.statsd.testWakeupAlarm");
+            assertThat(wao.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
         }
     }
 
@@ -836,8 +843,8 @@
                 atom -> atom.getWifiLockStateChanged().getState().getNumber());
 
         for (EventMetricData event : data) {
-            assertEquals(WifiModeEnum.WIFI_MODE_FULL_HIGH_PERF,
-                         event.getAtom().getWifiLockStateChanged().getMode());
+            assertThat(event.getAtom().getWifiLockStateChanged().getMode())
+                .isEqualTo(WifiModeEnum.WIFI_MODE_FULL_HIGH_PERF);
         }
     }
 
@@ -866,8 +873,8 @@
                 atom -> atom.getWifiLockStateChanged().getState().getNumber());
 
         for (EventMetricData event : data) {
-            assertEquals(WifiModeEnum.WIFI_MODE_FULL_LOW_LATENCY,
-                         event.getAtom().getWifiLockStateChanged().getMode());
+            assertThat(event.getAtom().getWifiLockStateChanged().getMode())
+                .isEqualTo(WifiModeEnum.WIFI_MODE_FULL_LOW_LATENCY);
         }
     }
 
@@ -901,7 +908,7 @@
 
         for (EventMetricData event: data) {
             String tag = event.getAtom().getWifiMulticastLockStateChanged().getTag();
-            assertEquals("Wrong tag.", EXPECTED_TAG, tag);
+            assertThat(tag).isEqualTo(EXPECTED_TAG);
         }
     }
 
@@ -922,12 +929,11 @@
         List<EventMetricData> data = doDeviceMethodOnOff("testWifiScan", atom, key,
                 stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, demandExactlyTwo);
 
-        assertTrue(data.size() >= 2);
-        assertTrue(data.size() <= 4);
+        assertThat(data.size()).isIn(Range.closed(2, 4));
         WifiScanStateChanged a0 = data.get(0).getAtom().getWifiScanStateChanged();
         WifiScanStateChanged a1 = data.get(1).getAtom().getWifiScanStateChanged();
-        assertTrue(a0.getState().getNumber() == stateOn);
-        assertTrue(a1.getState().getNumber() == stateOff);
+        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
+        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
     }
 
     public void testBinderStats() throws Exception {
@@ -963,20 +969,16 @@
 
                 if (calls.getUid() == uid && classMatches && methodMatches) {
                     found = true;
-                    assertTrue("Call count should not be negative or equal to 0.",
-                            calls.getRecordedCallCount() > 0);
-                    assertTrue("Call count should not be negative or equal to 0.",
-                            calls.getCallCount() > 0);
-                    assertTrue("Wrong latency",
-                            calls.getRecordedTotalLatencyMicros() > 0
-                            && calls.getRecordedTotalLatencyMicros() < 1000000);
-                    assertTrue("Wrong cpu usage",
-                            calls.getRecordedTotalCpuMicros() > 0
-                            && calls.getRecordedTotalCpuMicros() < 1000000);
+                    assertThat(calls.getRecordedCallCount()).isGreaterThan(0L);
+                    assertThat(calls.getCallCount()).isGreaterThan(0L);
+                    assertThat(calls.getRecordedTotalLatencyMicros())
+                        .isIn(Range.open(0L, 1000000L));
+                    assertThat(calls.getRecordedTotalCpuMicros()).isIn(Range.open(0L, 1000000L));
                 }
             }
 
-            assertTrue("Did not find a matching atom for uid " + uid, found);
+            assertWithMessage(String.format("Did not find a matching atom for uid %d", uid))
+                .that(found).isTrue();
 
         } finally {
             disableBinderStats();
@@ -1017,34 +1019,21 @@
                                 notificationServiceFullName + "$EnqueueNotificationRunnable");
                 if (atom.getLooperStats().getUid() == uid && handlerMatches && messageMatches) {
                     found = true;
-                    assertTrue(stats.getMessageCount() > 0);
-                    assertTrue("Message count should be non-negative.",
-                            stats.getMessageCount() > 0);
-                    assertTrue("Recorded message count should be non-negative.",
-                            stats.getRecordedMessageCount() > 0);
-                    assertTrue("Wrong latency",
-                            stats.getRecordedTotalLatencyMicros() > 0
-                                    && stats.getRecordedTotalLatencyMicros() < 1000000);
-                    assertTrue("Wrong cpu usage",
-                            stats.getRecordedTotalCpuMicros() > 0
-                                    && stats.getRecordedTotalCpuMicros() < 1000000);
-                    assertTrue("Wrong max latency",
-                            stats.getRecordedMaxLatencyMicros() > 0
-                                    && stats.getRecordedMaxLatencyMicros() < 1000000);
-                    assertTrue("Wrong max cpu usage",
-                            stats.getRecordedMaxCpuMicros() > 0
-                                    && stats.getRecordedMaxCpuMicros() < 1000000);
-                    assertTrue("Recorded delay message count should be non-negative.",
-                            stats.getRecordedDelayMessageCount() > 0);
-                    assertTrue("Wrong delay",
-                            stats.getRecordedTotalDelayMillis() >= 0
-                                    && stats.getRecordedTotalDelayMillis() < 5000);
-                    assertTrue("Wrong max delay",
-                            stats.getRecordedMaxDelayMillis() >= 0
-                                    && stats.getRecordedMaxDelayMillis() < 5000);
+                    assertThat(stats.getMessageCount()).isGreaterThan(0L);
+                    assertThat(stats.getRecordedMessageCount()).isGreaterThan(0L);
+                    assertThat(stats.getRecordedTotalLatencyMicros())
+                        .isIn(Range.open(0L, 1000000L));
+                    assertThat(stats.getRecordedTotalCpuMicros()).isIn(Range.open(0L, 1000000L));
+                    assertThat(stats.getRecordedMaxLatencyMicros()).isIn(Range.open(0L, 1000000L));
+                    assertThat(stats.getRecordedMaxCpuMicros()).isIn(Range.open(0L, 1000000L));
+                    assertThat(stats.getRecordedDelayMessageCount()).isGreaterThan(0L);
+                    assertThat(stats.getRecordedTotalDelayMillis())
+                        .isIn(Range.closedOpen(0L, 5000L));
+                    assertThat(stats.getRecordedMaxDelayMillis()).isIn(Range.closedOpen(0L, 5000L));
                 }
             }
-            assertTrue("Did not find a matching atom for uid " + uid, found);
+            assertWithMessage(String.format("Did not find a matching atom for uid %d", uid))
+                .that(found).isTrue();
         } finally {
             cleanUpLooperStats();
             plugInAc();
@@ -1081,18 +1070,18 @@
                 continue;
             }
             found = true;
-            assertEquals(DEVICE_SIDE_TEST_PACKAGE, state.getProcessName());
-            assertTrue("oom_score should not be negative", state.getOomAdjScore() >= 0);
-            assertTrue("page_fault should not be negative", state.getPageFault() >= 0);
-            assertTrue("page_major_fault should not be negative", state.getPageMajorFault() >= 0);
-            assertTrue("rss_in_bytes should be positive", state.getRssInBytes() > 0);
-            assertTrue("cache_in_bytes should not be negative", state.getCacheInBytes() >= 0);
-            assertTrue("swap_in_bytes should not be negative", state.getSwapInBytes() >= 0);
-            assertTrue("start_time_nanos should be positive", state.getStartTimeNanos() > 0);
-            assertTrue("start_time_nanos should be in the past",
-                    state.getStartTimeNanos() < System.nanoTime());
+            assertThat(state.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+            assertThat(state.getOomAdjScore()).isAtLeast(0);
+            assertThat(state.getPageFault()).isAtLeast(0L);
+            assertThat(state.getPageMajorFault()).isAtLeast(0L);
+            assertThat(state.getRssInBytes()).isGreaterThan(0L);
+            assertThat(state.getCacheInBytes()).isAtLeast(0L);
+            assertThat(state.getSwapInBytes()).isAtLeast(0L);
+            assertThat(state.getStartTimeNanos()).isGreaterThan(0L);
+            assertThat(state.getStartTimeNanos()).isLessThan(System.nanoTime());
         }
-        assertTrue("Did not find a matching atom for uid=" + uid, found);
+        assertWithMessage(String.format("Did not find a matching atom for uid %d", uid))
+            .that(found).isTrue();
     }
 
     public void testNativeProcessMemoryState() throws Exception {
@@ -1119,15 +1108,14 @@
                 continue;
             }
             found = true;
-            assertTrue("uid is below 10000", state.getUid() < 10000);
-            assertTrue("page_fault should not be negative", state.getPageFault() >= 0);
-            assertTrue("page_major_fault should not be negative", state.getPageMajorFault() >= 0);
-            assertTrue("rss_in_bytes should be positive", state.getRssInBytes() > 0);
-            assertTrue("start_time_nanos should be positive", state.getStartTimeNanos() > 0);
-            assertTrue("start_time_nanos should be in the past",
-                    state.getStartTimeNanos() < System.nanoTime());
+            assertThat(state.getUid()).isLessThan(10000);
+            assertThat(state.getPageFault()).isAtLeast(0L);
+            assertThat(state.getPageMajorFault()).isAtLeast(0L);
+            assertThat(state.getRssInBytes()).isGreaterThan(0L);
+            assertThat(state.getStartTimeNanos()).isGreaterThan(0L);
+            assertThat(state.getStartTimeNanos()).isLessThan(System.nanoTime());
         }
-        assertTrue("Did not find a matching atom for statsd", found);
+        assertWithMessage("Did not find a matching atom for statsd").that(found).isTrue();
     }
 
     public void testProcessMemoryHighWaterMark() throws Exception {
@@ -1135,13 +1123,13 @@
             return;
         }
 
-        // Get ProcessMemoryState as a simple gauge metric.
+        // Get ProcessMemoryHighWaterMark as a simple gauge metric.
         StatsdConfig.Builder config = getPulledConfig();
         addGaugeAtomWithDimensions(config, Atom.PROCESS_MEMORY_HIGH_WATER_MARK_FIELD_NUMBER, null);
         uploadConfig(config);
         Thread.sleep(WAIT_TIME_SHORT);
 
-        // Start test app and trigger a pull while its running.
+        // Start test app and trigger a pull while it is running.
         try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
                 "action.show_notification")) {
             setAppBreadcrumbPredicate();
@@ -1158,22 +1146,71 @@
             ProcessMemoryHighWaterMark state = atom.getProcessMemoryHighWaterMark();
             if (state.getUid() == uid) {
                 foundTestApp = true;
-                assertEquals(DEVICE_SIDE_TEST_PACKAGE, state.getProcessName());
-                assertTrue("rss_high_water_mark_in_bytes should be positive",
-                        state.getRssHighWaterMarkInBytes() > 0);
+                assertThat(state.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+                assertThat(state.getRssHighWaterMarkInBytes()).isGreaterThan(0L);
             } else if (state.getProcessName().contains("/statsd")) {
                 foundStatsd = true;
-                assertTrue("rss_high_water_mark_in_bytes should be positive",
-                        state.getRssHighWaterMarkInBytes() > 0);
+                assertThat(state.getRssHighWaterMarkInBytes()).isGreaterThan(0L);
             } else if (state.getProcessName().equals("system")) {
                 foundSystemServer = true;
-                assertTrue("rss_high_water_mark_in_bytes should be positive",
-                        state.getRssHighWaterMarkInBytes() > 0);
+                assertThat(state.getRssHighWaterMarkInBytes()).isGreaterThan(0L);
             }
         }
-        assertTrue("Did not find a matching atom for test app uid=" + uid, foundTestApp);
-        assertTrue("Did not find a matching atom for statsd", foundStatsd);
-        assertTrue("Did not find a matching atom for system server", foundSystemServer);
+        assertWithMessage(String.format("Did not find a matching atom for test app uid=%d",uid))
+            .that(foundTestApp).isTrue();
+        assertWithMessage("Did not find a matching atom for statsd").that(foundStatsd).isTrue();
+        assertWithMessage("Did not find a matching atom for system server")
+            .that(foundSystemServer).isTrue();
+    }
+
+    public void testProcessMemorySnapshot() throws Exception {
+        if (statsdDisabled()) {
+            return;
+        }
+
+        // Get ProcessMemorySnapshot as a simple gauge metric.
+        StatsdConfig.Builder config = getPulledConfig();
+        addGaugeAtomWithDimensions(config, Atom.PROCESS_MEMORY_SNAPSHOT_FIELD_NUMBER, null);
+        uploadConfig(config);
+        Thread.sleep(WAIT_TIME_SHORT);
+
+        // Start test app and trigger a pull while it is running.
+        try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
+                "action.show_notification")) {
+            setAppBreadcrumbPredicate();
+            Thread.sleep(WAIT_TIME_LONG);
+        }
+
+        // Assert about ProcessMemorySnapshot for the test app, statsd and system server.
+        List<Atom> atoms = getGaugeMetricDataList();
+        int uid = getUid();
+        boolean foundTestApp = false;
+        boolean foundStatsd = false;
+        boolean foundSystemServer = false;
+        for (Atom atom : atoms) {
+          ProcessMemorySnapshot snapshot = atom.getProcessMemorySnapshot();
+          if (snapshot.getUid() == uid) {
+              foundTestApp = true;
+              assertThat(snapshot.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+          } else if (snapshot.getProcessName().contains("/statsd")) {
+              foundStatsd = true;
+          } else if (snapshot.getProcessName().equals("system")) {
+              foundSystemServer = true;
+          }
+
+          assertThat(snapshot.getPid()).isGreaterThan(0);
+          assertThat(snapshot.getAnonRssAndSwapInKilobytes()).isGreaterThan(0);
+          assertThat(snapshot.getAnonRssAndSwapInKilobytes()).isEqualTo(
+                  snapshot.getAnonRssInKilobytes() + snapshot.getSwapInKilobytes());
+          assertThat(snapshot.getRssInKilobytes()).isAtLeast(0);
+          assertThat(snapshot.getAnonRssInKilobytes()).isAtLeast(0);
+          assertThat(snapshot.getSwapInKilobytes()).isAtLeast(0);
+        }
+        assertWithMessage(String.format("Did not find a matching atom for test app uid=%d",uid))
+            .that(foundTestApp).isTrue();
+        assertWithMessage("Did not find a matching atom for statsd").that(foundStatsd).isTrue();
+        assertWithMessage("Did not find a matching atom for system server")
+            .that(foundSystemServer).isTrue();
     }
 
     /**
@@ -1216,20 +1253,20 @@
         for (Atom atom : getGaugeMetricDataList()) {
             AtomsProto.RoleHolder roleHolder = atom.getRoleHolder();
 
-            assertNotNull(roleHolder.getPackageName());
-            assertTrue(roleHolder.getUid() >= 0);
-            assertNotNull(roleHolder.getRole());
+            assertThat(roleHolder.getPackageName()).isNotNull();
+            assertThat(roleHolder.getUid()).isAtLeast(0);
+            assertThat(roleHolder.getRole()).isNotNull();
 
             if (roleHolder.getPackageName().equals(DEVICE_SIDE_TEST_PACKAGE)) {
-                assertEquals(testAppId, getAppId(roleHolder.getUid()));
-                assertEquals(DEVICE_SIDE_TEST_PACKAGE, roleHolder.getPackageName());
-                assertEquals(callScreenAppRole, roleHolder.getRole());
+                assertThat(getAppId(roleHolder.getUid())).isEqualTo(testAppId);
+                assertThat(roleHolder.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+                assertThat(roleHolder.getRole()).isEqualTo(callScreenAppRole);
 
                 verifiedKnowRoleState = true;
             }
         }
 
-        assertTrue(verifiedKnowRoleState);
+        assertThat(verifiedKnowRoleState).isTrue();
     }
 
     public void testDangerousPermissionState() throws Exception {
@@ -1257,26 +1294,27 @@
         for (Atom atom : getGaugeMetricDataList()) {
             DangerousPermissionState permissionState = atom.getDangerousPermissionState();
 
-            assertNotNull(permissionState.getPermissionName());
-            assertTrue(permissionState.getUid() >= 0);
-            assertNotNull(permissionState.getPackageName());
+            assertThat(permissionState.getPermissionName()).isNotNull();
+            assertThat(permissionState.getUid()).isAtLeast(0);
+            assertThat(permissionState.getPackageName()).isNotNull();
 
             if (permissionState.getPackageName().equals(DEVICE_SIDE_TEST_PACKAGE)) {
-                assertEquals(testAppId, getAppId(permissionState.getUid()));
+                assertThat(getAppId(permissionState.getUid())).isEqualTo(testAppId);
 
                 if (permissionState.getPermissionName().equals(
                         "android.permission.ACCESS_FINE_LOCATION")) {
-                    assertTrue(permissionState.getIsGranted());
-                    assertEquals(0, permissionState.getPermissionFlags() & (~(
+                    assertThat(permissionState.getIsGranted()).isTrue();
+                    assertThat(permissionState.getPermissionFlags() & (~(
                             FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED
-                                    | FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED)));
+                            | FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED)))
+                        .isEqualTo(0);
 
                     verifiedKnowPermissionState = true;
                 }
             }
         }
 
-        assertTrue(verifiedKnowPermissionState);
+        assertThat(verifiedKnowPermissionState).isTrue();
     }
 
     public void testANROccurred() throws Exception {
@@ -1297,14 +1335,15 @@
         // Sorted list of events in order in which they occurred.
         List<EventMetricData> data = getEventMetricDataList();
 
-        assertEquals(1, data.size());
-        assertTrue(data.get(0).getAtom().hasAnrOccurred());
+        assertThat(data).hasSize(1);
+        assertThat(data.get(0).getAtom().hasAnrOccurred()).isTrue();
         ANROccurred atom = data.get(0).getAtom().getAnrOccurred();
-        assertEquals(ANROccurred.InstantApp.FALSE_VALUE, atom.getIsInstantApp().getNumber());
-        assertEquals(ANROccurred.ForegroundState.FOREGROUND_VALUE,
-                atom.getForegroundState().getNumber());
-        assertEquals(ErrorSource.DATA_APP, atom.getErrorSource());
-        assertEquals(DEVICE_SIDE_TEST_PACKAGE, atom.getPackageName());
+        assertThat(atom.getIsInstantApp().getNumber())
+            .isEqualTo(ANROccurred.InstantApp.FALSE_VALUE);
+        assertThat(atom.getForegroundState().getNumber())
+            .isEqualTo(ANROccurred.ForegroundState.FOREGROUND_VALUE);
+        assertThat(atom.getErrorSource()).isEqualTo(ErrorSource.DATA_APP);
+        assertThat(atom.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
     }
 
     public void testWriteRawTestAtom() throws Exception {
@@ -1320,80 +1359,71 @@
         Thread.sleep(WAIT_TIME_SHORT);
         // Sorted list of events in order in which they occurred.
         List<EventMetricData> data = getEventMetricDataList();
-        assertEquals(data.size(), 4);
+        assertThat(data).hasSize(4);
 
         TestAtomReported atom = data.get(0).getAtom().getTestAtomReported();
         List<AttributionNode> attrChain = atom.getAttributionNodeList();
-        assertEquals(2, attrChain.size());
-        assertEquals(1234, attrChain.get(0).getUid());
-        assertEquals("tag1", attrChain.get(0).getTag());
-        assertEquals(getUid(), attrChain.get(1).getUid());
-        assertEquals("tag2", attrChain.get(1).getTag());
+        assertThat(attrChain).hasSize(2);
+        assertThat(attrChain.get(0).getUid()).isEqualTo(1234);
+        assertThat(attrChain.get(0).getTag()).isEqualTo("tag1");
+        assertThat(attrChain.get(1).getUid()).isEqualTo(getUid());
+        assertThat(attrChain.get(1).getTag()).isEqualTo("tag2");
 
-        assertEquals(42, atom.getIntField());
-        assertEquals(Long.MAX_VALUE, atom.getLongField());
-        assertEquals(3.14f, atom.getFloatField());
-        assertEquals("This is a basic test!", atom.getStringField());
-        assertEquals(false, atom.getBooleanField());
-        assertEquals(TestAtomReported.State.ON_VALUE, atom.getState().getNumber());
-        List<Long> expIds = atom.getBytesField().getExperimentIdList();
-        assertEquals(3, expIds.size());
-        assertEquals(1L, (long) expIds.get(0));
-        assertEquals(2L, (long) expIds.get(1));
-        assertEquals(3L, (long) expIds.get(2));
+        assertThat(atom.getIntField()).isEqualTo(42);
+        assertThat(atom.getLongField()).isEqualTo(Long.MAX_VALUE);
+        assertThat(atom.getFloatField()).isEqualTo(3.14f);
+        assertThat(atom.getStringField()).isEqualTo("This is a basic test!");
+        assertThat(atom.getBooleanField()).isFalse();
+        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.ON_VALUE);
+        assertThat(atom.getBytesField().getExperimentIdList())
+            .containsExactly(1L, 2L, 3L).inOrder();
+
 
         atom = data.get(1).getAtom().getTestAtomReported();
         attrChain = atom.getAttributionNodeList();
-        assertEquals(2, attrChain.size());
-        assertEquals(9999, attrChain.get(0).getUid());
-        assertEquals("tag9999", attrChain.get(0).getTag());
-        assertEquals(getUid(), attrChain.get(1).getUid());
-        assertEquals("", attrChain.get(1).getTag());
+        assertThat(attrChain).hasSize(2);
+        assertThat(attrChain.get(0).getUid()).isEqualTo(9999);
+        assertThat(attrChain.get(0).getTag()).isEqualTo("tag9999");
+        assertThat(attrChain.get(1).getUid()).isEqualTo(getUid());
+        assertThat(attrChain.get(1).getTag()).isEmpty();
 
-        assertEquals(100, atom.getIntField());
-        assertEquals(Long.MIN_VALUE, atom.getLongField());
-        assertEquals(-2.5f, atom.getFloatField());
-        assertEquals("Test null uid", atom.getStringField());
-        assertEquals(true, atom.getBooleanField());
-        assertEquals(TestAtomReported.State.UNKNOWN_VALUE, atom.getState().getNumber());
-        expIds = atom.getBytesField().getExperimentIdList();
-        assertEquals(3, expIds.size());
-        assertEquals(1L, (long) expIds.get(0));
-        assertEquals(2L, (long) expIds.get(1));
-        assertEquals(3L, (long) expIds.get(2));
+        assertThat(atom.getIntField()).isEqualTo(100);
+        assertThat(atom.getLongField()).isEqualTo(Long.MIN_VALUE);
+        assertThat(atom.getFloatField()).isEqualTo(-2.5f);
+        assertThat(atom.getStringField()).isEqualTo("Test null uid");
+        assertThat(atom.getBooleanField()).isTrue();
+        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.UNKNOWN_VALUE);
+        assertThat(atom.getBytesField().getExperimentIdList())
+            .containsExactly(1L, 2L, 3L).inOrder();
 
         atom = data.get(2).getAtom().getTestAtomReported();
         attrChain = atom.getAttributionNodeList();
-        assertEquals(1, attrChain.size());
-        assertEquals(getUid(), attrChain.get(0).getUid());
-        assertEquals("tag1", attrChain.get(0).getTag());
+        assertThat(attrChain).hasSize(1);
+        assertThat(attrChain.get(0).getUid()).isEqualTo(getUid());
+        assertThat(attrChain.get(0).getTag()).isEqualTo("tag1");
 
-        assertEquals(-256, atom.getIntField());
-        assertEquals(-1234567890L, atom.getLongField());
-        assertEquals(42.01f, atom.getFloatField());
-        assertEquals("Test non chained", atom.getStringField());
-        assertEquals(true, atom.getBooleanField());
-        assertEquals(TestAtomReported.State.OFF_VALUE, atom.getState().getNumber());
-        expIds = atom.getBytesField().getExperimentIdList();
-        assertEquals(3, expIds.size());
-        assertEquals(1L, (long) expIds.get(0));
-        assertEquals(2L, (long) expIds.get(1));
-        assertEquals(3L, (long) expIds.get(2));
+        assertThat(atom.getIntField()).isEqualTo(-256);
+        assertThat(atom.getLongField()).isEqualTo(-1234567890L);
+        assertThat(atom.getFloatField()).isEqualTo(42.01f);
+        assertThat(atom.getStringField()).isEqualTo("Test non chained");
+        assertThat(atom.getBooleanField()).isTrue();
+        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.OFF_VALUE);
+        assertThat(atom.getBytesField().getExperimentIdList())
+            .containsExactly(1L, 2L, 3L).inOrder();
 
         atom = data.get(3).getAtom().getTestAtomReported();
         attrChain = atom.getAttributionNodeList();
-        assertEquals(1, attrChain.size());
-        assertEquals(getUid(), attrChain.get(0).getUid());
-        assertEquals("", attrChain.get(0).getTag());
+        assertThat(attrChain).hasSize(1);
+        assertThat(attrChain.get(0).getUid()).isEqualTo(getUid());
+        assertThat(attrChain.get(0).getTag()).isEmpty();
 
-        assertEquals(0, atom.getIntField());
-        assertEquals(0L, atom.getLongField());
-        assertEquals(0f, atom.getFloatField());
-        assertEquals("", atom.getStringField());
-        assertEquals(true, atom.getBooleanField());
-        assertEquals(TestAtomReported.State.OFF_VALUE, atom.getState().getNumber());
-        expIds = atom.getBytesField().getExperimentIdList();
-        assertEquals(0, expIds.size());
+        assertThat(atom.getIntField()).isEqualTo(0);
+        assertThat(atom.getLongField()).isEqualTo(0L);
+        assertThat(atom.getFloatField()).isEqualTo(0f);
+        assertThat(atom.getStringField()).isEmpty();
+        assertThat(atom.getBooleanField()).isTrue();
+        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.OFF_VALUE);
+        assertThat(atom.getBytesField().getExperimentIdList()).isEmpty();
     }
 
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java b/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
index e92e7b2..4c0e4e6 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.metadata;
 
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.cts.statsd.atom.AtomTestCase;
 
 import com.android.internal.os.StatsdConfigProto;
@@ -61,13 +63,14 @@
         for (ConfigStats stats: report.getConfigStatsList()) {
             if (stats.getId() == CONFIG_ID && stats.getUid() == getHostUid()) {
                 if(!stats.hasDeletionTimeSec()) {
-                    assertTrue("Found multiple active CTS configs!", foundActiveConfig == false);
+                    assertWithMessage("Found multiple active CTS configs!")
+                            .that(foundActiveConfig).isFalse();
                     foundActiveConfig = true;
                     creationTime = stats.getCreationTimeSec();
                 }
             }
         }
-        assertTrue("Did not find an active CTS config", foundActiveConfig);
+        assertWithMessage("Did not find an active CTS config").that(foundActiveConfig).isTrue();
 
         while(System.currentTimeMillis() - startTime < 8_000) {
             Thread.sleep(10);
@@ -81,26 +84,29 @@
             if (stats.getId() == CONFIG_ID && stats.getUid() == getHostUid()) {
                 // Original config should be TTL'd
                 if (stats.getCreationTimeSec() == creationTime) {
-                    assertTrue("Config should have TTL'd but is still active",
-                            stats.hasDeletionTimeSec());
-                    assertTrue("Config deletion time should be about " + TTL_TIME_SEC +
-                            " after creation",
-                            Math.abs(stats.getDeletionTimeSec() - expectedTime) <= 2);
+                    assertWithMessage("Config should have TTL'd but is still active")
+                            .that(stats.hasDeletionTimeSec()).isTrue();
+                    assertWithMessage(
+                            "Config deletion time should be about %s after creation", TTL_TIME_SEC
+                    ).that(Math.abs(stats.getDeletionTimeSec() - expectedTime)).isAtMost(2);
                 }
                 // There should still be one active config, that is marked as reset.
                 if(!stats.hasDeletionTimeSec()) {
-                    assertTrue("Found multiple active CTS configs!", foundActiveConfig == false);
+                    assertWithMessage("Found multiple active CTS configs!")
+                            .that(foundActiveConfig).isFalse();
                     foundActiveConfig = true;
                     creationTime = stats.getCreationTimeSec();
-                    assertTrue("Active config after TTL should be marked as reset",
-                            stats.hasResetTimeSec());
-                    assertEquals("Reset time and creation time should be equal for TTl'd configs",
-                            stats.getResetTimeSec(), stats.getCreationTimeSec());
-                    assertTrue("Reset config should be created when the original config TTL'd",
-                            Math.abs(stats.getCreationTimeSec() - expectedTime) <= 2);
+                    assertWithMessage("Active config after TTL should be marked as reset")
+                            .that(stats.hasResetTimeSec()).isTrue();
+                    assertWithMessage("Reset and creation time should be equal for TTl'd configs")
+                            .that(stats.getResetTimeSec()).isEqualTo(stats.getCreationTimeSec());
+                    assertWithMessage(
+                            "Reset config should be created when the original config TTL'd"
+                    ).that(Math.abs(stats.getCreationTimeSec() - expectedTime)).isAtMost(2);
                 }
             }
         }
-        assertTrue("Did not find an active CTS config after the TTL", foundActiveConfig);
+        assertWithMessage("Did not find an active CTS config after the TTL")
+                .that(foundActiveConfig).isTrue();
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
index 70777ef..4eeb74c 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
@@ -15,6 +15,9 @@
  */
 package android.cts.statsd.metric;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.cts.statsd.atom.DeviceAtomTestCase;
 
 import com.android.internal.os.StatsdConfigProto;
@@ -53,13 +56,13 @@
 
         StatsLogReport metricReport = getStatsLogReport();
         LogUtil.CLog.d("Got the following stats log report: \n" + metricReport.toString());
-        assertEquals(MetricsUtils.COUNT_METRIC_ID, metricReport.getMetricId());
-        assertTrue(metricReport.hasCountMetrics());
+        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
+        assertThat(metricReport.hasCountMetrics()).isTrue();
 
         StatsLogReport.CountMetricDataWrapper countData = metricReport.getCountMetrics();
 
-        assertTrue(countData.getDataCount() > 0);
-        assertEquals(2, countData.getData(0).getBucketInfo(0).getCount());
+        assertThat(countData.getDataCount()).isGreaterThan(0);
+        assertThat(countData.getData(0).getBucketInfo(0).getCount()).isEqualTo(2);
     }
     public void testEventCountWithCondition() throws Exception {
         if (statsdDisabled()) {
@@ -112,13 +115,13 @@
         Thread.sleep(2000);  // Wait for the metrics to propagate to statsd.
 
         StatsLogReport metricReport = getStatsLogReport();
-        assertEquals(MetricsUtils.COUNT_METRIC_ID, metricReport.getMetricId());
-        assertTrue(metricReport.hasCountMetrics());
+        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
+        assertThat(metricReport.hasCountMetrics()).isTrue();
 
         StatsLogReport.CountMetricDataWrapper countData = metricReport.getCountMetrics();
 
-        assertTrue(countData.getDataCount() > 0);
-        assertEquals(1, countData.getData(0).getBucketInfo(0).getCount());
+        assertThat(countData.getDataCount()).isGreaterThan(0);
+        assertThat(countData.getData(0).getBucketInfo(0).getCount()).isEqualTo(1);
     }
 
     public void testEventCountWithConditionAndActivation() throws Exception {
@@ -236,16 +239,16 @@
         Thread.sleep(2000);
 
         StatsLogReport metricReport = getStatsLogReport();
-        assertEquals(MetricsUtils.COUNT_METRIC_ID, metricReport.getMetricId());
+        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
         LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertTrue(metricReport.hasCountMetrics());
-        assertFalse(metricReport.getIsActive());
+        assertThat(metricReport.hasCountMetrics()).isTrue();
+        assertThat(metricReport.getIsActive()).isFalse();
 
         StatsLogReport.CountMetricDataWrapper countData = metricReport.getCountMetrics();
-        assertEquals(1, countData.getDataCount());
-        assertEquals(2, countData.getData(0).getBucketInfoCount());
-        assertEquals(2, countData.getData(0).getBucketInfo(0).getCount());
-        assertEquals(1, countData.getData(0).getBucketInfo(1).getCount());
+        assertThat(countData.getDataCount()).isEqualTo(1);
+        assertThat(countData.getData(0).getBucketInfoCount()).isEqualTo(2);
+        assertThat(countData.getData(0).getBucketInfo(0).getCount()).isEqualTo(2);
+        assertThat(countData.getData(0).getBucketInfo(1).getCount()).isEqualTo(1);
     }
 
     public void testPartialBucketCountMetric() throws Exception {
@@ -273,17 +276,14 @@
         ConfigMetricsReportList reports = getReportList();
         LogUtil.CLog.d("Got following report list: " + reports.toString());
 
-        assertEquals("Expected 2 reports, got " + reports.getReportsCount(),
-                2, reports.getReportsCount());
+        assertThat(reports.getReportsCount()).isEqualTo(2);
         boolean inOrder = reports.getReports(0).getCurrentReportWallClockNanos() <
                 reports.getReports(1).getCurrentReportWallClockNanos();
 
         // Only 1 metric, so there should only be 1 StatsLogReport.
         for (ConfigMetricsReport report : reports.getReportsList()) {
-            assertEquals("Expected 1 StatsLogReport in each ConfigMetricsReport",
-                    1, report.getMetricsCount());
-            assertEquals("Expected 1 CountMetricData in each report",
-                    1, report.getMetrics(0).getCountMetrics().getDataCount());
+            assertThat(report.getMetricsCount()).isEqualTo(1);
+            assertThat(report.getMetrics(0).getCountMetrics().getDataCount()).isEqualTo(1);
         }
         CountMetricData data1 =
                 reports.getReports(inOrder? 0 : 1).getMetrics(0).getCountMetrics().getData(0);
@@ -291,19 +291,20 @@
                 reports.getReports(inOrder? 1 : 0).getMetrics(0).getCountMetrics().getData(0);
         // Data1 should have only 1 bucket, and it should be a partial bucket.
         // The count should be 1.
-        assertEquals("First report should only have 1 bucket", 1, data1.getBucketInfoCount());
+        assertThat(data1.getBucketInfoCount()).isEqualTo(1);
         CountBucketInfo bucketInfo = data1.getBucketInfo(0);
-        assertEquals("First report should have a count of 1", 1, bucketInfo.getCount());
-        assertTrue("First report's bucket should be less than 1 day",
-                bucketInfo.getEndBucketElapsedNanos() <
-                (bucketInfo.getStartBucketElapsedNanos() + 1_000_000_000L * 60L * 60L * 24L));
+        assertThat(bucketInfo.getCount()).isEqualTo(1);
+        assertWithMessage("First report's bucket should be less than 1 day")
+                .that(bucketInfo.getEndBucketElapsedNanos())
+                .isLessThan(bucketInfo.getStartBucketElapsedNanos() + 
+                        1_000_000_000L * 60L * 60L * 24L);
 
         //Second report should have a count of 2.
-        assertTrue("Second report should have at most 2 buckets", data2.getBucketInfoCount() < 3);
+        assertThat(data2.getBucketInfoCount()).isAtMost(2);
         int totalCount = 0;
         for (CountBucketInfo bucket : data2.getBucketInfoList()) {
             totalCount += bucket.getCount();
         }
-        assertEquals("Second report should have a count of 2", 2, totalCount);
+        assertThat(totalCount).isEqualTo(2);
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java
index 4bd5a2a..16c3baf 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java
@@ -122,30 +122,30 @@
 
       StatsLogReport metricReport = getStatsLogReport();
       LogUtil.CLog.d("Got the following gauge metric data: " + metricReport.toString());
-      assertEquals(MetricsUtils.GAUGE_METRIC_ID, metricReport.getMetricId());
-      assertTrue(metricReport.hasGaugeMetrics());
+      assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.GAUGE_METRIC_ID);
+      assertThat(metricReport.hasGaugeMetrics()).isTrue();
       StatsLogReport.GaugeMetricDataWrapper gaugeData = metricReport.getGaugeMetrics();
-      assertEquals(gaugeData.getDataCount(), 1);
+      assertThat(gaugeData.getDataCount()).isEqualTo(1);
 
       int bucketCount = gaugeData.getData(0).getBucketInfoCount();
       GaugeMetricData data = gaugeData.getData(0);
-      assertTrue(bucketCount > 2);
+      assertThat(bucketCount).isGreaterThan(2);
       MetricsUtils.assertBucketTimePresent(data.getBucketInfo(0));
-      assertEquals(data.getBucketInfo(0).getAtomCount(), 1);
-      assertEquals(data.getBucketInfo(0).getAtom(0).getAppBreadcrumbReported().getLabel(), 0);
-      assertEquals(data.getBucketInfo(0).getAtom(0).getAppBreadcrumbReported().getState(),
-          AppBreadcrumbReported.State.START);
+      assertThat(data.getBucketInfo(0).getAtomCount()).isEqualTo(1);
+      assertThat(data.getBucketInfo(0).getAtom(0).getAppBreadcrumbReported().getLabel())
+              .isEqualTo(0);
+      assertThat(data.getBucketInfo(0).getAtom(0).getAppBreadcrumbReported().getState())
+              .isEqualTo(AppBreadcrumbReported.State.START);
 
       MetricsUtils.assertBucketTimePresent(data.getBucketInfo(1));
-      assertEquals(data.getBucketInfo(1).getAtomCount(), 1);
+      assertThat(data.getBucketInfo(1).getAtomCount()).isEqualTo(1);
 
       MetricsUtils.assertBucketTimePresent(data.getBucketInfo(bucketCount-1));
-      assertEquals(data.getBucketInfo(bucketCount - 1).getAtomCount(), 1);
-      assertEquals(
-          data.getBucketInfo(bucketCount - 1).getAtom(0).getAppBreadcrumbReported().getLabel(), 2);
-      assertEquals(
-          data.getBucketInfo(bucketCount - 1).getAtom(0).getAppBreadcrumbReported().getState(),
-          AppBreadcrumbReported.State.STOP);
+      assertThat(data.getBucketInfo(bucketCount-1).getAtomCount()).isEqualTo(1);
+      assertThat(data.getBucketInfo(bucketCount-1).getAtom(0).getAppBreadcrumbReported().getLabel())
+              .isEqualTo(2);
+      assertThat(data.getBucketInfo(bucketCount-1).getAtom(0).getAppBreadcrumbReported().getState())
+              .isEqualTo(AppBreadcrumbReported.State.STOP);
   }
 
   public void testPulledGaugeMetricWithActivation() throws Exception {
@@ -197,8 +197,8 @@
 
       StatsLogReport metricReport = getStatsLogReport();
       LogUtil.CLog.d("Got the following gauge metric data: " + metricReport.toString());
-      assertEquals(MetricsUtils.GAUGE_METRIC_ID, metricReport.getMetricId());
-      assertFalse(metricReport.hasGaugeMetrics());
+      assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.GAUGE_METRIC_ID);
+      assertThat(metricReport.hasGaugeMetrics()).isFalse();
   }
 
     public void testPulledGaugeMetricWithConditionAndActivation() throws Exception {
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
index 803dd2e..b976678 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.metric;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import android.cts.statsd.atom.DeviceAtomTestCase;
 
 import com.android.internal.os.StatsdConfigProto;
@@ -374,7 +376,7 @@
 
         ConfigMetricsReportList reportList = getReportList();
         List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
-        assertEquals(3, reports.size());
+        assertThat(reports).hasSize(3);
 
         // Report before restart.
         ConfigMetricsReport report = reports.get(0);
@@ -510,7 +512,7 @@
 
         ConfigMetricsReportList reportList = getReportList();
         List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
-        assertEquals(3, reports.size());
+        assertThat(reports).hasSize(3);
 
         // Report before restart.
         ConfigMetricsReport report = reports.get(0);
@@ -538,7 +540,7 @@
 
     private void verifyMetrics(ConfigMetricsReport report, int metric1Count, int metric2Count,
             int metric3Count) throws Exception {
-        assertEquals(3, report.getMetricsCount());
+        assertThat(report.getMetricsCount()).isEqualTo(3);
 
         verifyMetric(
                 report.getMetrics(0),   // StatsLogReport
@@ -563,17 +565,14 @@
     private void verifyMetric(StatsLogReport metricReport, long metricId, int metricMatcherLabel,
             int dataCount) {
         LogUtil.CLog.d("Got the following event metric data: " + metricReport.toString());
-        assertEquals(metricId, metricReport.getMetricId());
-        if (dataCount > 0) {
-            assertTrue(metricReport.hasEventMetrics());
-        } else {
-            assertFalse(metricReport.hasEventMetrics());
-        }
+        assertThat(metricReport.getMetricId()).isEqualTo(metricId);
+        assertThat(metricReport.hasEventMetrics()).isEqualTo(dataCount > 0);
+
         StatsLogReport.EventMetricDataWrapper eventData = metricReport.getEventMetrics();
-        assertEquals(dataCount, eventData.getDataCount());
+        assertThat(eventData.getDataCount()).isEqualTo(dataCount);
         for (int i = 0; i < eventData.getDataCount(); i++) {
             AppBreadcrumbReported atom = eventData.getData(i).getAtom().getAppBreadcrumbReported();
-            assertEquals(metricMatcherLabel, atom.getLabel());
+            assertThat(atom.getLabel()).isEqualTo(metricMatcherLabel);
         }
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java
index 2677634..7097587 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.metric;
 
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import com.android.internal.os.StatsdConfigProto;
 import com.android.internal.os.StatsdConfigProto.AtomMatcher;
 import com.android.internal.os.StatsdConfigProto.EventActivation;
@@ -26,8 +28,6 @@
 import com.google.protobuf.Descriptors.Descriptor;
 import com.google.protobuf.Descriptors.FieldDescriptor;
 
-import static org.junit.Assert.assertTrue;
-
 public class MetricsUtils {
     public static final long COUNT_METRIC_ID = 3333;
     public static final long DURATION_METRIC_ID = 4444;
@@ -156,7 +156,8 @@
                    endMillis != null && bucketInfo.hasField(endMillis)) {
             found = true;
         }
-        assertTrue("Bucket info did not have either bucket num or start and end elapsed millis",
-                found);
+        assertWithMessage(
+                "Bucket info did not have either bucket num or start and end elapsed millis"
+        ).that(found).isTrue();
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java
index 25c06e3..2b2eee7 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java
@@ -94,22 +94,22 @@
 
     StatsLogReport metricReport = getStatsLogReport();
     LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertEquals(MetricsUtils.VALUE_METRIC_ID, metricReport.getMetricId());
-    assertTrue(metricReport.hasValueMetrics());
+    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
+    assertThat(metricReport.hasValueMetrics()).isTrue();
     StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-    assertEquals(1, valueData.getDataCount());
+    assertThat(valueData.getDataCount()).isEqualTo(1);
 
     int bucketCount = valueData.getData(0).getBucketInfoCount();
-    assertTrue(bucketCount > 1);
+    assertThat(bucketCount).isGreaterThan(1);
     ValueMetricData data = valueData.getData(0);
     int totalValue = 0;
     for (ValueBucketInfo bucketInfo : data.getBucketInfoList()) {
       MetricsUtils.assertBucketTimePresent(bucketInfo);
-      assertEquals(1, bucketInfo.getValuesCount());
-      assertEquals(0, bucketInfo.getValues(0).getIndex());
+      assertThat(bucketInfo.getValuesCount()).isEqualTo(1);
+      assertThat(bucketInfo.getValues(0).getIndex()).isEqualTo(0);
       totalValue += (int) bucketInfo.getValues(0).getValueLong();
     }
-    assertEquals(8, totalValue);
+    assertThat(totalValue).isEqualTo(8);
   }
 
   // Test value metric with pulled atoms and across multiple buckets
@@ -172,24 +172,24 @@
 
     StatsLogReport metricReport = getStatsLogReport();
     LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertEquals(MetricsUtils.VALUE_METRIC_ID, metricReport.getMetricId());
-    assertTrue(metricReport.hasValueMetrics());
+    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
+    assertThat(metricReport.hasValueMetrics()).isTrue();
     StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-    assertEquals(valueData.getDataCount(), 1);
+    assertThat(valueData.getDataCount()).isEqualTo(1);
 
     int bucketCount = valueData.getData(0).getBucketInfoCount();
     // should have at least 2 buckets
-    assertTrue(bucketCount >= 2);
+    assertThat(bucketCount).isAtLeast(2);
     ValueMetricData data = valueData.getData(0);
     int totalValue = 0;
     for (ValueBucketInfo bucketInfo : data.getBucketInfoList()) {
       MetricsUtils.assertBucketTimePresent(bucketInfo);
-      assertEquals(1, bucketInfo.getValuesCount());
-      assertEquals(0, bucketInfo.getValues(0).getIndex());
+      assertThat(bucketInfo.getValuesCount()).isEqualTo(1);
+      assertThat(bucketInfo.getValues(0).getIndex()).isEqualTo(0);
       totalValue += (int) bucketInfo.getValues(0).getValueLong();
     }
     // At most we lose one full min bucket
-    assertTrue(totalValue > (130_000 - 60_000));
+    assertThat(totalValue).isGreaterThan(130_000 - 60_000);
   }
 
   // Test value metric with pulled atoms and across multiple buckets
@@ -256,24 +256,24 @@
 
     StatsLogReport metricReport = getStatsLogReport();
     LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertEquals(MetricsUtils.VALUE_METRIC_ID, metricReport.getMetricId());
-    assertTrue(metricReport.hasValueMetrics());
+    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
+    assertThat(metricReport.hasValueMetrics()).isTrue();
     StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-    assertEquals(valueData.getDataCount(), 1);
+    assertThat(valueData.getDataCount()).isEqualTo(1);
 
     int bucketCount = valueData.getData(0).getBucketInfoCount();
     // should have at least 2 buckets
-    assertTrue(bucketCount >= 2);
+    assertThat(bucketCount).isAtLeast(2);
     ValueMetricData data = valueData.getData(0);
     int totalValue = 0;
     for (ValueBucketInfo bucketInfo : data.getBucketInfoList()) {
       MetricsUtils.assertBucketTimePresent(bucketInfo);
-      assertEquals(1, bucketInfo.getValuesCount());
-      assertEquals(0, bucketInfo.getValues(0).getIndex());
+      assertThat(bucketInfo.getValuesCount()).isEqualTo(1);
+      assertThat(bucketInfo.getValues(0).getIndex()).isEqualTo(0);
       totalValue += (int) bucketInfo.getValues(0).getValueLong();
     }
     // At most we lose one full min bucket
-    assertTrue(totalValue > (GAP_INTERVAL*NUM_EVENTS - 60_000));
+    assertThat((long) totalValue).isGreaterThan(GAP_INTERVAL * NUM_EVENTS - 60_000);
   }
 
   // Test value metric with pulled atoms and across multiple buckets
@@ -329,8 +329,8 @@
 
     StatsLogReport metricReport = getStatsLogReport();
     LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertEquals(MetricsUtils.VALUE_METRIC_ID, metricReport.getMetricId());
-    assertFalse(metricReport.hasValueMetrics());
+    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
+    assertThat(metricReport.hasValueMetrics()).isFalse();
   }
 
     public void testValueMetricWithConditionAndActivation() throws Exception {
diff --git a/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java b/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java
index f8aa3b7..f239f0e 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.subscriber;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import com.android.compatibility.common.util.CpuFeatures;
 import com.android.internal.os.StatsdConfigProto;
 import com.android.os.AtomsProto;
@@ -79,7 +81,7 @@
         startSubscription(config, receiver, 10);
         byte[] output = receiver.getOutput();
         // There should be at lease some data returned.
-        assertTrue(output.length > sizetBytes);
+        assertThat(output.length).isGreaterThan(sizetBytes);
 
         int atomCount = 0;
         int i = 0;
@@ -98,8 +100,8 @@
                 ShellDataProto.ShellData data =
                         ShellDataProto.ShellData.parseFrom(
                                 Arrays.copyOfRange(output, i + sizetBytes, i + sizetBytes + len));
-                assertTrue(data.getAtomCount() > 0);
-                assertTrue(data.getAtom(0).hasSystemUptime());
+                assertThat(data.getAtomCount()).isGreaterThan(0);
+                assertThat(data.getAtom(0).hasSystemUptime()).isTrue();
                 atomCount++;
                 LogUtil.CLog.d("Received " + data.toString());
             } catch (InvalidProtocolBufferException e) {
@@ -108,7 +110,7 @@
             i += (sizetBytes + len);
         }
 
-        assertTrue(atomCount > 0);
+        assertThat(atomCount).isGreaterThan(0);
     }
 
     private void startSubscription(ShellConfig.ShellSubscription config,
diff --git a/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java b/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java
index bf599d3f..dab7f0f 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java
@@ -15,7 +15,7 @@
  */
 package android.cts.statsd.uidmap;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.cts.statsd.atom.DeviceAtomTestCase;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
@@ -40,15 +40,15 @@
         createAndUploadConfig(AtomsProto.Atom.UID_PROCESS_STATE_CHANGED_FIELD_NUMBER);
 
         ConfigMetricsReportList reports = getReportList();
-        assertTrue(reports.getReportsCount() > 0);
+        assertThat(reports.getReportsCount()).isGreaterThan(0);
 
         for (ConfigMetricsReport report : reports.getReportsList()) {
             UidMapping uidmap = report.getUidMap();
-            assertTrue(uidmap.getSnapshotsCount() > 0);
+            assertThat(uidmap.getSnapshotsCount()).isGreaterThan(0);
             for (PackageInfoSnapshot snapshot : uidmap.getSnapshotsList()) {
                 // There must be at least one element in each snapshot (at least one package is
                 // installed).
-                assertTrue(snapshot.getPackageInfoCount() > 0);
+                assertThat(snapshot.getPackageInfoCount()).isGreaterThan(0);
             }
         }
     }
@@ -81,7 +81,7 @@
         Thread.sleep(WAIT_TIME_SHORT);
 
         ConfigMetricsReportList reports = getReportList();
-        assertTrue(reports.getReportsCount() > 0);
+        assertThat(reports.getReportsCount()).isGreaterThan(0);
 
         boolean found = false;
         int uid = getUid();
@@ -91,7 +91,7 @@
                 found = true;
             }
         }
-        assertTrue(found);
+        assertThat(found).isTrue();
     }
 
     // We check that a re-installation gives a change event (similar to an app upgrade).
@@ -108,7 +108,7 @@
         Thread.sleep(WAIT_TIME_SHORT);
 
         ConfigMetricsReportList reports = getReportList();
-        assertTrue(reports.getReportsCount() > 0);
+        assertThat(reports.getReportsCount()).isGreaterThan(0);
 
         boolean found = false;
         int uid = getUid();
@@ -118,7 +118,7 @@
                 found = true;
             }
         }
-        assertTrue(found);
+        assertThat(found).isTrue();
     }
 
     public void testChangeFromUninstall() throws Exception {
@@ -134,7 +134,7 @@
         Thread.sleep(WAIT_TIME_SHORT);
 
         ConfigMetricsReportList reports = getReportList();
-        assertTrue(reports.getReportsCount() > 0);
+        assertThat(reports.getReportsCount()).isGreaterThan(0);
 
         boolean found = false;
         for (ConfigMetricsReport report : reports.getReportsList()) {
@@ -143,6 +143,6 @@
                 found = true;
             }
         }
-        assertTrue(found);
+        assertThat(found).isTrue();
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
index 7b95933..dc3e23b 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
@@ -15,8 +15,8 @@
  */
 package android.cts.statsd.validation;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.cts.statsd.atom.DeviceAtomTestCase;
 import android.os.BatteryStatsProto;
@@ -70,11 +70,11 @@
 
         BatteryStatsProto batterystatsProto = getBatteryStatsProto();
         List<CountMetricData> countMetricData = getCountMetricDataList();
-        assertEquals(1, countMetricData.size());
-        assertEquals(1, countMetricData.get(0).getBucketInfoCount());
-        assertTrue(countMetricData.get(0).getBucketInfo(0).getCount() >= 2);
-        assertEquals(batterystatsProto.getSystem().getMisc().getNumConnectivityChanges(),
-                countMetricData.get(0).getBucketInfo(0).getCount());
+        assertThat(countMetricData).hasSize(1);
+        assertThat(countMetricData.get(0).getBucketInfoCount()).isEqualTo(1);
+        assertThat(countMetricData.get(0).getBucketInfo(0).getCount()).isAtLeast(2L);
+        assertThat(countMetricData.get(0).getBucketInfo(0).getCount()).isEqualTo(
+                (long) batterystatsProto.getSystem().getMisc().getNumConnectivityChanges());
     }
 
     public void testPowerUse() throws Exception {
@@ -104,19 +104,16 @@
         // Extract statsd data
         Atom atom = atomList.get(0);
         long statsdPowerNas = atom.getDeviceCalculatedPowerUse().getComputedPowerNanoAmpSecs();
-        assertTrue("Statsd: Non-positive power value.", statsdPowerNas > 0);
+        assertThat(statsdPowerNas).isGreaterThan(0L);
 
         // Extract BatteryStats data
         double bsPowerNas = batterystatsProto.getSystem().getPowerUseSummary().getComputedPowerMah()
                 * 1_000_000L * 3600L; /* mAh to nAs */
-        assertTrue("BatteryStats: Non-positive power value.", bsPowerNas > 0);
+        assertThat(bsPowerNas).isGreaterThan(0d);
 
-        assertTrue(
-                String.format("Statsd (%d) < Batterystats (%f)", statsdPowerNas, bsPowerNas),
-                statsdPowerNas > ALLOWED_FRACTIONAL_DIFFERENCE * bsPowerNas);
-        assertTrue(
-                String.format("Batterystats (%f) < Statsd (%d)", bsPowerNas, statsdPowerNas),
-                bsPowerNas > ALLOWED_FRACTIONAL_DIFFERENCE * statsdPowerNas);
+        assertThat((double) statsdPowerNas)
+                .isGreaterThan(ALLOWED_FRACTIONAL_DIFFERENCE * bsPowerNas);
+        assertThat(bsPowerNas).isGreaterThan(ALLOWED_FRACTIONAL_DIFFERENCE * statsdPowerNas);
     }
 
     public void testPowerBlameUid() throws Exception {
@@ -151,13 +148,15 @@
         for (Atom atom : atomList) {
             DeviceCalculatedPowerBlameUid item = atom.getDeviceCalculatedPowerBlameUid();
             if (item.getUid() == uid) {
-                assertFalse("Found multiple power values for uid " + uid, uidFound);
+                assertWithMessage("Found multiple power values for uid %s", uid)
+                        .that(uidFound).isFalse();
                 uidFound = true;
                 statsdUidPowerNas = item.getPowerNanoAmpSecs();
             }
         }
-        assertTrue("Statsd: No power value for uid " + uid, uidFound);
-        assertTrue("Statsd: Non-positive power value for uid " + uid, statsdUidPowerNas > 0);
+        assertWithMessage("Statsd: No power value for uid %s", uid).that(uidFound).isTrue();
+        assertWithMessage("Statsd: Non-positive power value for uid %s", uid)
+                .that(statsdUidPowerNas).isGreaterThan(0L);
 
         // Extract batterystats data
         double bsUidPowerNas = -1;
@@ -169,15 +168,13 @@
                         * 1_000_000L * 3600L; /* mAh to nAs */;
             }
         }
-        assertTrue("Batterystats: No power value for uid " + uid, hadUid);
-        assertTrue("BatteryStats: Non-positive power value for uid " + uid, bsUidPowerNas > 0);
+        assertWithMessage("Batterystats: No power value for uid %s", uid).that(hadUid).isTrue();
+        assertWithMessage("BatteryStats: Non-positive power value for uid %s", uid)
+                .that(bsUidPowerNas).isGreaterThan(0d);
 
-        assertTrue(
-                String.format("Statsd (%d) < Batterystats (%f).", statsdUidPowerNas, bsUidPowerNas),
-                statsdUidPowerNas > ALLOWED_FRACTIONAL_DIFFERENCE * bsUidPowerNas);
-        assertTrue(
-                String.format("Batterystats (%f) < Statsd (%d).", bsUidPowerNas, statsdUidPowerNas),
-                bsUidPowerNas > ALLOWED_FRACTIONAL_DIFFERENCE * statsdUidPowerNas);
+        assertThat((double) statsdUidPowerNas)
+                .isGreaterThan(ALLOWED_FRACTIONAL_DIFFERENCE * bsUidPowerNas);
+        assertThat(bsUidPowerNas).isGreaterThan(ALLOWED_FRACTIONAL_DIFFERENCE * statsdUidPowerNas);
     }
 
     public void testServiceStartCount() throws Exception {
@@ -192,16 +189,17 @@
 
         BatteryStatsProto batterystatsProto = getBatteryStatsProto();
         List<CountMetricData> countMetricData = getCountMetricDataList();
-        assertTrue(countMetricData.size() > 0);
+        assertThat(countMetricData).isNotEmpty();
         int uid = getUid();
         long countFromStatsd = 0;
         for (CountMetricData data : countMetricData) {
             List<DimensionsValue> dims = data.getDimensionLeafValuesInWhatList();
             if (dims.get(0).getValueInt() == uid) {
-                assertEquals(DEVICE_SIDE_TEST_PACKAGE, dims.get(1).getValueStr());
-                assertEquals(dims.get(2).getValueStr(), DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME);
+                assertThat(dims.get(1).getValueStr()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+                assertThat(dims.get(2).getValueStr())
+                        .isEqualTo(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME);
                 countFromStatsd = data.getBucketInfo(0).getCount();
-                assertTrue(countFromStatsd > 0);
+                assertThat(countFromStatsd).isGreaterThan(0L);
             }
         }
         long countFromBS = 0;
@@ -212,16 +210,16 @@
                         for (Service svc : pkg.getServicesList()) {
                             if (svc.getName().equals(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME)) {
                                 countFromBS = svc.getStartCount();
-                                assertTrue(countFromBS > 0);
+                                assertThat(countFromBS).isGreaterThan(0L);
                             }
                         }
                     }
                 }
             }
         }
-        assertTrue(countFromStatsd > 0);
-        assertTrue(countFromBS > 0);
-        assertEquals(countFromBS, countFromStatsd);
+        assertThat(countFromStatsd).isGreaterThan(0L);
+        assertThat(countFromBS).isGreaterThan(0L);
+        assertThat(countFromBS).isEqualTo(countFromStatsd);
     }
 
     public void testServiceLaunchCount() throws Exception {
@@ -236,16 +234,17 @@
 
         BatteryStatsProto batterystatsProto = getBatteryStatsProto();
         List<CountMetricData> countMetricData = getCountMetricDataList();
-        assertTrue(countMetricData.size() > 0);
+        assertThat(countMetricData).isNotEmpty();
         int uid = getUid();
         long countFromStatsd = 0;
         for (CountMetricData data : countMetricData) {
             List<DimensionsValue> dims = data.getDimensionLeafValuesInWhatList();
             if (dims.get(0).getValueInt() == uid) {
-                assertEquals(DEVICE_SIDE_TEST_PACKAGE, dims.get(1).getValueStr());
-                assertEquals(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME, dims.get(2).getValueStr());
+                assertThat(dims.get(1).getValueStr()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
+                assertThat(dims.get(2).getValueStr())
+                        .isEqualTo(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME);
                 countFromStatsd = data.getBucketInfo(0).getCount();
-                assertTrue(countFromStatsd > 0);
+                assertThat(countFromStatsd).isGreaterThan(0L);
             }
         }
         long countFromBS = 0;
@@ -256,15 +255,15 @@
                         for (Service svc : pkg.getServicesList()) {
                             if (svc.getName().equals(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME)) {
                                 countFromBS = svc.getLaunchCount();
-                                assertTrue(countFromBS > 0);
+                                assertThat(countFromBS).isGreaterThan(0L);
                             }
                         }
                     }
                 }
             }
         }
-        assertTrue(countFromStatsd > 0);
-        assertTrue(countFromBS > 0);
-        assertEquals(countFromBS, countFromStatsd);
+        assertThat(countFromStatsd).isGreaterThan(0L);
+        assertThat(countFromBS).isGreaterThan(0L);
+        assertThat(countFromBS).isEqualTo(countFromStatsd);
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java
index cfa0a37..9cb198c 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java
@@ -15,7 +15,7 @@
  */
 package android.cts.statsd.validation;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.cts.statsd.atom.ProcStateTestCase;
 import android.service.procstats.ProcessState;
@@ -113,8 +113,8 @@
             }
         }
         // Verify that duration is within 1% difference
-        assertTrue(Math.abs(durationInTopStatsd - durationInTopProcStats) / durationInTopProcStats
-                < 0.1);
+        assertThat(Math.abs(durationInTopStatsd - durationInTopProcStats) / durationInTopProcStats)
+                .isLessThan(0.01);
     }
 
     public void testProcessStateCachedEmptyDuration() throws Exception {
@@ -178,8 +178,8 @@
             }
         }
         // Verify that duration is within 1% difference
-        assertTrue(Math.abs(durationInStatsd - durationInProcStats) / durationInProcStats
-                < 0.1);
+        assertThat(Math.abs(durationInStatsd - durationInProcStats) / durationInProcStats)
+                .isLessThan(0.01);
     }
 
     public void testProcessStatePssValue() throws Exception {
@@ -240,8 +240,8 @@
                 }
             }
         }
-        assertTrue(valueInProcStats > 0);
-        assertTrue(valueInStatsd == valueInProcStats);
+        assertThat(valueInProcStats).isGreaterThan(0d);
+        assertThat(valueInStatsd).isWithin(1e-10).of(valueInProcStats);
     }
 
     public void testProcessStateByPulling() throws Exception {
@@ -342,11 +342,11 @@
         }
 
         LogUtil.CLog.d("avg pss from procstats is " + pssAvgProcstats);
-        assertTrue(durationStatsd > 0);
-        assertTrue(durationStatsd == durationProcstats);
-        assertTrue(pssAvgStatsd == pssAvgProcstats);
-        assertTrue(ussAvgStatsd == ussAvgProcstats);
-        assertTrue(rssAvgStatsd == rssAvgProcstats);
+        assertThat(durationStatsd).isGreaterThan(0L);
+        assertThat(durationStatsd).isEqualTo(durationProcstats);
+        assertThat(pssAvgStatsd).isEqualTo(pssAvgProcstats);
+        assertThat(ussAvgStatsd).isEqualTo(ussAvgProcstats);
+        assertThat(rssAvgStatsd).isEqualTo(rssAvgProcstats);
     }
 
     public void testProcStatsPkgProcStats() throws Exception {
@@ -390,8 +390,11 @@
         Thread.sleep(WAIT_TIME_SHORT);
 
         List<Atom> statsdData = getGaugeMetricDataList();
-        assertTrue(statsdData.size() > 0);
-        assertTrue(statsdData.get(0).getProcStatsPkgProc().getProcStatsSection().getAvailablePagesList().size() > 0);
+        assertThat(statsdData).isNotEmpty();
+        assertThat(
+                statsdData.get(0).getProcStatsPkgProc().getProcStatsSection()
+                        .getAvailablePagesList()
+        ).isNotEmpty();
 
         List<ProcessStatsPackageProto> processStatsPackageProtoList = getAllProcStatsProto();
 
@@ -421,8 +424,8 @@
                         }
                     }
                 }
-                assertTrue(pkg.getServiceStatsCount() == 0);
-                assertTrue(pkg.getAssociationStatsCount() == 0);
+                assertThat(pkg.getServiceStatsCount()).isEqualTo(0L);
+                assertThat(pkg.getAssociationStatsCount()).isEqualTo(0L);
             }
         }
 
@@ -453,14 +456,14 @@
             serviceStatsCount += pkg.getServiceStatsCount();
             associationStatsCount += pkg.getAssociationStatsCount();
         }
-        assertTrue(serviceStatsCount > 0);
-        assertTrue(associationStatsCount > 0);
+        assertThat(serviceStatsCount).isGreaterThan(0);
+        assertThat(associationStatsCount).isGreaterThan(0);
 
         LogUtil.CLog.d("avg pss from procstats is " + pssAvgProcstats);
-        assertTrue(durationStatsd > 0);
-        assertTrue(durationStatsd == durationProcstats);
-        assertTrue(pssAvgStatsd == pssAvgProcstats);
-        assertTrue(ussAvgStatsd == ussAvgProcstats);
-        assertTrue(rssAvgStatsd == rssAvgProcstats);
+        assertThat(durationStatsd).isGreaterThan(0L);
+        assertThat(durationStatsd).isEqualTo(durationProcstats);
+        assertThat(pssAvgStatsd).isEqualTo(pssAvgProcstats);
+        assertThat(ussAvgStatsd).isEqualTo(ussAvgProcstats);
+        assertThat(rssAvgStatsd).isEqualTo(rssAvgProcstats);
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
index ae40111..d4815b4 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
@@ -15,7 +15,8 @@
  */
 package android.cts.statsd.validation;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.cts.statsd.atom.DeviceAtomTestCase;
 import android.os.BatteryPluggedStateEnum;
@@ -48,6 +49,8 @@
 import com.android.os.StatsLog.StatsLogReport;
 import com.android.tradefed.log.LogUtil.CLog;
 
+import com.google.common.collect.Range;
+
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -118,10 +121,8 @@
         for (EventMetricData event : data) {
             String tag = event.getAtom().getWakelockStateChanged().getTag();
             WakeLockLevelEnum type = event.getAtom().getWakelockStateChanged().getType();
-            assertTrue("Expected tag: " + EXPECTED_TAG + ", but got tag: " + tag,
-                    tag.equals(EXPECTED_TAG));
-            assertTrue("Expected wakelock level: " + EXPECTED_LEVEL + ", but got level: " + type,
-                    type == EXPECTED_LEVEL);
+            assertThat(tag).isEqualTo(EXPECTED_TAG);
+            assertThat(type).isEqualTo(EXPECTED_LEVEL);
         }
 
         //=================== verify that batterystats is correct ===============//
@@ -129,12 +130,10 @@
         android.os.TimerProto wl =
                 getBatteryStatsPartialWakelock(batterystatsProto, uid, EXPECTED_TAG);
 
-        assertNotNull(wl);
-        assertTrue(wl.getDurationMs() > 0);
-        assertTrue(wl.getMaxDurationMs() >= 400);
-        assertTrue(wl.getMaxDurationMs() < 700);
-        assertTrue(wl.getTotalDurationMs() >= 400);
-        assertTrue(wl.getTotalDurationMs() < 700);
+        assertThat(wl).isNotNull();
+        assertThat(wl.getDurationMs()).isGreaterThan(0L);
+        assertThat(wl.getMaxDurationMs()).isIn(Range.closedOpen(400L, 700L));
+        assertThat(wl.getTotalDurationMs()).isIn(Range.closedOpen(400L, 700L));
 
         setAodState(aodState); // restores AOD to initial state.
     }
@@ -174,36 +173,34 @@
         // Get the batterystats wakelock time and make sure it's reasonable.
         android.os.TimerProto bsWakelock =
                 getBatteryStatsPartialWakelock(batterystatsProto, EXPECTED_UID, EXPECTED_TAG);
-        assertNotNull("Could not find any partial wakelocks with uid " + EXPECTED_UID +
-                " and tag " + EXPECTED_TAG + " in BatteryStats", bsWakelock);
+        assertWithMessage(
+                "No partial wakelocks with uid %s and tag %s in BatteryStats",
+                EXPECTED_UID, EXPECTED_TAG
+        ).that(bsWakelock).isNotNull();
         long bsDurationMs = bsWakelock.getTotalDurationMs();
-        assertTrue("Wakelock in batterystats with uid " + EXPECTED_UID + " and tag "
-                + EXPECTED_TAG + "was too short. Expected " + MIN_DURATION +
-                ", received " + bsDurationMs, bsDurationMs >= MIN_DURATION);
-        assertTrue("Wakelock in batterystats with uid " + EXPECTED_UID + " and tag "
-                + EXPECTED_TAG + "was too long. Expected " + MAX_DURATION +
-                ", received " + bsDurationMs, bsDurationMs <= MAX_DURATION);
+        assertWithMessage(
+                "Wakelock in batterystats with uid %s and tag %s was too short or too long",
+                EXPECTED_UID, EXPECTED_TAG
+        ).that(bsDurationMs).isIn(Range.closed((long) MIN_DURATION, (long) MAX_DURATION));
 
         // Get the statsd wakelock time and make sure it's reasonable.
-        assertTrue("Could not find any wakelocks with uid " + EXPECTED_UID + " in statsd",
-                statsdWakelockData.containsKey(EXPECTED_UID));
-        assertTrue("Did not find any wakelocks with tag " + EXPECTED_TAG + " in statsd",
-                statsdWakelockData.get(EXPECTED_UID).containsKey(EXPECTED_TAG_HASH));
+        assertWithMessage("No wakelocks with uid %s in statsd", EXPECTED_UID)
+                .that(statsdWakelockData).containsKey(EXPECTED_UID);
+        assertWithMessage("No wakelocks with tag %s in statsd", EXPECTED_TAG)
+                .that(statsdWakelockData.get(EXPECTED_UID)).containsKey(EXPECTED_TAG_HASH);
         long statsdDurationMs = statsdWakelockData.get(EXPECTED_UID)
                 .get(EXPECTED_TAG_HASH) / 1_000_000;
-        assertTrue("Wakelock in statsd with uid " + EXPECTED_UID + " and tag " + EXPECTED_TAG +
-                        "was too short. Expected " + MIN_DURATION + ", received " +
-                        statsdDurationMs,
-                statsdDurationMs >= MIN_DURATION);
-        assertTrue("Wakelock in statsd with uid " + EXPECTED_UID + " and tag " + EXPECTED_TAG +
-                        "was too long. Expected " + MAX_DURATION + ", received " + statsdDurationMs,
-                statsdDurationMs <= MAX_DURATION);
+        assertWithMessage(
+                "Wakelock in statsd with uid %s and tag %s was too short or too long", 
+                EXPECTED_UID, EXPECTED_TAG
+        ).that(statsdDurationMs).isIn(Range.closed((long) MIN_DURATION, (long) MAX_DURATION));
 
         // Compare batterystats with statsd.
         long difference = Math.abs(statsdDurationMs - bsDurationMs);
-        assertTrue("For uid=" + EXPECTED_UID + " tag=" + EXPECTED_TAG + " had " +
-                        "BatteryStats=" + bsDurationMs + "ms but statsd=" + statsdDurationMs + "ms",
-                difference <= Math.max(bsDurationMs / 10, 10L));
+        assertWithMessage(
+                "For uid=%s tag=%s had BatteryStats=%s ms but statsd=%s ms",
+                EXPECTED_UID, EXPECTED_TAG, bsDurationMs, statsdDurationMs
+        ).that(difference).isAtMost(Math.max(bsDurationMs / 10, 10L));
 
         setAodState(aodState); // restores AOD to initial state.
     }
@@ -304,7 +301,7 @@
         for (DurationMetricData data : report.getDurationMetrics().getDataList()) {
             // Gets tag and uid.
             List<DimensionsValue> dims = data.getDimensionLeafValuesInWhatList();
-            assertTrue("Expected 2 dimensions, received " + dims.size(), dims.size() == 2);
+            assertThat(dims).hasSize(2);
             boolean hasTag = false;
             long tag = 0;
             int uid = -1;
@@ -317,8 +314,8 @@
                     tag = dim.getValueStrHash();
                 }
             }
-            assertTrue("Did not receive a tag for the wakelock", hasTag);
-            assertTrue("Did not receive a uid for the wakelock", uid != -1);
+            assertWithMessage("Did not receive a tag for the wakelock").that(hasTag).isTrue();
+            assertWithMessage("Did not receive a uid for the wakelock").that(uid).isNotEqualTo(-1);
 
             // Gets duration.
             for (DurationBucketInfo bucketInfo : data.getBucketInfoList()) {
diff --git a/hostsidetests/testharness/Android.mk b/hostsidetests/testharness/Android.mk
index 8959f53..f7fa2b23 100644
--- a/hostsidetests/testharness/Android.mk
+++ b/hostsidetests/testharness/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsTestHarnessModeTestCases
 
diff --git a/hostsidetests/testharness/app/Android.mk b/hostsidetests/testharness/app/Android.mk
index 6396cc4..5e931c4 100644
--- a/hostsidetests/testharness/app/Android.mk
+++ b/hostsidetests/testharness/app/Android.mk
@@ -34,7 +34,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsTestHarnessModeDeviceApp
 
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index f31b081..2fcbb5b 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -295,7 +295,7 @@
 
     private static int getDensityForDevice(ITestDevice device) throws DeviceNotAvailableException {
         final String densityProp;
-        if (device.getSerialNumber().startsWith("emulator-")) {
+        if (isEmulator(device)) {
             densityProp = DENSITY_PROP_EMULATOR;
         } else {
             densityProp = DENSITY_PROP_DEVICE;
@@ -308,4 +308,9 @@
                 || hardwareTypeString.contains("android.hardware.type.television")
                 || hardwareTypeString.contains("android.hardware.type.automotive");
     }
+
+    private static boolean isEmulator(ITestDevice device) {
+        // Expecting something like "emulator-XXXX" or "EMULATORXXXX".
+        return device.getSerialNumber().toLowerCase().startsWith("emulator");
+    }
 }
diff --git a/hostsidetests/usb/Android.bp b/hostsidetests/usb/Android.bp
index 8c0bd95..b2b4f4d 100644
--- a/hostsidetests/usb/Android.bp
+++ b/hostsidetests/usb/Android.bp
@@ -26,6 +26,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/usb/SerialTestApp/Android.bp b/hostsidetests/usb/SerialTestApp/Android.bp
index ec06142..eeb7d6e 100644
--- a/hostsidetests/usb/SerialTestApp/Android.bp
+++ b/hostsidetests/usb/SerialTestApp/Android.bp
@@ -28,6 +28,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/webkit/Android.bp b/hostsidetests/webkit/Android.bp
index afbb007..2dfbbb3 100644
--- a/hostsidetests/webkit/Android.bp
+++ b/hostsidetests/webkit/Android.bp
@@ -26,6 +26,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/webkit/app/Android.bp b/hostsidetests/webkit/app/Android.bp
index b2ce1f2..b2ed224 100644
--- a/hostsidetests/webkit/app/Android.bp
+++ b/hostsidetests/webkit/app/Android.bp
@@ -35,6 +35,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/hostsidetests/wifibroadcasts/Android.mk b/hostsidetests/wifibroadcasts/Android.mk
index 584cc4c..ee00ea8 100644
--- a/hostsidetests/wifibroadcasts/Android.mk
+++ b/hostsidetests/wifibroadcasts/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsWifiBroadcastsHostTestCases
 
diff --git a/hostsidetests/wifibroadcasts/app/Android.mk b/hostsidetests/wifibroadcasts/app/Android.mk
index ae4bcd1..29a624c 100644
--- a/hostsidetests/wifibroadcasts/app/Android.mk
+++ b/hostsidetests/wifibroadcasts/app/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsWifiBroadcastsDeviceApp
 
diff --git a/hostsidetests/wifibroadcasts/src/android/wifibroadcasts/cts/WifiBroadcastsHostJUnit4Test.java b/hostsidetests/wifibroadcasts/src/android/wifibroadcasts/cts/WifiBroadcastsHostJUnit4Test.java
index e01d682..8dcc4d3 100644
--- a/hostsidetests/wifibroadcasts/src/android/wifibroadcasts/cts/WifiBroadcastsHostJUnit4Test.java
+++ b/hostsidetests/wifibroadcasts/src/android/wifibroadcasts/cts/WifiBroadcastsHostJUnit4Test.java
@@ -71,9 +71,14 @@
     private static final String PROHIBITED_STRING = "UNEXPECTED WIFI BROADCAST RECEIVED";
 
     /**
-     * The maximim number of times to attempt a ping
+     * The maximum total number of times to attempt a ping.
      */
-    private static final int MAXIMUM_PING_TRIES = 30;
+    private static final int MAXIMUM_PING_TRIES = 180;
+
+    /**
+     * The maximum number of times to attempt a ping before toggling wifi.
+     */
+    private static final int MAXIMUM_PING_TRIES_PER_CONNECTION = 60;
 
     /**
      * Name for wifi feature test
@@ -121,6 +126,10 @@
         CommandResult pingCommandResult = null;
         boolean pingSucceeded = false;
         for (int tries = 0; tries < MAXIMUM_PING_TRIES; tries++) {
+            if (tries > 0 && tries % MAXIMUM_PING_TRIES_PER_CONNECTION == 0) {
+                // if we have been trying for a while, toggle wifi off and then on.
+                device.executeShellCommand("svc wifi disable; sleep 1; svc wifi enable; sleep 3");
+            }
             // We don't require internet connectivity, just a configured address
             pingCommandResult = device.executeShellV2Command("ping -c 4 -W 2 -t 1 8.8.8.8");
             pingResult = String.join("/", pingCommandResult.getStdout(),
diff --git a/libs/install/testapp/src/com/android/cts/install/lib/testapp/ProcessUserData.java b/libs/install/testapp/src/com/android/cts/install/lib/testapp/ProcessUserData.java
index 842a674..359e03f 100644
--- a/libs/install/testapp/src/com/android/cts/install/lib/testapp/ProcessUserData.java
+++ b/libs/install/testapp/src/com/android/cts/install/lib/testapp/ProcessUserData.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.res.Resources;
+import android.os.Process;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -29,7 +30,7 @@
 
 /**
  * A broadcast receiver to check for and update user app data version
- * compatibility.
+ * and user handle compatibility.
  */
 public class ProcessUserData extends BroadcastReceiver {
 
@@ -58,7 +59,8 @@
     }
 
     /**
-     * Update the app's user data version to match the app version.
+     * Update the app's user data version to match the app version, and confirm
+     * the user data is for the correct user.
      *
      * @param context The application context.
      * @throws UserDataException in case of problems with app user data.
@@ -67,6 +69,8 @@
         Resources res = context.getResources();
         String packageName = context.getPackageName();
 
+        String userHandle = Process.myUserHandle().toString();
+
         int appVersionId = res.getIdentifier("app_version", "integer", packageName);
         int appVersion = res.getInteger(appVersionId);
 
@@ -80,18 +84,27 @@
         }
 
         // Read the version of the app's user data and ensure it is compatible
-        // with our version of the application.
-        File versionFile = new File(context.getFilesDir(), "version.txt");
+        // with our version of the application. Also ensure that the user data is
+        // for the correct user.
+        File versionFile = new File(context.getFilesDir(), "userdata.txt");
         try {
             Scanner s = new Scanner(versionFile);
             int userDataVersion = s.nextInt();
-            s.close();
+            s.nextLine();
 
             if (userDataVersion > appVersion) {
                 throw new UserDataException("User data is from version " + userDataVersion
                         + ", which is not compatible with this version " + appVersion
                         + " of the RollbackTestApp");
             }
+
+            String readUserHandle = s.nextLine();
+            s.close();
+
+            if (!readUserHandle.equals(userHandle)) {
+                throw new UserDataException("User handle expected to be: " + userHandle
+                        + ", but was actually " + readUserHandle);
+            }
         } catch (FileNotFoundException e) {
             // No problem. This is a fresh install of the app or the user data
             // has been wiped.
@@ -101,6 +114,7 @@
         try {
             PrintWriter pw = new PrintWriter(versionFile);
             pw.println(appVersion);
+            pw.println(userHandle);
             pw.close();
         } catch (IOException e) {
             throw new UserDataException("Unable to write user data.", e);
diff --git a/tests/acceleration/Android.bp b/tests/acceleration/Android.bp
index 5ab6a1c..2d4e9e4 100644
--- a/tests/acceleration/Android.bp
+++ b/tests/acceleration/Android.bp
@@ -35,7 +35,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/accessibility/Android.bp b/tests/accessibility/Android.bp
index fba6008..4ab6ed5 100644
--- a/tests/accessibility/Android.bp
+++ b/tests/accessibility/Android.bp
@@ -36,7 +36,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityGestureInfoTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityGestureEventTest.java
similarity index 72%
rename from tests/accessibility/src/android/view/accessibility/cts/AccessibilityGestureInfoTest.java
rename to tests/accessibility/src/android/view/accessibility/cts/AccessibilityGestureEventTest.java
index 0d851cf..abf9be8 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityGestureInfoTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityGestureEventTest.java
@@ -20,7 +20,7 @@
 import static org.junit.Assert.assertSame;
 
 import android.accessibility.cts.common.AccessibilityDumpOnFailureRule;
-import android.accessibilityservice.AccessibilityGestureInfo;
+import android.accessibilityservice.AccessibilityGestureEvent;
 import android.accessibilityservice.AccessibilityService;
 import android.os.Parcel;
 import android.platform.test.annotations.Presubmit;
@@ -34,11 +34,11 @@
 import org.junit.runner.RunWith;
 
 /**
- * Class for testing {@link android.accessibilityservice.AccessibilityGestureInfo}.
+ * Class for testing {@link android.accessibilityservice.AccessibilityGestureEvent}.
  */
 @Presubmit
 @RunWith(AndroidJUnit4.class)
-public class AccessibilityGestureInfoTest {
+public class AccessibilityGestureEventTest {
 
     @Rule
     public final AccessibilityDumpOnFailureRule mDumpOnFailureRule =
@@ -52,18 +52,18 @@
     public void testMarshaling() {
 
         // Fully populate the gesture info to marshal.
-        AccessibilityGestureInfo sentGestureInfo = new AccessibilityGestureInfo(
+        AccessibilityGestureEvent sentGestureEvent = new AccessibilityGestureEvent(
                 SENT_GESTURE, TARGET_DISPLAY);
 
         // Marshal and unmarshal the gesture info.
         Parcel parcel = Parcel.obtain();
-        sentGestureInfo.writeToParcel(parcel, 0);
+        sentGestureEvent.writeToParcel(parcel, 0);
         parcel.setDataPosition(0);
-        AccessibilityGestureInfo receivedGestureInfo =
-                AccessibilityGestureInfo.CREATOR.createFromParcel(parcel);
+        AccessibilityGestureEvent receivedGestureEvent =
+                AccessibilityGestureEvent.CREATOR.createFromParcel(parcel);
 
         // Make sure all fields properly marshaled.
-        assertEqualsGestureInfo(sentGestureInfo, receivedGestureInfo);
+        assertEqualsGestureEvent(sentGestureEvent, receivedGestureEvent);
 
         parcel.recycle();
     }
@@ -75,7 +75,7 @@
     @SmallTest
     @Test
     public void testGetterMethods() {
-        AccessibilityGestureInfo actualGesture = new AccessibilityGestureInfo(SENT_GESTURE,
+        AccessibilityGestureEvent actualGesture = new AccessibilityGestureEvent(SENT_GESTURE,
                 TARGET_DISPLAY);
 
         assertEquals("getGestureId is different from parameter of constructor", SENT_GESTURE,
@@ -90,20 +90,20 @@
     @SmallTest
     @Test
     public void testDescribeContents() {
-        AccessibilityGestureInfo gesture1 = new AccessibilityGestureInfo(SENT_GESTURE,TARGET_DISPLAY);
+        AccessibilityGestureEvent event1 = new AccessibilityGestureEvent(SENT_GESTURE,TARGET_DISPLAY);
         assertSame("accessibility gesture infos always return 0 for this method.", 0,
-                gesture1.describeContents());
-        AccessibilityGestureInfo gesture2 = new AccessibilityGestureInfo(
+                event1.describeContents());
+        AccessibilityGestureEvent event2 = new AccessibilityGestureEvent(
                 AccessibilityService.GESTURE_SWIPE_LEFT, TARGET_DISPLAY);
         assertSame("accessibility gesture infos always return 0 for this method.", 0,
-                gesture2.describeContents());
+                event2.describeContents());
     }
 
-    private void assertEqualsGestureInfo(AccessibilityGestureInfo sentGestureInfo,
-            AccessibilityGestureInfo receivedGestureInfo) {
-        assertEquals("getDisplayId has incorrectValue", sentGestureInfo.getDisplayId(),
-                receivedGestureInfo.getDisplayId());
-        assertEquals("getGestureId has incorrectValue", sentGestureInfo.getGestureId(),
-                receivedGestureInfo.getGestureId());
+    private void assertEqualsGestureEvent(AccessibilityGestureEvent sentGestureEvent,
+            AccessibilityGestureEvent receivedGestureEvent) {
+        assertEquals("getDisplayId has incorrectValue", sentGestureEvent.getDisplayId(),
+                receivedGestureEvent.getDisplayId());
+        assertEquals("getGestureId has incorrectValue", sentGestureEvent.getGestureId(),
+                receivedGestureEvent.getGestureId());
     }
 }
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java
index c7c9b0d..5a695de 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java
@@ -208,6 +208,7 @@
         info.setText(updatingString);
         info.setError(updatingString);
         info.setContentDescription(updatingString);
+        info.setStateDescription(updatingString);
 
         updatingString.delete(0, updatingString.length());
         updatingString.append(newText);
@@ -215,6 +216,7 @@
         assertTrue(TextUtils.equals(originalText, info.getText()));
         assertTrue(TextUtils.equals(originalText, info.getError()));
         assertTrue(TextUtils.equals(originalText, info.getContentDescription()));
+        assertTrue(TextUtils.equals(originalText, info.getStateDescription()));
     }
 
     @SmallTest
@@ -241,6 +243,7 @@
         info.setBoundsInScreen(new Rect(2,2,2,2));
         info.setClassName("foo.bar.baz.Class");
         info.setContentDescription("content description");
+        info.setStateDescription("state description");
         info.setTooltipText("tooltip");
         info.setPackageName("foo.bar.baz");
         info.setText("text");
@@ -374,6 +377,8 @@
                 receivedInfo.getClassName());
         assertEquals("contentDescription has incorrect value", expectedInfo.getContentDescription(),
                 receivedInfo.getContentDescription());
+        assertEquals("stateDescription has incorrect value", expectedInfo.getStateDescription(),
+                receivedInfo.getStateDescription());
         assertEquals("tooltip text has incorrect value", expectedInfo.getTooltipText(),
                 receivedInfo.getTooltipText());
         assertEquals("packageName has incorrect value", expectedInfo.getPackageName(),
@@ -556,6 +561,7 @@
         assertTrue("boundsInScreen not properly recycled", bounds.isEmpty());
         assertNull("className not properly recycled", info.getClassName());
         assertNull("contentDescription not properly recycled", info.getContentDescription());
+        assertNull("stateDescription not properly recycled", info.getStateDescription());
         assertNull("tooltiptext not properly recycled", info.getTooltipText());
         assertNull("packageName not properly recycled", info.getPackageName());
         assertNull("text not properly recycled", info.getText());
diff --git a/tests/accessibilityservice/Android.bp b/tests/accessibilityservice/Android.bp
index 8b2a0ec..d96b5459 100644
--- a/tests/accessibilityservice/Android.bp
+++ b/tests/accessibilityservice/Android.bp
@@ -33,7 +33,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
     data: [":CtsAccessibilityWidgetProvider"],
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEmbeddedDisplayTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEmbeddedDisplayTest.java
index f2eeb34..9166356 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEmbeddedDisplayTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEmbeddedDisplayTest.java
@@ -39,7 +39,6 @@
 import android.graphics.Rect;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
-import android.view.ViewGroup;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.accessibility.AccessibilityWindowInfo;
 
@@ -80,9 +79,6 @@
     private final AccessibilityDumpOnFailureRule mDumpOnFailureRule =
             new AccessibilityDumpOnFailureRule();
 
-    private final static int DEFAULT_ACTIVITYVIEW_HEIGHT = 500;
-    private final static int DEFAULT_ACTIVITYVIEW_WIDTH = 500;
-
     @Rule
     public final RuleChain mRuleChain = RuleChain
             .outerRule(mActivityRule)
@@ -171,13 +167,11 @@
     public void testA11yWindowNotifyWhenResizeActivityView() throws Exception {
         final AccessibilityWindowInfo oldActivityWindow =
                 findWindowByTitle(sUiAutomation, mActivityTitle);
-        final Rect oldWindowBound = new Rect();
-        oldActivityWindow.getBoundsInScreen(oldWindowBound);
-        assertEquals(DEFAULT_ACTIVITYVIEW_HEIGHT, oldWindowBound.height());
-        assertEquals(DEFAULT_ACTIVITYVIEW_WIDTH, oldWindowBound.width());
+        final Rect activityBound = new Rect();
+        oldActivityWindow.getBoundsInScreen(activityBound);
 
-        final int width = DEFAULT_ACTIVITYVIEW_WIDTH / 2;
-        final int height = DEFAULT_ACTIVITYVIEW_WIDTH / 2;
+        final int width = activityBound.width() / 2;
+        final int height = activityBound.height() / 2;
         sUiAutomation.executeAndWaitForEvent(() -> sInstrumentation.runOnMainSync(
                 () -> mActivityView.layout(0, 0, width, height)),
                 filterWindowsChangeTypesAndWindowTitle(sUiAutomation, WINDOWS_CHANGE_BOUNDS,
@@ -186,11 +180,10 @@
 
         final AccessibilityWindowInfo newActivityWindow =
                 findWindowByTitle(sUiAutomation, mActivityTitle);
-        final Rect newWindowBound = new Rect();
-        newActivityWindow.getBoundsInScreen(newWindowBound);
+        newActivityWindow.getBoundsInScreen(activityBound);
 
-        assertEquals(height, newWindowBound.height());
-        assertEquals(width, newWindowBound.width());
+        assertEquals(height, activityBound.height());
+        assertEquals(width, activityBound.width());
     }
 
     private void launchActivityInActivityView() throws Exception {
@@ -227,11 +220,6 @@
             super.onCreate(savedInstanceState);
             mActivityView = new ActivityView(this);
             setContentView(mActivityView);
-
-            ViewGroup.LayoutParams layoutParams = mActivityView.getLayoutParams();
-            layoutParams.width = DEFAULT_ACTIVITYVIEW_WIDTH;
-            layoutParams.height = DEFAULT_ACTIVITYVIEW_HEIGHT;
-            mActivityView.requestLayout();
         }
 
         ActivityView getActivityView() {
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
index b28b419..28e8f67 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
@@ -27,11 +27,10 @@
 
 import android.accessibility.cts.common.AccessibilityDumpOnFailureRule;
 import android.accessibility.cts.common.InstrumentedAccessibilityServiceTestRule;
-import android.accessibilityservice.AccessibilityGestureInfo;
+import android.accessibilityservice.AccessibilityGestureEvent;
 import android.accessibilityservice.AccessibilityService;
 import android.accessibilityservice.GestureDescription;
 import android.accessibilityservice.GestureDescription.StrokeDescription;
-import android.accessibilityservice.cts.utils.DisplayUtils;
 import android.app.Instrumentation;
 import android.content.Context;
 import android.content.pm.PackageManager;
@@ -253,10 +252,10 @@
             assertEquals(gestureId, mService.getGesture(0));
         }
 
-        AccessibilityGestureInfo expectedGestureInfo = new AccessibilityGestureInfo(gestureId,
+        AccessibilityGestureEvent expectedGestureEvent = new AccessibilityGestureEvent(gestureId,
                 displayId);
         assertEquals(1, mService.getGestureInfoSize());
-        assertEquals(expectedGestureInfo.toString(), mService.getGestureInfo(0).toString());
+        assertEquals(expectedGestureEvent.toString(), mService.getGestureInfo(0).toString());
     }
 
     /** Create a path from startPoint, moving by delta1, then delta2. (delta2 may be null.) */
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java
index 1bc62f62..049bae1 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java
@@ -17,7 +17,7 @@
 import static org.junit.Assert.fail;
 
 import android.accessibility.cts.common.InstrumentedAccessibilityService;
-import android.accessibilityservice.AccessibilityGestureInfo;
+import android.accessibilityservice.AccessibilityGestureEvent;
 import android.view.accessibility.AccessibilityEvent;
 
 import java.util.ArrayList;
@@ -30,7 +30,7 @@
     // Member variables
     protected final Object mLock = new Object();
     private ArrayList<Integer> mCollectedGestures = new ArrayList();
-    private ArrayList<AccessibilityGestureInfo> mCollectedGestureInfos = new ArrayList();
+    private ArrayList<AccessibilityGestureEvent> mCollectedGestureEvents = new ArrayList();
     protected ArrayList<Integer> mCollectedEvents = new ArrayList();
 
     @Override
@@ -42,11 +42,11 @@
     }
 
     @Override
-    public boolean onGesture(AccessibilityGestureInfo gestureInfo) {
-        super.onGesture(gestureInfo);
-        synchronized (mCollectedGestureInfos) {
-            mCollectedGestureInfos.add(gestureInfo);
-            mCollectedGestureInfos.notifyAll(); // Stop waiting for gesture.
+    public boolean onGesture(AccessibilityGestureEvent gestureEvent) {
+        super.onGesture(gestureEvent);
+        synchronized (mCollectedGestureEvents) {
+            mCollectedGestureEvents.add(gestureEvent);
+            mCollectedGestureEvents.notifyAll(); // Stop waiting for gesture.
         }
         return true;
     }
@@ -55,8 +55,8 @@
         synchronized (mCollectedGestures) {
             mCollectedGestures.clear();
         }
-        synchronized (mCollectedGestureInfos) {
-            mCollectedGestureInfos.clear();
+        synchronized (mCollectedGestureEvents) {
+            mCollectedGestureEvents.clear();
         }
     }
 
@@ -72,15 +72,15 @@
         }
     }
 
-    /** Waits for {@link #onGesture(AccessibilityGestureInfo)} to collect next gesture. */
+    /** Waits for {@link #onGesture(AccessibilityGestureEvent)} to collect next gesture. */
     public void waitUntilGestureInfo() {
-        synchronized (mCollectedGestureInfos) {
-            //Assume the size of mCollectedGestures is changed before mCollectedGestureInfos.
-            if (mCollectedGestureInfos.size() > 0) {
+        synchronized (mCollectedGestureEvents) {
+            //Assume the size of mCollectedGestures is changed before mCollectedGestureEvents.
+            if (mCollectedGestureEvents.size() > 0) {
                 return;
             }
             try {
-                mCollectedGestureInfos.wait(GESTURE_RECOGNIZE_TIMEOUT_MS);
+                mCollectedGestureEvents.wait(GESTURE_RECOGNIZE_TIMEOUT_MS);
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
@@ -88,14 +88,14 @@
     }
 
     public int getGestureInfoSize() {
-        synchronized (mCollectedGestureInfos) {
-            return mCollectedGestureInfos.size();
+        synchronized (mCollectedGestureEvents) {
+            return mCollectedGestureEvents.size();
         }
     }
 
-    public AccessibilityGestureInfo getGestureInfo(int index) {
-        synchronized (mCollectedGestureInfos) {
-            return mCollectedGestureInfos.get(index);
+    public AccessibilityGestureEvent getGestureInfo(int index) {
+        synchronized (mCollectedGestureEvents) {
+            return mCollectedGestureEvents.get(index);
         }
     }
 
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorationStubAccessibilityService.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorationStubAccessibilityService.java
index 9db2478..61a1cea 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorationStubAccessibilityService.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorationStubAccessibilityService.java
@@ -17,7 +17,6 @@
 import static android.view.accessibility.AccessibilityEvent.TYPE_GESTURE_DETECTION_START;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED;
-import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_FOCUSED;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_LONG_CLICKED;
 
 import android.view.accessibility.AccessibilityEvent;
@@ -34,7 +33,6 @@
             switch (event.getEventType()) {
                 case TYPE_GESTURE_DETECTION_START:
                 case TYPE_GESTURE_DETECTION_END:
-                case TYPE_VIEW_FOCUSED:
                 case TYPE_VIEW_ACCESSIBILITY_FOCUSED:
                 case TYPE_VIEW_CLICKED:
                 case TYPE_VIEW_LONG_CLICKED:
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
index c29c268..4beae0b 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
@@ -41,7 +41,6 @@
 import static android.view.accessibility.AccessibilityEvent.TYPE_TOUCH_INTERACTION_START;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED;
-import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_FOCUSED;
 import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_LONG_CLICKED;
 
 import static org.hamcrest.CoreMatchers.both;
@@ -158,13 +157,12 @@
     /** Test a slow swipe which should initiate touch exploration. */
     @Test
     @AppModeFull
-    public void testSlowSwipe() {
+    public void testSlowSwipe_initiatesTouchExploration() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(swipe(mTapLocation, add(mTapLocation, mSwipeDistance, 0), SWIPE_TIME_MILLIS));
         mHoverListener.assertPropagated(ACTION_HOVER_ENTER, ACTION_HOVER_MOVE, ACTION_HOVER_EXIT);
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED,
                 TYPE_TOUCH_INTERACTION_START,
                 TYPE_TOUCH_EXPLORATION_GESTURE_START,
                 TYPE_TOUCH_EXPLORATION_GESTURE_END,
@@ -174,13 +172,12 @@
     /** Test a fast swipe which should not initiate touch exploration. */
     @Test
     @AppModeFull
-    public void testFastSwipe() {
+    public void testFastSwipe_doesNotInitiateTouchExploration() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(swipe(mTapLocation, add(mTapLocation, mSwipeDistance, 0)));
         mHoverListener.assertNonePropagated();
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED,
                 TYPE_TOUCH_INTERACTION_START,
                 TYPE_GESTURE_DETECTION_START,
                 TYPE_GESTURE_DETECTION_END,
@@ -193,7 +190,7 @@
      */
     @Test
     @AppModeFull
-    public void testTwoFingerDrag() {
+    public void testTwoFingerDrag_dispatchesEventsBetweenFingers() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         // A two point moving that are in the same direction can perform a drag gesture by
         // TouchExplorer while one point moving can not perform a drag gesture. We use two swipes
@@ -238,13 +235,12 @@
     /** Test a basic single tap which should initiate touch exploration. */
     @Test
     @AppModeFull
-    public void testSingleTap() {
+    public void testSingleTap_initiatesTouchExploration() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(click(mTapLocation));
         mHoverListener.assertPropagated(ACTION_HOVER_ENTER, ACTION_HOVER_EXIT);
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED,
                 TYPE_TOUCH_INTERACTION_START,
                 TYPE_TOUCH_EXPLORATION_GESTURE_START,
                 TYPE_TOUCH_EXPLORATION_GESTURE_END,
@@ -257,7 +253,7 @@
      */
     @Test
     @AppModeFull
-    public void testDoubleTapAccessibilityFocus() {
+    public void testDoubleTapAccessibilityFocus_performsClick() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         syncAccessibilityFocusToInputFocus();
         dispatch(doubleTap(mTapLocation));
@@ -265,7 +261,6 @@
         // The click should not be delivered via touch events in this case.
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED,
                 TYPE_VIEW_ACCESSIBILITY_FOCUSED,
                 TYPE_TOUCH_INTERACTION_START,
                 TYPE_TOUCH_INTERACTION_END,
@@ -279,13 +274,13 @@
      */
     @Test
     @AppModeFull
-    public void testDoubleTapNoAccessibilityFocus() {
+    public void testDoubleTapNoAccessibilityFocus_doesNotPerformClick() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(doubleTap(mTapLocation));
         mHoverListener.assertNonePropagated();
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED, TYPE_TOUCH_INTERACTION_START, TYPE_TOUCH_INTERACTION_END);
+                 TYPE_TOUCH_INTERACTION_START, TYPE_TOUCH_INTERACTION_END);
         mService.clearEvents();
         mClickListener.assertNoneClicked();
     }
@@ -293,7 +288,7 @@
     /** Test the case where we want to long click on the item that has accessibility focus. */
     @Test
     @AppModeFull
-    public void testDoubleTapAndHoldAccessibilityFocus() {
+    public void testDoubleTapAndHoldAccessibilityFocus_performsLongClick() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         syncAccessibilityFocusToInputFocus();
         dispatch(doubleTapAndHold(mTapLocation));
@@ -301,7 +296,6 @@
         // The click should not be delivered via touch events in this case.
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED,
                 TYPE_VIEW_ACCESSIBILITY_FOCUSED,
                 TYPE_TOUCH_INTERACTION_START,
                 TYPE_VIEW_LONG_CLICKED,
@@ -315,13 +309,13 @@
      */
     @Test
     @AppModeFull
-    public void testDoubleTapAndHoldNoAccessibilityFocus() {
+    public void testDoubleTapAndHoldNoAccessibilityFocus_doesNotPerformLongClick() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
         dispatch(doubleTap(mTapLocation));
         mHoverListener.assertNonePropagated();
         mTouchListener.assertNonePropagated();
         mService.assertPropagated(
-                TYPE_VIEW_FOCUSED, TYPE_TOUCH_INTERACTION_START, TYPE_TOUCH_INTERACTION_END);
+                TYPE_TOUCH_INTERACTION_START, TYPE_TOUCH_INTERACTION_END);
         mService.clearEvents();
         mLongClickListener.assertNoneLongClicked();
     }
diff --git a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
index c3fc069..09c2130 100644
--- a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
@@ -1169,6 +1169,10 @@
                 appInfo.uid, ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE-1,
                 WAIT_TIME);
         uidBackgroundListener.register();
+        UidImportanceListener uidCachedListener = new UidImportanceListener(mContext,
+                appInfo.uid, ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE + 1,
+                WAIT_TIME);
+        uidCachedListener.register();
 
         WatchUidRunner uidWatcher = new WatchUidRunner(getInstrumentation(), appInfo.uid,
                 WAIT_TIME);
@@ -1237,14 +1241,14 @@
                     AccessibilityService.GLOBAL_ACTION_BACK);
 
             // Wait for process to become cached
-            uidBackgroundListener.waitForValue(
+            uidCachedListener.waitForValue(
                     IMPORTANCE_CACHED,
                     IMPORTANCE_CACHED);
             assertEquals(IMPORTANCE_CACHED,
                     am.getPackageImportance(CANT_SAVE_STATE_1_PACKAGE_NAME));
 
             uidWatcher.expect(WatchUidRunner.CMD_CACHED, null);
-            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
+            uidWatcher.waitFor(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
 
             // While in background, should go in to normal idle state.
             // Force app to go idle now
@@ -1256,6 +1260,7 @@
             uidWatcher.finish();
             uidForegroundListener.unregister();
             uidBackgroundListener.unregister();
+            uidCachedListener.unregister();
         }
     }
 
@@ -1400,7 +1405,7 @@
             getInstrumentation().getUiAutomation().performGlobalAction(
                     AccessibilityService.GLOBAL_ACTION_BACK);
             uid1Watcher.expect(WatchUidRunner.CMD_CACHED, null);
-            uid1Watcher.expect(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
+            uid1Watcher.waitFor(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
 
             // Make both apps idle for cleanliness.
             cmd = "am make-uid-idle " + CANT_SAVE_STATE_1_PACKAGE_NAME;
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 39addcd..5fcb1cf 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -21,6 +21,9 @@
 import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
 import static android.app.NotificationManager.IMPORTANCE_HIGH;
 import static android.app.NotificationManager.INTERRUPTION_FILTER_ALL;
+import static android.app.NotificationManager.INTERRUPTION_FILTER_PRIORITY;
+import static android.app.NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS;
+import static android.app.NotificationManager.Policy.PRIORITY_CATEGORY_MEDIA;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
@@ -70,6 +73,7 @@
 import android.graphics.Bitmap;
 import android.graphics.drawable.Icon;
 import android.media.AudioAttributes;
+import android.media.AudioManager;
 import android.media.session.MediaSession;
 import android.net.Uri;
 import android.os.Build;
@@ -125,6 +129,7 @@
     private static final int WAIT_TIME = 2000;
 
     private PackageManager mPackageManager;
+    private AudioManager mAudioManager;
     private NotificationManager mNotificationManager;
     private ActivityManager mActivityManager;
     private String mId;
@@ -148,6 +153,7 @@
                 NOTIFICATION_CHANNEL_ID, "name", NotificationManager.IMPORTANCE_DEFAULT));
         mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
         mPackageManager = mContext.getPackageManager();
+        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
         mRuleIds = new ArrayList<>();
 
         toggleNotificationPolicyAccess(mContext.getPackageName(),
@@ -571,13 +577,17 @@
                 && Objects.equals(a.getConfigurationActivity(), b.getConfigurationActivity());
     }
 
-    private AutomaticZenRule createRule(String name) {
+    private AutomaticZenRule createRule(String name, int filter) {
         return new AutomaticZenRule(name, null,
                 new ComponentName(mContext, AutomaticZenRuleActivity.class),
                 new Uri.Builder().scheme("scheme")
                         .appendPath("path")
                         .appendQueryParameter("fake_rule", "fake_value")
-                        .build(), null, NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
+                        .build(), null, filter, true);
+    }
+
+    private AutomaticZenRule createRule(String name) {
+        return createRule(name, NotificationManager.INTERRUPTION_FILTER_PRIORITY);
     }
 
     private void assertExpectedDndState(int expectedState) {
@@ -1582,10 +1592,10 @@
                                 Icon.createWithResource(getContext(), R.drawable.icon_blue),
                                 "a2", getPendingIntent()).build())
                         .setStyle(new Notification.BigPictureStyle()
-                        .setBigContentTitle("title")
-                        .bigPicture(Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565))
-                        .bigLargeIcon(Icon.createWithResource(getContext(), R.drawable.icon_blue))
-                        .setSummaryText("summary"))
+                                .setBigContentTitle("title")
+                                .bigPicture(Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565))
+                                .bigLargeIcon(Icon.createWithResource(getContext(), R.drawable.icon_blue))
+                                .setSummaryText("summary"))
                         .build();
         mNotificationManager.notify(id, notification);
 
@@ -1654,7 +1664,7 @@
     }
 
     public void testNewNotificationsAddedToAutogroup_ifOriginalNotificationsCanceled()
-        throws Exception {
+            throws Exception {
         String newGroup = "new!";
         sendNotification(910, R.drawable.black);
         sendNotification(920, R.drawable.blue);
@@ -1695,6 +1705,94 @@
         assertOnlySomeNotificationsAutogrouped(postedIds);
     }
 
+    public void testTotalSilenceOnlyMuteStreams() throws Exception {
+        if (mActivityManager.isLowRamDevice()) {
+            return;
+        }
+
+        final int originalFilter = mNotificationManager.getCurrentInterruptionFilter();
+        try {
+            toggleNotificationPolicyAccess(mContext.getPackageName(),
+                    InstrumentationRegistry.getInstrumentation(), true);
+
+            // ensure volume is not muted/0 to start test
+            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
+            mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, 1, 0);
+            mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 1, 0);
+            mAudioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
+
+            mNotificationManager.setNotificationPolicy(new NotificationManager.Policy(
+                    PRIORITY_CATEGORY_ALARMS | PRIORITY_CATEGORY_MEDIA, 0, 0));
+            AutomaticZenRule rule = createRule("test_total_silence",
+                    NotificationManager.INTERRUPTION_FILTER_NONE);
+            String id = mNotificationManager.addAutomaticZenRule(rule);
+            mRuleIds.add(id);
+            Condition condition =
+                    new Condition(rule.getConditionId(), "summary", Condition.STATE_TRUE);
+            mNotificationManager.setAutomaticZenRuleState(id, condition);
+            mNotificationManager.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY);
+
+            // delay for streams to get into correct mute states
+            Thread.sleep(50);
+            assertTrue("Music (media) stream should be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_MUSIC));
+            assertTrue("System stream should be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_SYSTEM));
+            assertTrue("Alarm stream should be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_ALARM));
+
+            // Test requires that the phone's default state has no channels that can bypass dnd
+            assertTrue("Ringer stream should be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_RING));
+        } finally {
+            mNotificationManager.setInterruptionFilter(originalFilter);
+        }
+    }
+
+    public void testAlarmsOnlyMuteStreams() throws Exception {
+        if (mActivityManager.isLowRamDevice()) {
+            return;
+        }
+
+        final int originalFilter = mNotificationManager.getCurrentInterruptionFilter();
+        try {
+            toggleNotificationPolicyAccess(mContext.getPackageName(),
+                    InstrumentationRegistry.getInstrumentation(), true);
+
+            // ensure volume is not muted/0 to start test
+            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
+            mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, 1, 0);
+            mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 1, 0);
+            mAudioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
+
+            mNotificationManager.setNotificationPolicy(new NotificationManager.Policy(
+                    PRIORITY_CATEGORY_ALARMS | PRIORITY_CATEGORY_MEDIA, 0, 0));
+            AutomaticZenRule rule = createRule("test_alarms",
+                    NotificationManager.INTERRUPTION_FILTER_ALARMS);
+            String id = mNotificationManager.addAutomaticZenRule(rule);
+            mRuleIds.add(id);
+            Condition condition =
+                    new Condition(rule.getConditionId(), "summary", Condition.STATE_TRUE);
+            mNotificationManager.setAutomaticZenRuleState(id, condition);
+            mNotificationManager.setInterruptionFilter(INTERRUPTION_FILTER_PRIORITY);
+
+            // delay for streams to get into correct mute states
+            Thread.sleep(50);
+            assertFalse("Music (media) stream should not be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_MUSIC));
+            assertTrue("System stream should be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_SYSTEM));
+            assertFalse("Alarm stream should not be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_ALARM));
+
+            // Test requires that the phone's default state has no channels that can bypass dnd
+            assertTrue("Ringer stream should be muted",
+                    mAudioManager.isStreamMute(AudioManager.STREAM_RING));
+        } finally {
+            mNotificationManager.setInterruptionFilter(originalFilter);
+        }
+    }
+
     public void testAddAutomaticZenRule_configActivity() throws Exception {
         if (mActivityManager.isLowRamDevice()) {
             return;
@@ -2442,7 +2540,7 @@
             // Tested in LegacyNotificationManager20Test
             if (checkNotificationExistence(notificationId, /*shouldExist=*/ true)) {
                 fail("Notification should have been cancelled for targetSdk below L.  targetSdk="
-                    + mContext.getApplicationInfo().targetSdkVersion);
+                        + mContext.getApplicationInfo().targetSdkVersion);
             }
         }
 
diff --git a/tests/apppredictionservice/Android.mk b/tests/apppredictionservice/Android.mk
index 718f718..1ff52e6 100644
--- a/tests/apppredictionservice/Android.mk
+++ b/tests/apppredictionservice/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppPredictionServiceTestCases
 
diff --git a/tests/autofillservice/Android.mk b/tests/autofillservice/Android.mk
index cab840a..5f7affb 100644
--- a/tests/autofillservice/Android.mk
+++ b/tests/autofillservice/Android.mk
@@ -36,7 +36,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAutoFillServiceTestCases
 
diff --git a/tests/autofillservice/OWNERS b/tests/autofillservice/OWNERS
index eac063b..18f17f3 100644
--- a/tests/autofillservice/OWNERS
+++ b/tests/autofillservice/OWNERS
@@ -1,4 +1,4 @@
 # Bug component: 351486
-felipeal@google.com
+adamhe@google.com
 svetoslavganov@google.com
-adamhe@google.com
\ No newline at end of file
+felipeal@google.com
diff --git a/tests/backup/Android.bp b/tests/backup/Android.bp
new file mode 100644
index 0000000..019c864
--- /dev/null
+++ b/tests/backup/Android.bp
@@ -0,0 +1,39 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test {
+    name: "CtsBackupTestCases",
+    defaults: ["cts_defaults"],
+    compile_multilib: "both",
+    libs: [
+        "android.test.runner.stubs",
+        "org.apache.http.legacy",
+        "android.test.base.stubs",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+        "ctstestserver",
+        "mockito-target-minus-junit4",
+        "testng",
+    ],
+    host_required: ["CtsBackupHostTestCases"],
+    srcs: ["src/**/*.java"],
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
diff --git a/tests/backup/Android.mk b/tests/backup/Android.mk
deleted file mode 100644
index 44fb751..0000000
--- a/tests/backup/Android.mk
+++ /dev/null
@@ -1,48 +0,0 @@
-# Copyright (C) 2016 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-# don't include this package in any target
-LOCAL_MODULE_TAGS := optional
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_JAVA_LIBRARIES := \
-    android.test.runner.stubs \
-    org.apache.http.legacy \
-    android.test.base.stubs \
-
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util-axt \
-    ctstestrunner-axt \
-    ctstestserver \
-    mockito-target-minus-junit4 \
-    testng
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_PACKAGE_NAME := CtsBackupTestCases
-
-LOCAL_SDK_VERSION := test_current
-
-include $(BUILD_CTS_PACKAGE)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/backup/OWNERS b/tests/backup/OWNERS
index c28c4d8..e0e5e22 100644
--- a/tests/backup/OWNERS
+++ b/tests/backup/OWNERS
@@ -2,6 +2,7 @@
 # Use this reviewer by default.
 br-framework-team+reviews@google.com
 
+alsutton@google.com
 anniemeng@google.com
 brufino@google.com
 nathch@google.com
diff --git a/tests/backup/app/Android.bp b/tests/backup/app/Android.bp
new file mode 100644
index 0000000..10e66ed
--- /dev/null
+++ b/tests/backup/app/Android.bp
@@ -0,0 +1,92 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test_helper_app {
+    name: "CtsFullBackupApp",
+    defaults: ["cts_support_defaults"],
+    srcs: [
+        "src/**/*.java",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+    ],
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    platform_apis: true,
+    manifest: "fullbackup/AndroidManifest.xml"
+}
+
+android_test_helper_app {
+    name: "CtsKeyValueBackupApp",
+    defaults: ["cts_support_defaults"],
+    // Tag this module as a cts test artifact
+    srcs: [
+        "src/**/*.java",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+    ],
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    platform_apis: true,
+    manifest: "keyvalue/AndroidManifest.xml"
+}
+
+android_test_helper_app {
+    name: "CtsPermissionBackupApp",
+    defaults: ["cts_support_defaults"],
+    // Tag this module as a cts test artifact
+    srcs: [
+        "src/**/*.java",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+    ],
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    platform_apis: true,
+    manifest: "permission/AndroidManifest.xml"
+}
+
+android_test_helper_app {
+    name: "CtsPermissionBackupApp22",
+    defaults: ["cts_support_defaults"],
+    // Tag this module as a cts test artifact
+    srcs: [
+        "src/**/*.java",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+    ],
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    platform_apis: true,
+    manifest: "permission22/AndroidManifest.xml"
+}
diff --git a/tests/backup/app/AndroidManifest.xml b/tests/backup/app/AndroidManifest.xml
new file mode 100644
index 0000000..d2a8a75
--- /dev/null
+++ b/tests/backup/app/AndroidManifest.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.backup.app">
+
+</manifest>
+
diff --git a/tests/backup/app/fullbackup/Android.mk b/tests/backup/app/fullbackup/Android.mk
deleted file mode 100644
index b53e38a..0000000
--- a/tests/backup/app/fullbackup/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (C) 2017 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsFullBackupApp
-LOCAL_SDK_VERSION := current
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util-axt \
-    ctstestrunner-axt
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/backup/app/keyvalue/Android.mk b/tests/backup/app/keyvalue/Android.mk
deleted file mode 100644
index dc5f2e8..0000000
--- a/tests/backup/app/keyvalue/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (C) 2017 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsKeyValueBackupApp
-LOCAL_SDK_VERSION := current
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util-axt \
-    ctstestrunner-axt
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/backup/app/permission/Android.mk b/tests/backup/app/permission/Android.mk
deleted file mode 100644
index f51a44d..0000000
--- a/tests/backup/app/permission/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (C) 2018 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp
-LOCAL_SDK_VERSION := current
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util-axt \
-    ctstestrunner-axt
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/camera/Android.mk b/tests/camera/Android.mk
index 3b4ecb7..083359a 100644
--- a/tests/camera/Android.mk
+++ b/tests/camera/Android.mk
@@ -28,7 +28,7 @@
 
 LOCAL_MODULE := CtsCameraUtils
 
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := test_current
 -include cts/error_prone_rules_tests.mk
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
@@ -50,7 +50,7 @@
 	androidx.test.rules
 
 LOCAL_SRC_FILES := \
-	src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java \
+	src/android/hardware/camera2/cts/testcases/Camera2AndroidBasicTestCase.java \
 	src/android/hardware/camera2/cts/PerformanceTest.java \
 	src/android/hardware/cts/CameraTestCase.java \
 	src/android/hardware/cts/LegacyCameraPerformanceTest.java
@@ -90,7 +90,7 @@
 	$(call all-renderscript-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsCameraTestCases
 
diff --git a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
index 92b171a..776879d 100644
--- a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
@@ -21,10 +21,13 @@
 import static android.hardware.camera2.cts.helpers.AssertHelpers.*;
 import static android.hardware.camera2.cts.CameraTestUtils.*;
 import static com.android.ex.camera2.blocking.BlockingStateCallback.*;
+import static junit.framework.Assert.*;
 
 import android.content.Context;
 import android.graphics.ImageFormat;
 import android.graphics.RectF;
+
+import android.hardware.camera2.cts.Camera2ParameterizedTestCase;
 import android.hardware.camera2.CameraAccessException;
 import android.hardware.camera2.CameraCaptureSession;
 import android.hardware.camera2.CameraCharacteristics;
@@ -50,11 +53,12 @@
 import android.os.HandlerThread;
 import android.renderscript.Allocation;
 import android.renderscript.Script.LaunchOptions;
-import android.test.AndroidTestCase;
 import android.util.Log;
 import android.util.Rational;
 import android.view.Surface;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.ex.camera2.blocking.BlockingCameraManager.BlockingOpenException;
 import com.android.ex.camera2.blocking.BlockingStateCallback;
 import com.android.ex.camera2.blocking.BlockingSessionCallback;
@@ -63,6 +67,10 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.Test;
+
 /**
  * Suite of tests for camera2 -> RenderScript APIs.
  *
@@ -71,17 +79,17 @@
  *
  * <p>YUV_420_888: flexible YUV420, it is a mandatory format for camera.</p>
  */
-public class AllocationTest extends AndroidTestCase {
+
+@RunWith(Parameterized.class)
+public class AllocationTest extends Camera2ParameterizedTestCase {
     private static final String TAG = "AllocationTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
 
-    private CameraManager mCameraManager;
     private CameraDevice mCamera;
     private CameraCaptureSession mSession;
     private BlockingStateCallback mCameraListener;
     private BlockingSessionCallback mSessionListener;
 
-    private String[] mCameraIds;
 
     private Handler mHandler;
     private HandlerThread mHandlerThread;
@@ -91,16 +99,8 @@
     private ResultIterable mResultIterable;
 
     @Override
-    public synchronized void setContext(Context context) {
-        super.setContext(context);
-        mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
-        assertNotNull("Can't connect to camera manager!", mCameraManager);
-    }
-
-    @Override
-    protected void setUp() throws Exception {
+    public void setUp() throws Exception {
         super.setUp();
-        mCameraIds = mCameraManager.getCameraIdList();
         mHandlerThread = new HandlerThread("AllocationTest");
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
@@ -110,11 +110,11 @@
         mSizeIterable = new SizeIterable();
         mResultIterable = new ResultIterable();
 
-        RenderScriptSingleton.setContext(getContext());
+        RenderScriptSingleton.setContext(mContext);
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         MaybeNull.close(mCamera);
         RenderScriptSingleton.clearContext();
         mHandlerThread.quitSafely();
@@ -475,6 +475,7 @@
         if (VERBOSE) Log.v(TAG, "validating Buffer , size = " + actualSize);
     }
 
+    @Test
     public void testAllocationFromCameraFlexibleYuv() throws Exception {
 
         /** number of frame (for streaming requests) to be verified. */
@@ -516,7 +517,7 @@
                             if (VERBOSE) Log.v(TAG, "Cleanup Renderscript cache");
                             scriptGraph.close();
                             RenderScriptSingleton.clearContext();
-                            RenderScriptSingleton.setContext(getContext());
+                            RenderScriptSingleton.setContext(mContext);
                         }
                     }
                 });
@@ -533,6 +534,7 @@
      *
      * @throws Exception
      */
+    @Test
     public void testBlackWhite() throws CameraAccessException {
 
         /** low iso + low exposure (first shot) */
@@ -610,6 +612,7 @@
     /**
      * Test that the android.sensitivity.parameter is applied.
      */
+    @Test
     public void testParamSensitivity() throws CameraAccessException {
         final float THRESHOLD_MAX_MIN_DIFF = 0.3f;
         final float THRESHOLD_MAX_MIN_RATIO = 2.0f;
@@ -761,33 +764,33 @@
         public void forEachCamera(boolean fullHwLevel, CameraBlock runnable)
                 throws CameraAccessException {
             assertNotNull("No camera manager", mCameraManager);
-            assertNotNull("No camera IDs", mCameraIds);
+            assertNotNull("No camera IDs", mCameraIdsUnderTest);
 
-            for (int i = 0; i < mCameraIds.length; i++) {
+            for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
                 // Don't execute the runnable against non-FULL cameras if FULL is required
                 CameraCharacteristics properties =
-                        mCameraManager.getCameraCharacteristics(mCameraIds[i]);
+                        mCameraManager.getCameraCharacteristics(mCameraIdsUnderTest[i]);
                 StaticMetadata staticInfo = new StaticMetadata(properties);
                 if (fullHwLevel && !staticInfo.isHardwareLevelAtLeastFull()) {
                     Log.i(TAG, String.format(
                             "Skipping this test for camera %s, needs FULL hw level",
-                            mCameraIds[i]));
+                            mCameraIdsUnderTest[i]));
                     continue;
                 }
                 if (!staticInfo.isColorOutputSupported()) {
                     Log.i(TAG, String.format(
                         "Skipping this test for camera %s, does not support regular outputs",
-                        mCameraIds[i]));
+                        mCameraIdsUnderTest[i]));
                     continue;
                 }
                 // Open camera and execute test
-                Log.i(TAG, "Testing Camera " + mCameraIds[i]);
+                Log.i(TAG, "Testing Camera " + mCameraIdsUnderTest[i]);
                 try {
-                    openDevice(mCameraIds[i]);
+                    openDevice(mCameraIdsUnderTest[i]);
 
                     runnable.run(mCamera);
                 } finally {
-                    closeDevice(mCameraIds[i]);
+                    closeDevice(mCameraIdsUnderTest[i]);
                 }
             }
         }
diff --git a/tests/camera/src/android/hardware/camera2/cts/BurstCaptureRawTest.java b/tests/camera/src/android/hardware/camera2/cts/BurstCaptureRawTest.java
index 7b23abf..afff41b 100644
--- a/tests/camera/src/android/hardware/camera2/cts/BurstCaptureRawTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/BurstCaptureRawTest.java
@@ -37,11 +37,14 @@
 
 import java.util.ArrayList;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 import org.junit.Test;
 
 /**
  * Basic tests for burst capture in RAW formats.
  */
+@RunWith(Parameterized.class)
 public class BurstCaptureRawTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "BurstCaptureRawTest";
     private static final int RAW_FORMATS[] = {
@@ -71,7 +74,7 @@
     @Test
     public void testRawSensorSize() throws Exception {
         Log.i(TAG, "Begin testRawSensorSize");
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 ArrayList<Integer> supportedRawList = new ArrayList<Integer>(RAW_FORMATS.length);
                 if (!checkCapability(id, supportedRawList, RAW_FORMATS)) {
@@ -675,7 +678,7 @@
     private void performTestRoutine(TestRoutine routine, int[] testedFormats) throws Exception
     {
         final int PREPARE_TIMEOUT_MS = 10000;
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 ArrayList<Integer> supportedRawList = new ArrayList<Integer>(RAW_FORMATS.length);
                 if (!checkCapability(id, supportedRawList, testedFormats)) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/BurstCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/BurstCaptureTest.java
index 03dbdeb5..b86c511 100644
--- a/tests/camera/src/android/hardware/camera2/cts/BurstCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/BurstCaptureTest.java
@@ -34,8 +34,11 @@
 import java.util.List;
 import java.util.ArrayList;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 import org.junit.Test;
 
+@RunWith(Parameterized.class)
 public class BurstCaptureTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "BurstCaptureTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -65,9 +68,9 @@
     }
 
     private void testBurst(int fmt, int burstSize, boolean checkFrameRate) throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                String id = mCameraIds[i];
+                String id = mCameraIdsUnderTest[i];
 
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
                 if (!staticInfo.isColorOutputSupported()) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 23f406f..73e3828 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -67,6 +67,9 @@
 import java.util.Set;
 import android.util.Size;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
 import org.mockito.ArgumentMatcher;
 
 import java.util.concurrent.Executor;
@@ -76,6 +79,8 @@
 /**
  * <p>Basic test for CameraDevice APIs.</p>
  */
+
+@RunWith(Parameterized.class)
 public class CameraDeviceTest extends Camera2AndroidTestCase {
     private static final String TAG = "CameraDeviceTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -114,16 +119,15 @@
     }
 
     @Override
-    public void setContext(Context context) {
-        super.setContext(context);
-
+    public void setUp() throws Exception {
+        super.setUp();
         /**
          * Workaround for mockito and JB-MR2 incompatibility
          *
          * Avoid java.lang.IllegalArgumentException: dexcache == null
          * https://code.google.com/p/dexmaker/issues/detail?id=2
          */
-        System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
+        System.setProperty("dexmaker.dexcache", mContext.getCacheDir().toString());
 
         /**
          * Create error listener in context scope, to catch asynchronous device error.
@@ -131,11 +135,6 @@
          * implementation (spy doesn't stub the functions unless we ask it to do so).
          */
         mCameraMockListener = spy(new BlockingStateCallback());
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
         /**
          * Due to the asynchronous nature of camera device error callback, we
          * have to make sure device doesn't run into error state before. If so,
@@ -154,7 +153,7 @@
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         super.tearDown();
     }
 
@@ -176,9 +175,10 @@
      * settings.</li>
      * </ul>
      */
+    @Test
     public void testCameraDevicePreviewTemplate() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            captureTemplateTestByCamera(mCameraIds[i], CameraDevice.TEMPLATE_PREVIEW);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            captureTemplateTestByCamera(mCameraIdsUnderTest[i], CameraDevice.TEMPLATE_PREVIEW);
         }
 
         // TODO: test the frame rate sustainability in preview use case test.
@@ -202,9 +202,10 @@
      * frame rate for the given settings.</li>
      * </ul>
      */
+    @Test
     public void testCameraDeviceStillTemplate() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            captureTemplateTestByCamera(mCameraIds[i], CameraDevice.TEMPLATE_STILL_CAPTURE);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            captureTemplateTestByCamera(mCameraIdsUnderTest[i], CameraDevice.TEMPLATE_STILL_CAPTURE);
         }
     }
 
@@ -222,9 +223,10 @@
      * <li>Frame rate should be stable, for example, wide fps range like [7, 30]
      * is a bad setting.</li>
      */
+    @Test
     public void testCameraDeviceRecordingTemplate() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            captureTemplateTestByCamera(mCameraIds[i], CameraDevice.TEMPLATE_RECORD);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            captureTemplateTestByCamera(mCameraIdsUnderTest[i], CameraDevice.TEMPLATE_RECORD);
         }
 
         // TODO: test the frame rate sustainability in recording use case test.
@@ -238,9 +240,10 @@
      * as recording, with an additional requirement: the settings should maximize image quality
      * without compromising stable frame rate.</p>
      */
+    @Test
     public void testCameraDeviceVideoSnapShotTemplate() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            captureTemplateTestByCamera(mCameraIds[i], CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            captureTemplateTestByCamera(mCameraIdsUnderTest[i], CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
         }
 
         // TODO: test the frame rate sustainability in video snapshot use case test.
@@ -253,9 +256,10 @@
      * metadata keys, and their values must be set correctly. It has the similar requirement
      * as preview, with an additional requirement: </p>
      */
+    @Test
     public void testCameraDeviceZSLTemplate() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            captureTemplateTestByCamera(mCameraIds[i], CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            captureTemplateTestByCamera(mCameraIdsUnderTest[i], CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG);
         }
     }
 
@@ -276,16 +280,18 @@
      * set to reasonable defaults.</li>
      * </ul>
      */
+    @Test
     public void testCameraDeviceManualTemplate() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            captureTemplateTestByCamera(mCameraIds[i], CameraDevice.TEMPLATE_MANUAL);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            captureTemplateTestByCamera(mCameraIdsUnderTest[i], CameraDevice.TEMPLATE_MANUAL);
         }
     }
 
+    @Test
     public void testCameraDeviceCreateCaptureBuilder() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 /**
                  * Test: that each template type is supported, and that its required fields are
                  * present.
@@ -331,16 +337,17 @@
                 try {
                     closeSession();
                 } finally {
-                    closeDevice(mCameraIds[i], mCameraMockListener);
+                    closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 }
             }
         }
     }
 
+    @Test
     public void testCameraDeviceSetErrorListener() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 /**
                  * Test: that the error listener can be set without problems.
                  * Also, wait some time to check if device doesn't run into error.
@@ -355,27 +362,31 @@
                 try {
                     closeSession();
                 } finally {
-                    closeDevice(mCameraIds[i], mCameraMockListener);
+                    closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 }
             }
         }
     }
 
+    @Test
     public void testCameraDeviceCapture() throws Exception {
         runCaptureTest(/*burst*/false, /*repeating*/false, /*abort*/false, /*useExecutor*/false);
         runCaptureTest(/*burst*/false, /*repeating*/false, /*abort*/false, /*useExecutor*/true);
     }
 
+    @Test
     public void testCameraDeviceCaptureBurst() throws Exception {
         runCaptureTest(/*burst*/true, /*repeating*/false, /*abort*/false, /*useExecutor*/false);
         runCaptureTest(/*burst*/true, /*repeating*/false, /*abort*/false, /*useExecutor*/true);
     }
 
+    @Test
     public void testCameraDeviceRepeatingRequest() throws Exception {
         runCaptureTest(/*burst*/false, /*repeating*/true, /*abort*/false, /*useExecutor*/false);
         runCaptureTest(/*burst*/false, /*repeating*/true, /*abort*/false, /*useExecutor*/true);
     }
 
+    @Test
     public void testCameraDeviceRepeatingBurst() throws Exception {
         runCaptureTest(/*burst*/true, /*repeating*/true, /*abort*/false, /*useExecutor*/ false);
         runCaptureTest(/*burst*/true, /*repeating*/true, /*abort*/false, /*useExecutor*/ true);
@@ -389,6 +400,7 @@
      * discarding in-progress work. Once the abort is complete, the idle callback will be called.
      * </p>
      */
+    @Test
     public void testCameraDeviceAbort() throws Exception {
         runCaptureTest(/*burst*/false, /*repeating*/true, /*abort*/true, /*useExecutor*/false);
         runCaptureTest(/*burst*/false, /*repeating*/true, /*abort*/true, /*useExecutor*/true);
@@ -414,10 +426,11 @@
     /**
      * Test invalid capture (e.g. null or empty capture request).
      */
+    @Test
     public void testInvalidCapture() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
                 prepareCapture();
@@ -427,7 +440,7 @@
                 closeSession();
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -442,6 +455,7 @@
      *  onCaptureCompleted -> createCaptureRequest, getDevice, abortCaptures,
      *     capture, setRepeatingRequest, stopRepeating, session+device.close
      */
+    @Test
     public void testChainedOperation() throws Throwable {
 
         final ArrayList<Surface> outputs = new ArrayList<>();
@@ -585,13 +599,13 @@
 
         // Actual test code
 
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
                 Throwable result;
 
-                if (!(new StaticMetadata(mCameraManager.getCameraCharacteristics(mCameraIds[i]))).
+                if (!(new StaticMetadata(mCameraManager.getCameraCharacteristics(mCameraIdsUnderTest[i]))).
                         isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
@@ -602,7 +616,7 @@
 
                 // Start chained cascade
                 ChainedCameraListener cameraListener = new ChainedCameraListener();
-                mCameraManager.openCamera(mCameraIds[i], cameraListener, mHandler);
+                mCameraManager.openCamera(mCameraIdsUnderTest[i], cameraListener, mHandler);
 
                 // Check if open succeeded
                 result = results.poll(CAMERA_OPEN_TIMEOUT_MS, TimeUnit.MILLISECONDS);
@@ -648,21 +662,22 @@
      * Verify basic semantics and error conditions of the prepare call.
      *
      */
+    @Test
     public void testPrepare() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
                 prepareTestByCamera();
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -671,26 +686,27 @@
      * Verify prepare call behaves properly when sharing surfaces.
      *
      */
+    @Test
     public void testPrepareForSharedSurfaces() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIds[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
                 if (staticInfo.isHardwareLevelLegacy()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] + " is legacy, skipping");
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] + " is legacy, skipping");
                     continue;
                 }
                 if (!staticInfo.isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
                 prepareTestForSharedSurfacesByCamera();
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -698,21 +714,22 @@
     /**
      * Verify creating sessions back to back.
      */
+    @Test
     public void testCreateSessions() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
-                testCreateSessionsByCamera(mCameraIds[i]);
+                testCreateSessionsByCamera(mCameraIdsUnderTest[i]);
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -720,21 +737,22 @@
     /**
      * Verify creating a custom session
      */
+    @Test
     public void testCreateCustomSession() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
-                testCreateCustomSessionByCamera(mCameraIds[i]);
+                testCreateCustomSessionByCamera(mCameraIdsUnderTest[i]);
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -808,6 +826,7 @@
     /**
      * Test session configuration.
      */
+    @Test
     public void testSessionConfiguration() throws Exception {
         ArrayList<OutputConfiguration> outConfigs = new ArrayList<OutputConfiguration> ();
         outConfigs.add(new OutputConfiguration(new Size(1, 1), SurfaceTexture.class));
@@ -856,14 +875,14 @@
         assertEquals("Session configuration input doesn't match",
                 highspeedSessionConfig.getInputConfiguration(), null);
 
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
                 CaptureRequest.Builder builder =
@@ -881,7 +900,7 @@
                         highspeedSessionConfig.getSessionParameters());
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -889,21 +908,22 @@
     /**
      * Check for any state leakage in case of internal re-configure
      */
+    @Test
     public void testSessionParametersStateLeak() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
-                testSessionParametersStateLeakByCamera(mCameraIds[i]);
+                testSessionParametersStateLeakByCamera(mCameraIdsUnderTest[i]);
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -1059,22 +1079,23 @@
     /**
      * Verify creating a session with additional parameters.
      */
+    @Test
     public void testCreateSessionWithParameters() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
-                testCreateSessionWithParametersByCamera(mCameraIds[i], /*reprocessable*/false);
-                testCreateSessionWithParametersByCamera(mCameraIds[i], /*reprocessable*/true);
+                testCreateSessionWithParametersByCamera(mCameraIdsUnderTest[i], /*reprocessable*/false);
+                testCreateSessionWithParametersByCamera(mCameraIdsUnderTest[i], /*reprocessable*/true);
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -1596,9 +1617,9 @@
      */
     private void runCaptureTest(boolean burst, boolean repeating, boolean abort,
             boolean useExecutor) throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
                 prepareCapture();
@@ -1617,13 +1638,13 @@
                             continue;
                         }
 
-                        captureSingleShot(mCameraIds[i], sTemplates[j], repeating, abort,
+                        captureSingleShot(mCameraIdsUnderTest[i], sTemplates[j], repeating, abort,
                                 useExecutor);
                     }
                 }
                 else {
                     // Test: burst of one shot
-                    captureBurstShot(mCameraIds[i], sTemplates, 1, repeating, abort, useExecutor);
+                    captureBurstShot(mCameraIdsUnderTest[i], sTemplates, 1, repeating, abort, useExecutor);
 
                     int template = mStaticInfo.isColorOutputSupported() ?
                         CameraDevice.TEMPLATE_STILL_CAPTURE :
@@ -1637,12 +1658,12 @@
                     };
 
                     // Test: burst of 5 shots of the same template type
-                    captureBurstShot(mCameraIds[i], templates, templates.length, repeating, abort,
+                    captureBurstShot(mCameraIdsUnderTest[i], templates, templates.length, repeating, abort,
                             useExecutor);
 
                     if (mStaticInfo.isColorOutputSupported()) {
                         // Test: burst of 6 shots of different template types
-                        captureBurstShot(mCameraIds[i], sTemplates, sTemplates.length, repeating,
+                        captureBurstShot(mCameraIdsUnderTest[i], sTemplates, sTemplates.length, repeating,
                                 abort, useExecutor);
                     }
                 }
@@ -1658,7 +1679,7 @@
                 } catch (Exception e) {
                     mCollector.addError(e);
                 }finally {
-                    closeDevice(mCameraIds[i], mCameraMockListener);
+                    closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 }
             }
         }
@@ -2702,19 +2723,21 @@
     /**
      * Verify audio restrictions are set properly for single CameraDevice usage
      */
+    @Test
     public void testAudioRestrictionSingleDevice() throws Exception {
         int[] testModes = {
             CameraDevice.AUDIO_RESTRICTION_VIBRATION_SOUND,
             CameraDevice.AUDIO_RESTRICTION_NONE,
             CameraDevice.AUDIO_RESTRICTION_VIBRATION,
         };
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                openDevice(mCameraIds[i], mCameraMockListener);
+                openDevice(mCameraIdsUnderTest[i], mCameraMockListener);
                 waitForDeviceState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
                 for (int mode : testModes) {
-                    int retMode = mCamera.setCameraAudioRestriction(mode);
+                    mCamera.setCameraAudioRestriction(mode);
+                    int retMode = mCamera.getCameraAudioRestriction();
                     assertTrue("Audio restriction mode mismatch: input: " + mode +
                             ", output:" + retMode, mode == retMode);
                 }
@@ -2728,7 +2751,7 @@
                 }
             }
             finally {
-                closeDevice(mCameraIds[i], mCameraMockListener);
+                closeDevice(mCameraIdsUnderTest[i], mCameraMockListener);
             }
         }
     }
@@ -2743,7 +2766,8 @@
             cam0Cb.waitForState(STATE_OPENED, CAMERA_OPEN_TIMEOUT_MS);
 
             int mode0 = CameraDevice.AUDIO_RESTRICTION_VIBRATION_SOUND;
-            int retMode = cam0.setCameraAudioRestriction(mode0);
+            cam0.setCameraAudioRestriction(mode0);
+            int retMode = cam0.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: input: " + mode0 + ", output:" + retMode,
                     retMode == mode0);
 
@@ -2771,7 +2795,8 @@
                 }
                 // Test the behavior for single remaining client
                 int mode1 = CameraDevice.AUDIO_RESTRICTION_VIBRATION;
-                retMode = cam1.setCameraAudioRestriction(mode1);
+                cam1.setCameraAudioRestriction(mode1);
+                retMode = cam1.getCameraAudioRestriction();
                 assertTrue("Audio restriction mode mismatch: input: " + mode1 +
                         ", output:" + retMode, retMode == mode1);
                 return;
@@ -2780,40 +2805,46 @@
             // The output mode should be union of all CameraDevices
             int mode1 = CameraDevice.AUDIO_RESTRICTION_VIBRATION;
             int expectMode = mode0 | mode1;
-            retMode = cam1.setCameraAudioRestriction(mode1);
+            cam1.setCameraAudioRestriction(mode1);
+            retMode = cam1.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
 
             // test turning off mute settings also
             mode0 = CameraDevice.AUDIO_RESTRICTION_NONE;
             expectMode = mode0 | mode1;
-            retMode = cam0.setCameraAudioRestriction(mode0);
+            cam0.setCameraAudioRestriction(mode0);
+            retMode = cam0.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
 
             // mode should be NONE when both device set to NONE
             mode1 = CameraDevice.AUDIO_RESTRICTION_NONE;
             expectMode = mode0 | mode1;
-            retMode = cam1.setCameraAudioRestriction(mode1);
+            cam1.setCameraAudioRestriction(mode1);
+            retMode = cam1.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
 
             // test removal of VIBRATE won't affect existing VIBRATE_SOUND state
             mode0 = CameraDevice.AUDIO_RESTRICTION_VIBRATION_SOUND;
             expectMode = mode0 | mode1;
-            retMode = cam0.setCameraAudioRestriction(mode0);
+            cam0.setCameraAudioRestriction(mode0);
+            retMode = cam0.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
 
             mode1 = CameraDevice.AUDIO_RESTRICTION_VIBRATION;
             expectMode = mode0 | mode1;
-            retMode = cam1.setCameraAudioRestriction(mode1);
+            cam1.setCameraAudioRestriction(mode1);
+            retMode = cam1.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
 
             mode1 = CameraDevice.AUDIO_RESTRICTION_NONE;
             expectMode = mode0 | mode1;
-            retMode = cam1.setCameraAudioRestriction(mode1);
+            cam1.setCameraAudioRestriction(mode1);
+            retMode = cam1.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
 
@@ -2831,7 +2862,8 @@
             cam0 = null;
             cam0Cb = null;
             expectMode = mode1;
-            retMode = cam1.setCameraAudioRestriction(mode1);
+            cam1.setCameraAudioRestriction(mode1);
+            retMode = cam1.getCameraAudioRestriction();
             assertTrue("Audio restriction mode mismatch: expect: " + expectMode +
                     ", output:" + retMode, retMode == expectMode);
         } finally {
@@ -2848,15 +2880,16 @@
         }
     }
 
+    @Test
     public void testAudioRestrictionMultipleDevices() throws Exception {
-        if (mCameraIds.length < 2) {
+        if (mCameraIdsUnderTest.length < 2) {
             Log.i(TAG, "device doesn't have multiple cameras, skipping");
             return;
         }
 
-        for (int i = 0; i < mCameraIds.length; i++) {
-            for (int j = i+1; j < mCameraIds.length; j++) {
-                testTwoCameraDevicesAudioRestriction(mCameraIds[i], mCameraIds[j]);
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            for (int j = i+1; j < mCameraIdsUnderTest.length; j++) {
+                testTwoCameraDevicesAudioRestriction(mCameraIdsUnderTest[i], mCameraIdsUnderTest[j]);
             }
         }
     }
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
index 4457f95..922dc3c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
@@ -19,6 +19,7 @@
 import static org.mockito.Mockito.*;
 import static org.mockito.AdditionalMatchers.not;
 import static org.mockito.AdditionalMatchers.and;
+import static junit.framework.Assert.*;
 
 import android.app.ActivityManager;
 import android.app.Instrumentation;
@@ -31,6 +32,7 @@
 import android.hardware.camera2.CameraDevice;
 import android.hardware.camera2.CameraDevice.StateCallback;
 import android.hardware.camera2.CameraManager;
+import android.hardware.camera2.cts.Camera2ParameterizedTestCase;
 import android.hardware.camera2.cts.CameraTestUtils.HandlerExecutor;
 import android.hardware.camera2.cts.CameraTestUtils.MockStateCallback;
 import android.hardware.camera2.cts.helpers.CameraErrorCollector;
@@ -45,6 +47,9 @@
 import com.android.compatibility.common.util.PropertyUtil;
 import com.android.ex.camera2.blocking.BlockingStateCallback;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
 import org.mockito.ArgumentCaptor;
 import org.mockito.InOrder;
 
@@ -61,13 +66,14 @@
 /**
  * <p>Basic test for CameraManager class.</p>
  */
-public class CameraManagerTest extends AndroidTestCase {
+
+@RunWith(Parameterized.class)
+public class CameraManagerTest extends Camera2ParameterizedTestCase {
     private static final String TAG = "CameraManagerTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
     private static final int NUM_CAMERA_REOPENS = 10;
 
     private PackageManager mPackageManager;
-    private CameraManager mCameraManager;
     private NoopCameraListener mListener;
     private HandlerThread mHandlerThread;
     private Handler mHandler;
@@ -75,18 +81,11 @@
     private CameraErrorCollector mCollector;
 
     @Override
-    public void setContext(Context context) {
-        super.setContext(context);
-        mCameraManager = (CameraManager)context.getSystemService(Context.CAMERA_SERVICE);
-        assertNotNull("Can't connect to camera manager", mCameraManager);
-        mPackageManager = context.getPackageManager();
+    public void setUp() throws Exception {
+        super.setUp();
+        mPackageManager = mContext.getPackageManager();
         assertNotNull("Can't get package manager", mPackageManager);
         mListener = new NoopCameraListener();
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
 
         /**
          * Workaround for mockito and JB-MR2 incompatibility
@@ -94,7 +93,7 @@
          * Avoid java.lang.IllegalArgumentException: dexcache == null
          * https://code.google.com/p/dexmaker/issues/detail?id=2
          */
-        System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
+        System.setProperty("dexmaker.dexcache", mContext.getCacheDir().toString());
 
         mCameraListener = spy(new BlockingStateCallback());
 
@@ -105,7 +104,7 @@
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         mHandlerThread.quitSafely();
         mHandler = null;
 
@@ -137,10 +136,10 @@
         return -1; // unreachable
     }
 
+    @Test
     public void testCameraManagerGetDeviceIdList() throws Exception {
 
-        // Test: that the getCameraIdList method runs without exceptions.
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         if (VERBOSE) Log.v(TAG, "CameraManager ids: " + Arrays.toString(ids));
 
         /**
@@ -197,8 +196,9 @@
     }
 
     // Test: that properties can be queried from each device, without exceptions.
+    @Test
     public void testCameraManagerGetCameraCharacteristics() throws Exception {
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         for (int i = 0; i < ids.length; i++) {
             CameraCharacteristics props = mCameraManager.getCameraCharacteristics(ids[i]);
             assertNotNull(
@@ -207,8 +207,9 @@
     }
 
     // Test: that an exception is thrown if an invalid device id is passed down.
+    @Test
     public void testCameraManagerInvalidDevice() throws Exception {
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         // Create an invalid id by concatenating all the valid ids together.
         StringBuilder invalidId = new StringBuilder();
         invalidId.append("INVALID");
@@ -226,6 +227,7 @@
     }
 
     // Test: that each camera device can be opened one at a time, several times.
+    @Test
     public void testCameraManagerOpenCamerasSerially() throws Exception {
         testCameraManagerOpenCamerasSerially(/*useExecutor*/ false);
         testCameraManagerOpenCamerasSerially(/*useExecutor*/ true);
@@ -233,7 +235,7 @@
 
     private void testCameraManagerOpenCamerasSerially(boolean useExecutor) throws Exception {
         final Executor executor = useExecutor ? new HandlerExecutor(mHandler) : null;
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         for (int i = 0; i < ids.length; i++) {
             for (int j = 0; j < NUM_CAMERA_REOPENS; j++) {
                 CameraDevice camera = null;
@@ -268,13 +270,14 @@
      * Test: one or more camera devices can be open at the same time, or the right error state
      * is set if this can't be done.
      */
+    @Test
     public void testCameraManagerOpenAllCameras() throws Exception {
         testCameraManagerOpenAllCameras(/*useExecutor*/ false);
         testCameraManagerOpenAllCameras(/*useExecutor*/ true);
     }
 
     private void testCameraManagerOpenAllCameras(boolean useExecutor) throws Exception {
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         assertNotNull("Camera ids shouldn't be null", ids);
 
         // Skip test if the device doesn't have multiple cameras.
@@ -451,13 +454,14 @@
      * Test: that opening the same device multiple times and make sure the right
      * error state is set.
      */
+    @Test
     public void testCameraManagerOpenCameraTwice() throws Exception {
         testCameraManagerOpenCameraTwice(/*useExecutor*/ false);
         testCameraManagerOpenCameraTwice(/*useExecutor*/ true);
     }
 
     private void testCameraManagerOpenCameraTwice(boolean useExecutor) throws Exception {
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         final Executor executor = useExecutor ? new HandlerExecutor(mHandler) : null;
 
         // Test across every camera device.
@@ -523,6 +527,7 @@
      * Registering a listener multiple times should have no effect, and unregistering
      * a listener that isn't registered should have no effect.
      */
+    @Test
     public void testCameraManagerListener() throws Exception {
         mCameraManager.unregisterAvailabilityCallback(mListener);
         // Test Handler API
@@ -541,6 +546,7 @@
     /**
      * Test that the availability callbacks fire when expected
      */
+    @Test
     public void testCameraManagerListenerCallbacks() throws Exception {
         testCameraManagerListenerCallbacks(/*useExecutor*/ false);
         testCameraManagerListenerCallbacks(/*useExecutor*/ true);
@@ -556,6 +562,17 @@
         CameraManager.AvailabilityCallback ac = new CameraManager.AvailabilityCallback() {
             @Override
             public void onCameraAvailable(String cameraId) {
+                try {
+                    // When we're testing system cameras, we don't list non system cameras in the
+                    // camera id list as mentioned in Camera2ParameterizedTest.java
+                    if (mAdoptShellPerm &&
+                            !CameraTestUtils.isSystemCamera(mCameraManager, cameraId)) {
+                        return;
+                    }
+                } catch (CameraAccessException e) {
+                    fail("CameraAccessException thrown when attempting to access camera" +
+                         "characteristics" + cameraId);
+                }
                 availableEventQueue.offer(cameraId);
             }
 
@@ -570,7 +587,7 @@
         } else {
             mCameraManager.registerAvailabilityCallback(ac, mHandler);
         }
-        String[] cameras = mCameraManager.getCameraIdList();
+        String[] cameras = mCameraIdsUnderTest;
 
         if (cameras.length == 0) {
             Log.i(TAG, "No cameras present, skipping test");
@@ -683,12 +700,13 @@
     } // testCameraManagerListenerCallbacks
 
     // Verify no LEGACY-level devices appear on devices first launched in the Q release or newer
+    @Test
     public void testNoLegacyOnQ() throws Exception {
         if(PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.Q){
             // LEGACY still allowed for devices upgrading to Q
             return;
         }
-        String[] ids = mCameraManager.getCameraIdList();
+        String[] ids = mCameraIdsUnderTest;
         for (int i = 0; i < ids.length; i++) {
             CameraCharacteristics props = mCameraManager.getCameraCharacteristics(ids[i]);
             assertNotNull(
@@ -703,14 +721,15 @@
         }
     }
 
+    @Test
     public void testCameraManagerWithDnD() throws Exception {
-        String[] cameras = mCameraManager.getCameraIdList();
+        String[] cameras = mCameraIdsUnderTest;
         if (cameras.length == 0) {
             Log.i(TAG, "No cameras present, skipping test");
             return;
         }
 
-        ActivityManager am = getContext().getSystemService(ActivityManager.class);
+        ActivityManager am = mContext.getSystemService(ActivityManager.class);
 
         // Go devices do not support all interrupt filtering functionality
         if (am.isLowRamDevice()) {
@@ -718,12 +737,12 @@
         }
 
         // Allow the test package to adjust notification policy
-        toggleNotificationPolicyAccess(getContext().getPackageName(),
+        toggleNotificationPolicyAccess(mContext.getPackageName(),
                 InstrumentationRegistry.getInstrumentation(), true);
 
         // Enable DnD filtering
 
-        NotificationManager nm = getContext().getSystemService(NotificationManager.class);
+        NotificationManager nm = mContext.getSystemService(NotificationManager.class);
         try {
             nm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
 
@@ -755,7 +774,7 @@
 
         runCommand(command, instrumentation);
 
-        NotificationManager nm = getContext().getSystemService(NotificationManager.class);
+        NotificationManager nm = mContext.getSystemService(NotificationManager.class);
         assertEquals("Notification Policy Access Grant is " +
                 nm.isNotificationPolicyAccessGranted() + " not " + on, on,
                 nm.isNotificationPolicyAccessGranted());
@@ -764,17 +783,14 @@
     private void runCommand(String command, Instrumentation instrumentation) throws IOException {
         UiAutomation uiAutomation = instrumentation.getUiAutomation();
         // Execute command
-        try (ParcelFileDescriptor fd = uiAutomation.executeShellCommand(command)) {
-            assertNotNull("Failed to execute shell command: " + command, fd);
-            // Wait for the command to finish by reading until EOF
-            try (InputStream in = new FileInputStream(fd.getFileDescriptor())) {
-                byte[] buffer = new byte[4096];
-                while (in.read(buffer) > 0) {}
-            } catch (IOException e) {
-                throw new IOException("Could not read stdout of command: " + command, e);
-            }
-        } finally {
-            uiAutomation.destroy();
+        ParcelFileDescriptor fd = mUiAutomation.executeShellCommand(command);
+        assertNotNull("Failed to execute shell command: " + command, fd);
+        // Wait for the command to finish by reading until EOF
+        try (InputStream in = new FileInputStream(fd.getFileDescriptor())) {
+            byte[] buffer = new byte[4096];
+            while (in.read(buffer) > 0) {}
+        } catch (IOException e) {
+            throw new IOException("Could not read stdout of command: " + command, e);
         }
     }
 
diff --git a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
index 2a46cf7..b02f13d 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CaptureRequestTest.java
@@ -52,6 +52,8 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 /**
@@ -63,6 +65,8 @@
  * manual ISP control and other per-frame control and synchronization.
  * </p>
  */
+
+@RunWith(Parameterized.class)
 public class CaptureRequestTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "CaptureRequestTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -147,9 +151,9 @@
         SurfaceTexture outputTexture = new SurfaceTexture(/* random texture ID */ 5);
         Surface surface = new Surface(outputTexture);
 
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 CaptureRequest.Builder requestBuilder =
                         mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                 requestBuilder.addTarget(surface);
@@ -236,14 +240,14 @@
      */
     @Test
     public void testBlackLevelLock() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isCapabilitySupported(
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isCapabilitySupported(
                         CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 SimpleCaptureCallback listener = new SimpleCaptureCallback();
                 CaptureRequest.Builder requestBuilder =
                         mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
@@ -290,7 +294,7 @@
      */
     @Test
     public void testDynamicBlackWhiteLevel() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isDynamicBlackLevelSupported()) {
                     continue;
@@ -318,11 +322,11 @@
      */
     @Test
     public void testLensShadingMap() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIds[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
                 if (!staticInfo.isManualLensShadingMapSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " doesn't support lens shading controls, skipping test");
                     continue;
                 }
@@ -334,7 +338,7 @@
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 SimpleCaptureCallback listener = new SimpleCaptureCallback();
                 CaptureRequest.Builder requestBuilder =
                         mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
@@ -396,15 +400,15 @@
      */
     @Test
     public void testAntiBandingModes() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
                 // Without manual sensor control, exposure time cannot be verified
-                if (!mAllStaticInfo.get(mCameraIds[i]).isCapabilitySupported(
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isCapabilitySupported(
                         CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 int[] modes = mStaticInfo.getAeAvailableAntiBandingModesChecked();
 
                 Size previewSz =
@@ -432,15 +436,15 @@
      */
     @Test(timeout=60*60*1000) // timeout = 60 mins for long running tests
     public void testAeModeAndLock() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 Size maxPreviewSz = mOrderedPreviewSizes.get(0); // Max preview size.
 
                 // Update preview surface with given size for all sub-tests.
@@ -465,15 +469,15 @@
      */
     @Test
     public void testFlashControl() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 SimpleCaptureCallback listener = new SimpleCaptureCallback();
                 CaptureRequest.Builder requestBuilder =
                         mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
@@ -509,15 +513,15 @@
      */
     @Test
     public void testFlashTurnOff() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 SimpleCaptureCallback listener = new SimpleCaptureCallback();
                 CaptureRequest.Builder requestBuilder =
                         mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
@@ -550,14 +554,14 @@
      */
     @Test
     public void testFaceDetection() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 faceDetectionTestByCamera();
             } finally {
                 closeDevice();
@@ -570,7 +574,7 @@
      */
     @Test
     public void testToneMapControl() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isManualToneMapSupported()) {
                     Log.i(TAG, "Camera " + id +
@@ -590,7 +594,7 @@
      */
     @Test
     public void testColorCorrectionControl() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorCorrectionSupported()) {
                     Log.i(TAG, "Camera " + id +
@@ -610,7 +614,7 @@
      */
     @Test
     public void testEdgeModeControl() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isEdgeModeControlSupported()) {
                     Log.i(TAG, "Camera " + id +
@@ -632,7 +636,7 @@
      */
     @Test
     public void testEdgeModeControlFastFps() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isEdgeModeControlSupported()) {
                     Log.i(TAG, "Camera " + id +
@@ -655,7 +659,7 @@
      */
     @Test
     public void testFocusDistanceControl() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
                 if (!staticInfo.hasFocuser()) {
@@ -683,7 +687,7 @@
      */
     @Test
     public void testNoiseReductionModeControl() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isNoiseReductionModeControlSupported()) {
                     Log.i(TAG, "Camera " + id +
@@ -705,7 +709,7 @@
      */
     @Test
     public void testNoiseReductionModeControlFastFps() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isNoiseReductionModeControlSupported()) {
                     Log.i(TAG, "Camera " + id +
@@ -729,7 +733,7 @@
      */
     @Test
     public void testAwbModeAndLock() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
@@ -748,7 +752,7 @@
      */
     @Test
     public void testAfModes() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
@@ -767,7 +771,7 @@
      */
     @Test
     public void testCameraStabilizations() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
                 List<Key<?>> keys = staticInfo.getCharacteristics().getKeys();
@@ -796,7 +800,7 @@
      */
     @Test
     public void testDigitalZoom() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
@@ -817,7 +821,7 @@
      */
     @Test
     public void testDigitalZoomPreviewCombinations() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
@@ -836,7 +840,7 @@
      */
     @Test
     public void testSceneModes() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (mAllStaticInfo.get(id).isSceneModeSupported()) {
                     openDevice(id);
@@ -853,7 +857,7 @@
      */
     @Test
     public void testEffectModes() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
diff --git a/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java b/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java
index 6f6b13c..0e68bd4 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java
@@ -38,6 +38,7 @@
 
 import static android.hardware.camera2.cts.CameraTestUtils.*;
 import static android.hardware.camera2.cts.helpers.CameraSessionUtils.*;
+import static junit.framework.Assert.*;
 
 import android.util.Log;
 import android.view.Surface;
@@ -52,6 +53,11 @@
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+@RunWith(Parameterized.class)
 public class CaptureResultTest extends Camera2AndroidTestCase {
     private static final String TAG = "CaptureResultTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -59,29 +65,15 @@
     private static final int NUM_FRAMES_VERIFIED = 30;
     private static final long WAIT_FOR_RESULT_TIMEOUT_MS = 3000;
 
-
     // List tracking the failed test keys.
 
     @Override
-    public void setContext(Context context) {
-        super.setContext(context);
-
-        /**
-         * Workaround for mockito and JB-MR2 incompatibility
-         *
-         * Avoid java.lang.IllegalArgumentException: dexcache == null
-         * https://code.google.com/p/dexmaker/issues/detail?id=2
-         */
-        System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
-    }
-
-    @Override
-    protected void setUp() throws Exception {
+    public void setUp() throws Exception {
         super.setUp();
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         super.tearDown();
     }
 
@@ -96,8 +88,9 @@
      * a capture result.
      * </p>
      */
+    @Test
     public void testCameraCaptureResultAllKeys() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 openDevice(id);
                 if (mStaticInfo.isColorOutputSupported()) {
@@ -150,10 +143,11 @@
      * onCaptureProgressed callbacks.
      * </ul></p>
      */
+    @Test
     public void testPartialResult() throws Exception {
         final int NUM_FRAMES_TESTED = 30;
         final int WAIT_FOR_RESULT_TIMOUT_MS = 2000;
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 // Skip the test if partial result is not supported
                 int partialResultCount = mAllStaticInfo.get(id).getPartialResultCount();
@@ -265,8 +259,9 @@
      * Check that the timestamps passed in the results, buffers, and capture callbacks match for
      * a single request, and increase monotonically
      */
+    @Test
     public void testResultTimestamps() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             ImageReader previewReader = null;
             ImageReader jpegReader = null;
 
diff --git a/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java b/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java
index 4af437c..b0c806f 100644
--- a/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/DngCreatorTest.java
@@ -60,11 +60,18 @@
 import java.util.TimeZone;
 import java.text.SimpleDateFormat;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
 import static android.hardware.camera2.cts.helpers.AssertHelpers.*;
+import static junit.framework.Assert.*;
 
 /**
  * Tests for the DngCreator API.
  */
+
+@RunWith(Parameterized.class)
 public class DngCreatorTest extends Camera2AndroidTestCase {
     private static final String TAG = "DngCreatorTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -99,24 +106,17 @@
     }
 
     @Override
-    protected void setUp() throws Exception {
-        RenderScriptSingleton.setContext(getContext());
-
+    public void setUp() throws Exception {
         super.setUp();
+        RenderScriptSingleton.setContext(mContext);
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         RenderScriptSingleton.clearContext();
-
         super.tearDown();
     }
 
-    @Override
-    public synchronized void setContext(Context context) {
-        super.setContext(context);
-    }
-
     /**
      * Test basic raw capture and DNG saving functionality for each of the available cameras.
      *
@@ -131,16 +131,17 @@
      * raw image captured for the first reported camera device to be saved to an output file.
      * </p>
      */
+    @Test
     public void testSingleImageBasic() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            String deviceId = mCameraIds[i];
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            String deviceId = mCameraIdsUnderTest[i];
             ImageReader captureReader = null;
             FileOutputStream fileStream = null;
             ByteArrayOutputStream outputStream = null;
             try {
                 if (!mAllStaticInfo.get(deviceId).isCapabilitySupported(
                         CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
-                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIds[i] +
+                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIdsUnderTest[i] +
                             ". Skip the test.");
                     continue;
                 }
@@ -205,9 +206,10 @@
      * raw image captured for the first reported camera device to be saved to an output file.
      * </p>
      */
+    @Test
     public void testSingleImageThumbnail() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
-            String deviceId = mCameraIds[i];
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            String deviceId = mCameraIdsUnderTest[i];
             List<ImageReader> captureReaders = new ArrayList<ImageReader>();
             List<CameraTestUtils.SimpleImageReaderListener> captureListeners =
                     new ArrayList<CameraTestUtils.SimpleImageReaderListener>();
@@ -216,7 +218,7 @@
             try {
                 if (!mAllStaticInfo.get(deviceId).isCapabilitySupported(
                         CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
-                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIds[i] +
+                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIdsUnderTest[i] +
                             ". Skip the test.");
                     continue;
                 }
@@ -369,8 +371,9 @@
      * adb shell setprop log.tag.DngCreatorTest VERBOSE
      * </p>
      */
+    @Test
     public void testRaw16JpegConsistency() throws Exception {
-        for (String deviceId : mCameraIds) {
+        for (String deviceId : mCameraIdsUnderTest) {
             List<ImageReader> captureReaders = new ArrayList<>();
             FileOutputStream fileStream = null;
             ByteArrayOutputStream outputStream = null;
@@ -461,8 +464,9 @@
     /**
      * Test basic DNG creation, ensure that the DNG image can be rendered by BitmapFactory.
      */
+    @Test
     public void testDngRenderingByBitmapFactor() throws Exception {
-        for (String deviceId : mCameraIds) {
+        for (String deviceId : mCameraIdsUnderTest) {
             List<ImageReader> captureReaders = new ArrayList<>();
 
             CapturedData data = captureRawJpegImagePair(deviceId, captureReaders);
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index a5ea222..d761c6f 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -59,14 +59,21 @@
 import java.util.regex.Pattern;
 import java.util.Set;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
 import static android.hardware.camera2.cts.helpers.AssertHelpers.*;
 import static android.hardware.camera2.cts.CameraTestUtils.SimpleCaptureCallback;
 
+import static junit.framework.Assert.*;
+
 import static org.mockito.Mockito.*;
 
 /**
  * Extended tests for static camera characteristics.
  */
+@RunWith(Parameterized.class)
 public class ExtendedCameraCharacteristicsTest extends Camera2AndroidTestCase {
     private static final String TAG = "ExChrsTest"; // must be short so next line doesn't throw
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -128,7 +135,7 @@
     private static final int HIGH_SPEED_FPS_UPPER_MIN = 120;
 
     @Override
-    protected void setUp() throws Exception {
+    public void setUp() throws Exception {
         super.setUp();
         mCharacteristics = new ArrayList<>();
         for (int i = 0; i < mAllCameraIds.length; i++) {
@@ -137,7 +144,7 @@
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         super.tearDown();
         mCharacteristics = null;
     }
@@ -146,6 +153,7 @@
      * Test that the available stream configurations contain a few required formats and sizes.
      */
     @CddTest(requirement="7.5.1/C-1-2")
+    @Test
     public void testAvailableStreamConfigs() throws Exception {
         boolean firstBackFacingCamera = true;
         for (int i = 0; i < mAllCameraIds.length; i++) {
@@ -169,7 +177,7 @@
 
             boolean isMonochromeWithY8 = arrayContains(actualCapabilities, MONOCHROME)
                     && arrayContains(outputFormats, ImageFormat.Y8);
-            boolean isHiddenPhysicalCamera = !arrayContains(mCameraIds, mAllCameraIds[i]);
+            boolean isHiddenPhysicalCamera = !arrayContains(mCameraIdsUnderTest, mAllCameraIds[i]);
             boolean supportHeic = arrayContains(outputFormats, ImageFormat.HEIC);
 
             assertArrayContains(
@@ -769,6 +777,7 @@
 
     }
 
+    @Test
     public void testRecommendedStreamConfigurations() throws Exception {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -868,6 +877,7 @@
     /**
      * Test {@link CameraCharacteristics#getKeys}
      */
+    @Test
     public void testKeys() {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -1036,6 +1046,7 @@
     /**
      * Test values for static metadata used by the RAW capability.
      */
+    @Test
     public void testStaticRawCharacteristics() {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -1142,6 +1153,7 @@
     /**
      * Test values for the available session keys.
      */
+    @Test
     public void testStaticSessionKeys() throws Exception {
         for (CameraCharacteristics c : mCharacteristics) {
             List<CaptureRequest.Key<?>> availableSessionKeys = c.getAvailableSessionKeys();
@@ -1161,6 +1173,7 @@
     /**
      * Test values for static metadata used by the BURST capability.
      */
+    @Test
     public void testStaticBurstCharacteristics() throws Exception {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -1325,6 +1338,7 @@
     /**
      * Check reprocessing capabilities.
      */
+    @Test
     public void testReprocessingCharacteristics() {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             Log.i(TAG, "testReprocessingCharacteristics: Testing camera ID " + mAllCameraIds[i]);
@@ -1453,6 +1467,7 @@
     /**
      * Check depth output capability
      */
+    @Test
     public void testDepthOutputCharacteristics() {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             Log.i(TAG, "testDepthOutputCharacteristics: Testing camera ID " + mAllCameraIds[i]);
@@ -1728,6 +1743,7 @@
     /**
      * Cross-check StreamConfigurationMap output
      */
+    @Test
     public void testStreamConfigurationMap() throws Exception {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             Log.i(TAG, "testStreamConfigurationMap: Testing camera ID " + mAllCameraIds[i]);
@@ -1933,6 +1949,7 @@
      * Test high speed capability and cross-check the high speed sizes and fps ranges from
      * the StreamConfigurationMap.
      */
+    @Test
     public void testConstrainedHighSpeedCapability() throws Exception {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -2013,6 +2030,7 @@
     /**
      * Sanity check of optical black regions.
      */
+    @Test
     public void testOpticalBlackRegions() {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -2089,6 +2107,7 @@
     /**
      * Check Logical camera capability
      */
+    @Test
     public void testLogicalCameraCharacteristics() throws Exception {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
@@ -2163,6 +2182,7 @@
     /**
      * Check monochrome camera capability
      */
+    @Test
     public void testMonochromeCharacteristics() {
         for (int i = 0; i < mAllCameraIds.length; i++) {
             Log.i(TAG, "testMonochromeCharacteristics: Testing camera ID " + mAllCameraIds[i]);
@@ -2297,7 +2317,13 @@
      * accessible via Camera2.
      */
     @CddTest(requirement="7.5.4/C-0-11")
+    @Test
     public void testLegacyCameraDeviceParity() {
+        if (mAdoptShellPerm) {
+            // There is no current way to determine in camera1 api if a device is a system camera
+            // Skip test, http://b/141496896
+            return;
+        }
         int legacyDeviceCount = Camera.getNumberOfCameras();
         assertTrue("More legacy devices: " + legacyDeviceCount + " compared to Camera2 devices: " +
                 mCharacteristics.size(), legacyDeviceCount <= mCharacteristics.size());
@@ -2339,6 +2365,7 @@
      * Check camera orientation against device orientation
      */
     @CddTest(requirement="7.5.5/C-1-1")
+    @Test
     public void testCameraOrientationAlignedWithDevice() {
         WindowManager windowManager =
                 (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
diff --git a/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java b/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java
index 0716c24..fc09e51 100644
--- a/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java
@@ -41,6 +41,8 @@
 import android.hardware.camera2.cts.CameraTestUtils.SimpleImageReaderListener;
 import android.hardware.camera2.cts.testcases.Camera2SurfaceViewTestCase;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 /**
@@ -50,6 +52,8 @@
  * May not take more than a few seconds to run, to be suitable for quick
  * testing.
  */
+
+@RunWith(Parameterized.class)
 public class FastBasicsTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "FastBasicsTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -62,17 +66,17 @@
     @Presubmit
     @Test
     public void testCamera2() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing camera2 API for camera device " + mCameraIds[i]);
+                Log.i(TAG, "Testing camera2 API for camera device " + mCameraIdsUnderTest[i]);
 
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 camera2TestByCamera();
             } finally {
                 closeDevice();
diff --git a/tests/camera/src/android/hardware/camera2/cts/FlashlightTest.java b/tests/camera/src/android/hardware/camera2/cts/FlashlightTest.java
index 1aa6a17..fb1bd6c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/FlashlightTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/FlashlightTest.java
@@ -31,10 +31,17 @@
 import java.util.concurrent.TimeUnit;
 
 import static org.mockito.Mockito.*;
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import static junit.framework.Assert.*;
 
 /**
  * <p>Tests for flashlight API.</p>
  */
+
+@RunWith(Parameterized.class)
 public class FlashlightTest extends Camera2AndroidTestCase {
     private static final String TAG = "FlashlightTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -45,13 +52,13 @@
     private ArrayList<String> mFlashCameraIdList;
 
     @Override
-    protected void setUp() throws Exception {
+    public void setUp() throws Exception {
         super.setUp();
 
         // initialize the list of cameras that have a flash unit so it won't interfere with
         // flash tests.
         mFlashCameraIdList = new ArrayList<String>();
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             StaticMetadata info =
                     new StaticMetadata(mCameraManager.getCameraCharacteristics(id),
                                        CheckLevel.ASSERT, /*collector*/ null);
@@ -61,6 +68,7 @@
         }
     }
 
+    @Test
     public void testSetTorchModeOnOff() throws Exception {
         if (mFlashCameraIdList.size() == 0)
             return;
@@ -124,6 +132,7 @@
         }
     }
 
+    @Test
     public void testTorchCallback() throws Exception {
         testTorchCallback(/*useExecutor*/ false);
         testTorchCallback(/*useExecutor*/ true);
@@ -169,12 +178,13 @@
         }
     }
 
+    @Test
     public void testCameraDeviceOpenAfterTorchOn() throws Exception {
         if (mFlashCameraIdList.size() == 0)
             return;
 
         for (String id : mFlashCameraIdList) {
-            for (String idToOpen : mCameraIds) {
+            for (String idToOpen : mCameraIdsUnderTest) {
                 resetTorchModeStatus(id);
 
                 CameraManager.TorchCallback torchListener =
@@ -225,15 +235,16 @@
         }
     }
 
+    @Test
     public void testTorchModeExceptions() throws Exception {
         // cameraIdsToTestTorch = all available camera ID + non-existing camera id +
         //                        non-existing numeric camera id + null
-        String[] cameraIdsToTestTorch = new String[mCameraIds.length + 3];
-        System.arraycopy(mCameraIds, 0, cameraIdsToTestTorch, 0, mCameraIds.length);
-        cameraIdsToTestTorch[mCameraIds.length] = generateNonexistingCameraId();
-        cameraIdsToTestTorch[mCameraIds.length + 1] = generateNonexistingNumericCameraId();
+        String[] cameraIdsToTestTorch = new String[mCameraIdsUnderTest.length + 3];
+        System.arraycopy(mCameraIdsUnderTest, 0, cameraIdsToTestTorch, 0, mCameraIdsUnderTest.length);
+        cameraIdsToTestTorch[mCameraIdsUnderTest.length] = generateNonexistingCameraId();
+        cameraIdsToTestTorch[mCameraIdsUnderTest.length + 1] = generateNonexistingNumericCameraId();
 
-        for (String idToOpen : mCameraIds) {
+        for (String idToOpen : mCameraIdsUnderTest) {
             openDevice(idToOpen);
             try {
                 for (String id : cameraIdsToTestTorch) {
@@ -288,8 +299,8 @@
 
     private String generateNonexistingCameraId() {
         String nonExisting = "none_existing_camera";
-        for (String id : mCameraIds) {
-            if (Arrays.asList(mCameraIds).contains(nonExisting)) {
+        for (String id : mCameraIdsUnderTest) {
+            if (Arrays.asList(mCameraIdsUnderTest).contains(nonExisting)) {
                 nonExisting += id;
             } else {
                 break;
@@ -299,11 +310,15 @@
     }
 
     // return a non-existing and non-negative numeric camera id.
-    private String generateNonexistingNumericCameraId() {
-        int[] numericCameraIds = new int[mCameraIds.length];
+    private String generateNonexistingNumericCameraId() throws Exception {
+        // We don't rely on mCameraIdsUnderTest to generate a non existing camera id since
+        // mCameraIdsUnderTest doesn't give us an accurate reflection of which camera ids actually
+        // exist. It just tells us the ones we're testing right now.
+        String[] allCameraIds = mCameraManager.getCameraIdListNoLazy();
+        int[] numericCameraIds = new int[allCameraIds.length];
         int size = 0;
 
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : allCameraIds) {
             try {
                 int value = Integer.parseInt(cameraId);
                 if (value >= 0) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/HeifWriterTest.java b/tests/camera/src/android/hardware/camera2/cts/HeifWriterTest.java
index 0cb5c1b..f729cc7 100644
--- a/tests/camera/src/android/hardware/camera2/cts/HeifWriterTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/HeifWriterTest.java
@@ -55,6 +55,11 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+@RunWith(Parameterized.class)
 public class HeifWriterTest extends Camera2AndroidTestCase {
     private static final String TAG = HeifWriterTest.class.getSimpleName();
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -79,6 +84,7 @@
         super.tearDown();
     }
 
+    @Test
     public void testHeif() throws Exception {
         final int NUM_SINGLE_CAPTURE_TESTED = 3;
         final int NUM_HEIC_CAPTURE_TESTED = 2;
@@ -93,7 +99,7 @@
         boolean sessionFailure = false;
         Integer[] sessionStates = {BlockingSessionCallback.SESSION_READY,
                 BlockingSessionCallback.SESSION_CONFIGURE_FAILED};
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing HEIF capture for Camera " + id);
                 openDevice(id);
diff --git a/tests/camera/src/android/hardware/camera2/cts/IdleUidTest.java b/tests/camera/src/android/hardware/camera2/cts/IdleUidTest.java
index 34d0947..9caf365 100644
--- a/tests/camera/src/android/hardware/camera2/cts/IdleUidTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/IdleUidTest.java
@@ -26,9 +26,12 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 
+import android.hardware.camera2.cts.Camera2ParameterizedTestCase;
+import android.hardware.camera2.cts.CameraTestUtils;
 import android.hardware.camera2.CameraAccessException;
 import android.hardware.camera2.CameraDevice;
 import android.hardware.camera2.CameraManager;
+
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.Process;
@@ -40,6 +43,8 @@
 
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
@@ -52,8 +57,9 @@
  * get an error callback losing the camera handle. Similarly if the UID is
  * already idle it cannot obtain a camera handle.
  */
-@RunWith(AndroidJUnit4.class)
-public final class IdleUidTest {
+
+@RunWith(Parameterized.class)
+public final class IdleUidTest extends Camera2ParameterizedTestCase {
     private static final long CAMERA_OPERATION_TIMEOUT_MILLIS = 5000; // 5 sec
 
     private static final HandlerThread sCallbackThread = new HandlerThread("Callback thread");
@@ -73,10 +79,8 @@
      */
     @Test
     public void testCameraAccessForIdleUid() throws Exception {
-        final CameraManager cameraManager = InstrumentationRegistry.getTargetContext()
-                .getSystemService(CameraManager.class);
-        for (String cameraId : cameraManager.getCameraIdList()) {
-            testCameraAccessForIdleUidByCamera(cameraManager, cameraId,
+        for (String cameraId : mCameraIdsUnderTest) {
+            testCameraAccessForIdleUidByCamera(cameraId,
                     new Handler(sCallbackThread.getLooper()));
         }
     }
@@ -86,32 +90,29 @@
      */
     @Test
     public void testCameraAccessBecomingInactiveUid() throws Exception {
-        final CameraManager cameraManager = InstrumentationRegistry.getTargetContext()
-                .getSystemService(CameraManager.class);
-        for (String cameraId : cameraManager.getCameraIdList()) {
-            testCameraAccessBecomingInactiveUidByCamera(cameraManager, cameraId,
+        for (String cameraId : mCameraIdsUnderTest) {
+            testCameraAccessBecomingInactiveUidByCamera(cameraId,
                     new Handler(sCallbackThread.getLooper()));
         }
-
     }
 
-    private void testCameraAccessForIdleUidByCamera(CameraManager cameraManager,
-            String cameraId, Handler handler) throws Exception {
+    private void testCameraAccessForIdleUidByCamera(String cameraId, Handler handler)
+            throws Exception {
         // Can access camera from an active UID.
-        assertCameraAccess(cameraManager, cameraId, true, handler);
+        assertCameraAccess(mCameraManager, cameraId, true, handler);
 
         // Make our UID idle
         makeMyPackageIdle();
         try {
             // Can not access camera from an idle UID.
-            assertCameraAccess(cameraManager, cameraId, false, handler);
+            assertCameraAccess(mCameraManager, cameraId, false, handler);
         } finally {
             // Restore our UID as active
             makeMyPackageActive();
         }
 
         // Can access camera from an active UID.
-        assertCameraAccess(cameraManager, cameraId, true, handler);
+        assertCameraAccess(mCameraManager, cameraId, true, handler);
     }
 
     private static void assertCameraAccess(CameraManager cameraManager,
@@ -152,14 +153,14 @@
         }
     }
 
-    private void testCameraAccessBecomingInactiveUidByCamera(CameraManager cameraManager,
-            String cameraId, Handler handler) throws Exception {
+    private void testCameraAccessBecomingInactiveUidByCamera(String cameraId, Handler handler)
+            throws Exception {
         // Mock the callback used to observe camera state.
         final CameraDevice.StateCallback callback = mock(CameraDevice.StateCallback.class);
 
         // Open the camera
         try {
-            cameraManager.openCamera(cameraId, callback, handler);
+            mCameraManager.openCamera(cameraId, callback, handler);
         } catch (CameraAccessException e) {
             fail("Unexpected exception" + e);
         }
diff --git a/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java b/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java
index abd6bb6..971b51c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java
@@ -52,11 +52,17 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.Test;
+
 import static android.hardware.camera2.cts.CameraTestUtils.CAPTURE_RESULT_TIMEOUT_MS;
+import static android.hardware.camera2.cts.CameraTestUtils.SESSION_READY_TIMEOUT_MS;
 import static android.hardware.camera2.cts.CameraTestUtils.SimpleCaptureCallback;
 import static android.hardware.camera2.cts.CameraTestUtils.SimpleImageReaderListener;
 import static android.hardware.camera2.cts.CameraTestUtils.dumpFile;
 import static android.hardware.camera2.cts.CameraTestUtils.getValueNotNull;
+import static junit.framework.Assert.*;
 
 /**
  * <p>Basic test for ImageReader APIs. It uses CameraDevice as producer, camera
@@ -68,6 +74,7 @@
  * <p>Some invalid access test. </p>
  * <p>TODO: Add more format tests? </p>
  */
+@RunWith(Parameterized.class)
 public class ImageReaderTest extends Camera2AndroidTestCase {
     private static final String TAG = "ImageReaderTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -92,22 +99,18 @@
     private SimpleImageListener mListener;
 
     @Override
-    public void setContext(Context context) {
-        super.setContext(context);
-    }
-
-    @Override
-    protected void setUp() throws Exception {
+    public void setUp() throws Exception {
         super.setUp();
     }
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         super.tearDown();
     }
 
+    @Test
     public void testFlexibleYuv() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 openDevice(id);
@@ -118,8 +121,9 @@
         }
     }
 
+    @Test
     public void testDepth16() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 openDevice(id);
@@ -130,8 +134,9 @@
         }
     }
 
+    @Test
     public void testDepthPointCloud() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 openDevice(id);
@@ -142,8 +147,9 @@
         }
     }
 
+    @Test
     public void testDynamicDepth() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 openDevice(id);
                 bufferFormatTestByCamera(ImageFormat.DEPTH_JPEG, /*repeating*/true,
@@ -154,8 +160,9 @@
         }
     }
 
+    @Test
     public void testY8() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 openDevice(id);
@@ -166,8 +173,9 @@
         }
     }
 
+    @Test
     public void testJpeg() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing jpeg capture for Camera " + id);
                 openDevice(id);
@@ -178,8 +186,9 @@
         }
     }
 
+    @Test
     public void testRaw() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing raw capture for camera " + id);
                 openDevice(id);
@@ -191,8 +200,9 @@
         }
     }
 
+    @Test
     public void testRawPrivate() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing raw capture for camera " + id);
                 openDevice(id);
@@ -204,8 +214,9 @@
         }
     }
 
+    @Test
     public void testHeic() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing heic capture for Camera " + id);
                 openDevice(id);
@@ -216,8 +227,9 @@
         }
     }
 
+    @Test
     public void testRepeatingJpeg() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing repeating jpeg capture for Camera " + id);
                 openDevice(id);
@@ -228,8 +240,9 @@
         }
     }
 
+    @Test
     public void testRepeatingRaw() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing repeating raw capture for camera " + id);
                 openDevice(id);
@@ -241,8 +254,9 @@
         }
     }
 
+    @Test
     public void testRepeatingRawPrivate() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing repeating raw capture for camera " + id);
                 openDevice(id);
@@ -254,8 +268,9 @@
         }
     }
 
+    @Test
     public void testRepeatingHeic() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing repeating heic capture for Camera " + id);
                 openDevice(id);
@@ -266,8 +281,9 @@
         }
     }
 
+    @Test
     public void testLongProcessingRepeatingRaw() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing long processing on repeating raw for camera " + id);
 
@@ -284,8 +300,9 @@
         }
     }
 
+    @Test
     public void testLongProcessingRepeatingFlexibleYuv() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing long processing on repeating YUV for camera " + id);
 
@@ -309,9 +326,10 @@
      * for camera case. For if the produced image byte buffer is not direct byte buffer, there
      * is no guarantee to get an ISE for this invalid access case.
      */
+    @Test
     public void testInvalidAccessTest() throws Exception {
         // Test byte buffer access after an image is released, it should throw ISE.
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing invalid image access for Camera " + id);
                 openDevice(id);
@@ -328,8 +346,9 @@
      *
      * <p>Both stream formats are mandatory for Camera2 API</p>
      */
+    @Test
     public void testYuvAndJpeg() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "YUV and JPEG testing for camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -351,8 +370,9 @@
      *
      * <p>Both stream formats are mandatory for Camera2 API</p>
      */
+    @Test
     public void testYuvAndJpegWithUsageFlag() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "YUV and JPEG testing for camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -372,8 +392,9 @@
      * Test two image stream (YUV420_888 and RAW_SENSOR) capture by using ImageReader.
      *
      */
+    @Test
     public void testImageReaderYuvAndRaw() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "YUV and RAW testing for camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -394,8 +415,9 @@
      * ImageFormat.PRIVATE + PROTECTED usage capture by using ImageReader with the
      * ImageReader factory method that has usage flag argument, and uses a custom usage flag.
      */
+    @Test
     public void testImageReaderPrivateWithProtectedUsageFlag() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Private format and protected usage testing for camera " + id);
                 if (!mAllStaticInfo.get(id).isCapabilitySupported(
@@ -420,8 +442,9 @@
      * ImageReader factory method that has usage flag argument.
      *
      */
+    @Test
     public void testImageReaderYuvAndRawWithUsageFlag() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "YUV and RAW testing for camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -441,10 +464,11 @@
      * Check that the center patches for YUV and JPEG outputs for the same frame match for each YUV
      * resolution and format supported.
      */
+    @Test
     public void testAllOutputYUVResolutions() throws Exception {
         Integer[] sessionStates = {BlockingSessionCallback.SESSION_READY,
                 BlockingSessionCallback.SESSION_CONFIGURE_FAILED};
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.v(TAG, "Testing all YUV image resolutions for camera " + id);
 
@@ -685,10 +709,11 @@
     /**
      * Test that images captured after discarding free buffers are valid.
      */
+    @Test
     public void testDiscardFreeBuffers() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
-                Log.v(TAG, "Testing jpeg capture for Camera " + id);
+                Log.v(TAG, "Testing discardFreeBuffers for Camera " + id);
                 openDevice(id);
                 discardFreeBuffersTestByCamera();
             } finally {
@@ -698,6 +723,7 @@
     }
 
     /** Tests that usage bits are preserved */
+    @Test
     public void testUsageRespected() throws Exception {
         ImageReader reader = ImageReader.newInstance(1, 1, PixelFormat.RGBA_8888, 1,
                 HardwareBuffer.USAGE_GPU_COLOR_OUTPUT | HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE);
@@ -964,13 +990,13 @@
 
         final Size SIZE = mStaticInfo.getAvailableSizesForFormatChecked(FORMAT,
                 StaticMetadata.StreamDirection.Output)[0];
-        Image img = null;
         // Create ImageReader.
         mListener = new SimpleImageListener();
         createDefaultImageReader(SIZE, FORMAT, MAX_NUM_IMAGES, mListener);
 
         // Start capture.
         final boolean REPEATING = true;
+        final boolean SINGLE = false;
         CaptureRequest request = prepareCaptureRequest();
         SimpleCaptureCallback listener = new SimpleCaptureCallback();
         startCapture(request, REPEATING, listener, mHandler);
@@ -985,6 +1011,23 @@
         // Validate images and capture resulst again.
         validateImage(SIZE, FORMAT, NUM_FRAME_VERIFIED, REPEATING);
         validateCaptureResult(FORMAT, SIZE, listener, NUM_FRAME_VERIFIED);
+
+        // Stop repeating request in preparation for discardFreeBuffers
+        mCameraSession.stopRepeating();
+        mCameraSessionListener.getStateWaiter().waitForState(
+                BlockingSessionCallback.SESSION_READY, SESSION_READY_TIMEOUT_MS);
+
+        // Drain the reader queue and discard free buffers from the reader.
+        Image img = mReader.acquireLatestImage();
+        if (img != null) {
+            img.close();
+        }
+        mReader.discardFreeBuffers();
+
+        // Do a single capture for camera device to reallocate buffers
+        mListener.reset();
+        startCapture(request, SINGLE, listener, mHandler);
+        validateImage(SIZE, FORMAT, /*captureCount*/1, SINGLE);
     }
 
     private void bufferFormatTestByCamera(int format, boolean repeating) throws Exception {
@@ -1212,6 +1255,10 @@
                 image.close();
             }
         }
+
+        public void reset() {
+            imageAvailable.close();
+        }
     }
 
     private void validateImage(Size sz, int format, int captureCount,  boolean repeating)
diff --git a/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java b/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
index 59e89a2..e5cbf5e 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ImageWriterTest.java
@@ -17,6 +17,7 @@
 package android.hardware.camera2.cts;
 
 import static android.hardware.camera2.cts.CameraTestUtils.*;
+import static junit.framework.Assert.*;
 
 import android.graphics.ImageFormat;
 import android.graphics.SurfaceTexture;
@@ -39,6 +40,10 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.Test;
+
 /**
  * <p>
  * Basic test for ImageWriter APIs. ImageWriter takes the images produced by
@@ -46,6 +51,7 @@
  * interface or ImageReader.
  * </p>
  */
+@RunWith(Parameterized.class)
 public class ImageWriterTest extends Camera2AndroidTestCase {
     private static final String TAG = "ImageWriterTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -57,7 +63,7 @@
     private ImageWriter mWriter;
 
     @Override
-    protected void tearDown() throws Exception {
+    public void tearDown() throws Exception {
         try {
             closeImageReader(mReaderForWriter);
         } finally {
@@ -89,8 +95,9 @@
      * interface.</li>
      * </p>
      */
+    @Test
     public void testYuvImageWriterReaderOperation() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -111,8 +118,9 @@
      * factory method of ImageReader and ImageWriter.
      * </p>
      */
+    @Test
     public void testYuvImageWriterReaderOperationAlt() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -127,6 +135,7 @@
         }
     }
 
+    @Test
     public void testAbandonedSurfaceExceptions() throws Exception {
         final int READER_WIDTH = 1920;
         final int READER_HEIGHT = 1080;
@@ -171,6 +180,7 @@
         }
     }
 
+    @Test
     public void testWriterFormatOverride() throws Exception {
         int[] TEXTURE_TEST_FORMATS = {ImageFormat.YV12, ImageFormat.YUV_420_888};
         SurfaceTexture texture = new SurfaceTexture(/*random int*/1);
diff --git a/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java
index 7a2e339..27e6492 100644
--- a/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/LogicalCameraDeviceTest.java
@@ -66,6 +66,8 @@
 import java.util.Map;
 import java.util.Set;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 import static org.mockito.Mockito.*;
@@ -73,6 +75,7 @@
 /**
  * Tests exercising logical camera setup, configuration, and usage.
  */
+@RunWith(Parameterized.class)
 public final class LogicalCameraDeviceTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "LogicalCameraDeviceTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -107,7 +110,7 @@
      */
     @Test
     public void testInvalidPhysicalCameraIdInOutputConfiguration() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 if (mAllStaticInfo.get(id).isHardwareLevelLegacy()) {
@@ -167,7 +170,7 @@
     @Test
     public void testBasicPhysicalStreaming() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
@@ -209,7 +212,7 @@
     @Test
     public void testBasicLogicalPhysicalStreamCombination() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
@@ -331,7 +334,7 @@
     @Test
     public void testBasicPhysicalRequests() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
@@ -462,7 +465,7 @@
     @Test
     public void testInvalidPhysicalCameraRequests() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
@@ -569,7 +572,7 @@
     @Test
     public void testLogicalCameraZoomSwitch() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
@@ -708,7 +711,7 @@
      */
     @Test
     public void testActivePhysicalId() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
@@ -792,7 +795,7 @@
         if (!isHandheldDevice()) {
             return;
         }
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
 
diff --git a/tests/camera/src/android/hardware/camera2/cts/MultiViewTest.java b/tests/camera/src/android/hardware/camera2/cts/MultiViewTest.java
index 5c1f11e..fd081b3 100644
--- a/tests/camera/src/android/hardware/camera2/cts/MultiViewTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/MultiViewTest.java
@@ -50,11 +50,15 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 import org.junit.Test;
 
 /**
  * CameraDevice test by using combination of SurfaceView, TextureView and ImageReader
  */
+
+@RunWith(Parameterized.class)
 public class MultiViewTest extends Camera2MultiViewTestCase {
     private static final String TAG = "MultiViewTest";
     private final static long WAIT_FOR_COMMAND_TO_COMPLETE = 5000; //ms
@@ -67,7 +71,7 @@
 
     @Test
     public void testTextureViewPreview() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             Exception prior = null;
 
             try {
@@ -96,7 +100,7 @@
 
     @Test
     public void testTextureViewPreviewWithImageReader() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             Exception prior = null;
 
             ImageVerifierListener yuvListener;
@@ -144,7 +148,7 @@
 
     @Test
     public void testDualTextureViewPreview() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             Exception prior = null;
             try {
                 openCamera(cameraId);
@@ -177,7 +181,7 @@
 
     @Test
     public void testDualTextureViewAndImageReaderPreview() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             Exception prior = null;
 
             ImageVerifierListener yuvListener;
@@ -223,31 +227,31 @@
     @Test
     public void testDualCameraPreview() throws Exception {
         final int NUM_CAMERAS_TESTED = 2;
-        if (mCameraIds.length < NUM_CAMERAS_TESTED) {
+        if (mCameraIdsUnderTest.length < NUM_CAMERAS_TESTED) {
             return;
         }
 
         try {
             for (int i = 0; i < NUM_CAMERAS_TESTED; i++) {
-                openCamera(mCameraIds[i]);
-                if (!getStaticInfo(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                openCamera(mCameraIdsUnderTest[i]);
+                if (!getStaticInfo(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
                 List<TextureView> views = Arrays.asList(mTextureView[i]);
 
-                startTextureViewPreview(mCameraIds[i], views, /*ImageReader*/null);
+                startTextureViewPreview(mCameraIdsUnderTest[i], views, /*ImageReader*/null);
             }
             // TODO: check the framerate is correct
             SystemClock.sleep(PREVIEW_TIME_MS);
             for (int i = 0; i < NUM_CAMERAS_TESTED; i++) {
-                if (!getStaticInfo(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!getStaticInfo(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                stopPreview(mCameraIds[i]);
+                stopPreview(mCameraIdsUnderTest[i]);
             }
         } catch (BlockingOpenException e) {
             // The only error accepted is ERROR_MAX_CAMERAS_IN_USE, which means HAL doesn't support
@@ -257,7 +261,7 @@
             Log.i(TAG, "Camera HAL does not support dual camera preview. Skip the test");
         } finally {
             for (int i = 0; i < NUM_CAMERAS_TESTED; i++) {
-                closeCamera(mCameraIds[i]);
+                closeCamera(mCameraIdsUnderTest[i]);
             }
         }
     }
@@ -267,7 +271,7 @@
      */
     @Test
     public void testSharedSurfaceBasic() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             try {
                 openCamera(cameraId);
                 if (getStaticInfo(cameraId).isHardwareLevelLegacy()) {
@@ -409,7 +413,7 @@
      */
     @Test
     public void testSharedSurfaceImageReaderSwitch() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             try {
                 openCamera(cameraId);
                 if (getStaticInfo(cameraId).isHardwareLevelLegacy()) {
@@ -501,7 +505,7 @@
         int YUVFormats[] = {ImageFormat.YUV_420_888, ImageFormat.YUV_422_888,
             ImageFormat.YUV_444_888, ImageFormat.YUY2, ImageFormat.YV12,
             ImageFormat.NV16, ImageFormat.NV21};
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             try {
                 openCamera(cameraId);
                 if (getStaticInfo(cameraId).isHardwareLevelLegacy()) {
@@ -629,7 +633,7 @@
      */
     @Test
     public void testSharedSurfaceLimit() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             try {
                 openCamera(cameraId);
                 if (getStaticInfo(cameraId).isHardwareLevelLegacy()) {
@@ -747,7 +751,7 @@
      */
     @Test(timeout=60*60*1000) // timeout = 60 mins for long running tests
     public void testSharedSurfaceSwitch() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             try {
                 openCamera(cameraId);
                 if (getStaticInfo(cameraId).isHardwareLevelLegacy()) {
@@ -848,7 +852,7 @@
      */
     @Test
     public void testTextureImageWriterReaderOperation() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             ImageReader reader = null;
             ImageWriter writer = null;
             Surface writerOutput = null;
@@ -1037,7 +1041,7 @@
      */
     @Test
     public void testSharedSurfaces() throws Exception {
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             try {
                 openCamera(cameraId);
                 if (getStaticInfo(cameraId).isHardwareLevelLegacy()) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/NativeCameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/NativeCameraDeviceTest.java
index 291d998..207c3e3 100644
--- a/tests/camera/src/android/hardware/camera2/cts/NativeCameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/NativeCameraDeviceTest.java
@@ -22,14 +22,17 @@
 import android.util.Size;
 import android.view.Surface;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 import org.junit.Test;
 
 import static org.junit.Assert.assertTrue;
 
-
 /**
  * <p>Basic test for CameraManager class.</p>
  */
+
+@RunWith(Parameterized.class)
 public class NativeCameraDeviceTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "NativeCameraDeviceTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
diff --git a/tests/camera/src/android/hardware/camera2/cts/NativeCameraManagerTest.java b/tests/camera/src/android/hardware/camera2/cts/NativeCameraManagerTest.java
index 08e0363..0ed5f0e 100644
--- a/tests/camera/src/android/hardware/camera2/cts/NativeCameraManagerTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/NativeCameraManagerTest.java
@@ -16,13 +16,21 @@
 
 package android.hardware.camera2.cts;
 
-import android.test.AndroidTestCase;
+import android.hardware.cts.helpers.CameraParameterizedTestCase;
 import android.util.Log;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import static junit.framework.Assert.*;
+
 /**
  * <p>Basic test for CameraManager class.</p>
  */
-public class NativeCameraManagerTest extends AndroidTestCase {
+
+@RunWith(Parameterized.class)
+public class NativeCameraManagerTest extends CameraParameterizedTestCase {
     private static final String TAG = "NativeCameraManagerTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
 
@@ -33,21 +41,25 @@
         Log.i("NativeCameraManagerTest", "after loadlibrary");
     }
 
+    @Test
     public void testCameraManagerGetAndClose() {
         assertTrue("testCameraManagerGetAndClose fail, see log for details",
                 testCameraManagerGetAndCloseNative());
     }
 
+    @Test
     public void testCameraManagerGetCameraIds() {
         assertTrue("testCameraManagerGetCameraIds fail, see log for details",
                 testCameraManagerGetCameraIdsNative());
     }
 
+    @Test
     public void testCameraManagerAvailabilityCallback() {
         assertTrue("testCameraManagerAvailabilityCallback fail, see log for details",
                 testCameraManagerAvailabilityCallbackNative());
     }
 
+    @Test
     public void testCameraManagerCameraCharacteristics() {
         assertTrue("testCameraManagerCameraCharacteristics fail, see log for details",
                 testCameraManagerCharacteristicsNative());
diff --git a/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java b/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
index 0933363..493e670 100644
--- a/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
@@ -19,9 +19,16 @@
 import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
 import android.util.Log;
 
+import org.junit.Test;
+
+import static junit.framework.Assert.*;
+
 /**
  * <p>Basic test for CameraManager class.</p>
  */
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+@RunWith(Parameterized.class)
 public class NativeImageReaderTest extends Camera2AndroidTestCase {
     private static final String TAG = "NativeImageReaderTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -33,26 +40,31 @@
         Log.i("NativeImageReaderTest", "after loadlibrary");
     }
 
+    @Test
     public void testJpeg() {
         assertTrue("testJpeg fail, see log for details",
                 testJpegNative(mDebugFileNameBase));
     }
 
+    @Test
     public void testY8() {
         assertTrue("testY8 fail, see log for details",
                 testY8Native(mDebugFileNameBase));
     }
 
+    @Test
     public void testHeic() {
         assertTrue("testHeic fail, see log for details",
                 testHeicNative(mDebugFileNameBase));
     }
 
+    @Test
     public void testDepthJpeg() {
         assertTrue("testDepthJpeg fail, see log for details",
                 testDepthJpegNative(mDebugFileNameBase));
     }
 
+    @Test
     public void testImageReaderCloseAcquiredImages() {
         assertTrue("testImageReaderClose fail, see log for details",
                 testImageReaderCloseAcquiredImagesNative());
diff --git a/tests/camera/src/android/hardware/camera2/cts/NativeStillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/NativeStillCaptureTest.java
index a892970..a778f7d 100644
--- a/tests/camera/src/android/hardware/camera2/cts/NativeStillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/NativeStillCaptureTest.java
@@ -21,6 +21,8 @@
 import android.util.Size;
 import android.view.Surface;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 import static org.junit.Assert.assertTrue;
@@ -28,6 +30,8 @@
 /**
  * <p>Basic test for CameraManager class.</p>
  */
+
+@RunWith(Parameterized.class)
 public class NativeStillCaptureTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "NativeStillCaptureTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
diff --git a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
index 2d6cb0a..0616433 100644
--- a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
@@ -36,7 +36,7 @@
 import android.hardware.camera2.cts.CameraTestUtils.SimpleImageReaderListener;
 import android.hardware.camera2.cts.helpers.StaticMetadata;
 import android.hardware.camera2.cts.helpers.StaticMetadata.CheckLevel;
-import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
+import android.hardware.camera2.cts.testcases.Camera2AndroidBasicTestCase;
 import android.hardware.camera2.params.InputConfiguration;
 import android.hardware.camera2.params.StreamConfigurationMap;
 import android.media.Image;
@@ -71,7 +71,7 @@
  * Test camera2 API use case performance KPIs, such as camera open time, session creation time,
  * shutter lag etc. The KPI data will be reported in cts results.
  */
-public class PerformanceTest extends Camera2AndroidTestCase {
+public class PerformanceTest extends Camera2AndroidBasicTestCase {
     private static final String TAG = "PerformanceTest";
     private static final String REPORT_LOG_NAME = "CtsCameraTestCases";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -133,10 +133,10 @@
      * </p>
      */
     public void testCameraLaunch() throws Exception {
-        double[] avgCameraLaunchTimes = new double[mCameraIds.length];
+        double[] avgCameraLaunchTimes = new double[mCameraIdsUnderTest.length];
 
         int counter = 0;
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             // Do NOT move these variables to outer scope
             // They will be passed to DeviceReportLog and their references will be stored
             String streamName = "test_camera_launch";
@@ -259,7 +259,7 @@
                         + ". Max(ms): " + Stat.getMax(cameraLaunchTimes));
             }
         }
-        if (mCameraIds.length != 0) {
+        if (mCameraIdsUnderTest.length != 0) {
             String streamName = "test_camera_launch_average";
             mReportLog = new DeviceReportLog(REPORT_LOG_NAME, streamName);
             mReportLog.setSummary("camera_launch_average_time_for_all_cameras",
@@ -309,10 +309,10 @@
 
     private void testSingleCaptureForFormat(int[] formats, String formatDescription,
             boolean addPreviewDelay) throws Exception {
-        double[] avgResultTimes = new double[mCameraIds.length];
+        double[] avgResultTimes = new double[mCameraIdsUnderTest.length];
 
         int counter = 0;
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             // Do NOT move these variables to outer scope
             // They will be passed to DeviceReportLog and their references will be stored
             String streamName = appendFormatDescription("test_single_capture", formatDescription);
@@ -448,7 +448,7 @@
         }
 
         // Result will not be reported in CTS report if no summary is printed.
-        if (mCameraIds.length != 0) {
+        if (mCameraIdsUnderTest.length != 0) {
             String streamName = appendFormatDescription("test_single_capture_average",
                     formatDescription);
             mReportLog = new DeviceReportLog(REPORT_LOG_NAME, streamName);
@@ -470,8 +470,8 @@
      * </p>
      */
     public void testMultipleCapture() throws Exception {
-        double[] avgResultTimes = new double[mCameraIds.length];
-        double[] avgDurationMs = new double[mCameraIds.length];
+        double[] avgResultTimes = new double[mCameraIdsUnderTest.length];
+        double[] avgDurationMs = new double[mCameraIdsUnderTest.length];
 
         // A simple CaptureSession StateCallback to handle onCaptureQueueEmpty
         class MultipleCaptureStateCallback extends CameraCaptureSession.StateCallback {
@@ -520,7 +520,7 @@
         final MultipleCaptureStateCallback sessionListener = new MultipleCaptureStateCallback();
 
         int counter = 0;
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             // Do NOT move these variables to outer scope
             // They will be passed to DeviceReportLog and their references will be stored
             String streamName = "test_multiple_capture";
@@ -657,7 +657,7 @@
         }
 
         // Result will not be reported in CTS report if no summary is printed.
-        if (mCameraIds.length != 0) {
+        if (mCameraIdsUnderTest.length != 0) {
             String streamName = "test_multiple_capture_average";
             mReportLog = new DeviceReportLog(REPORT_LOG_NAME, streamName);
             mReportLog.setSummary("camera_multiple_capture_result_average_latency_for_all_cameras",
@@ -675,7 +675,7 @@
      * a reprocess request is issued to the time the reprocess image is returned.
      */
     public void testReprocessingLatency() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             for (int format : REPROCESS_FORMATS) {
                 if (!isReprocessSupported(id, format)) {
                     continue;
@@ -705,7 +705,7 @@
      *
      */
     public void testReprocessingThroughput() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             for (int format : REPROCESS_FORMATS) {
                 if (!isReprocessSupported(id, format)) {
                     continue;
@@ -734,7 +734,7 @@
      * time a reprocess request is issued to the time the reprocess image is returned.
      */
     public void testHighQualityReprocessingLatency() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             for (int format : REPROCESS_FORMATS) {
                 if (!isReprocessSupported(id, format)) {
                     continue;
@@ -764,7 +764,7 @@
      *
      */
     public void testHighQualityReprocessingThroughput() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             for (int format : REPROCESS_FORMATS) {
                 if (!isReprocessSupported(id, format)) {
                     continue;
@@ -792,7 +792,7 @@
      * Testing reprocessing caused preview stall (frame drops)
      */
     public void testReprocessingCaptureStall() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             for (int format : REPROCESS_FORMATS) {
                 if (!isReprocessSupported(id, format)) {
                     continue;
diff --git a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
index c61071e..30d1943 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
@@ -55,6 +55,8 @@
 
 import junit.framework.AssertionFailedError;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 import java.io.File;
@@ -69,6 +71,7 @@
  * MediaCodec.
  */
 @LargeTest
+@RunWith(Parameterized.class)
 public class RecordingTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "RecordingTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -131,25 +134,25 @@
 
     private void doBasicRecording(boolean useVideoStab, boolean useIntermediateSurface)
             throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing basic recording for camera " + mCameraIds[i]);
-                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIds[i]);
+                Log.i(TAG, "Testing basic recording for camera " + mCameraIdsUnderTest[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
                 if (!staticInfo.isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
 
                 // External camera doesn't support CamcorderProfile recording
                 if (staticInfo.isExternalCamera()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support CamcorderProfile, skipping");
                     continue;
                 }
 
                 if (!staticInfo.isVideoStabilizationSupported() && useVideoStab) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support video stabilization, skipping the stabilization"
                             + " test");
                     continue;
@@ -157,8 +160,8 @@
 
                 // Re-use the MediaRecorder object for the same camera device.
                 mMediaRecorder = new MediaRecorder();
-                openDevice(mCameraIds[i]);
-                initSupportedVideoSize(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
+                initSupportedVideoSize(mCameraIdsUnderTest[i]);
 
                 basicRecordingTestByCamera(mCamcorderProfileList, useVideoStab,
                         useIntermediateSurface);
@@ -256,19 +259,19 @@
      */
     @Test(timeout=60*60*1000) // timeout = 60 mins for long running tests
     public void testSupportedVideoSizes() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing supported video size recording for camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                Log.i(TAG, "Testing supported video size recording for camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
                 // Re-use the MediaRecorder object for the same camera device.
                 mMediaRecorder = new MediaRecorder();
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
 
-                initSupportedVideoSize(mCameraIds[i]);
+                initSupportedVideoSize(mCameraIdsUnderTest[i]);
 
                 recordingSizeTestByCamera();
             } finally {
@@ -357,7 +360,7 @@
 
     @Test
     public void testAbandonedHighSpeedRequest() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing bad suface for createHighSpeedRequestList for camera " + id);
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
@@ -479,25 +482,25 @@
      */
     @Test
     public void testRecordingFramerateLowToHigh() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing basic recording for camera " + mCameraIds[i]);
-                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIds[i]);
+                Log.i(TAG, "Testing recording framerate low to high for camera " + mCameraIdsUnderTest[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
                 if (!staticInfo.isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
                 if (staticInfo.isExternalCamera()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support CamcorderProfile, skipping");
                     continue;
                 }
                 // Re-use the MediaRecorder object for the same camera device.
                 mMediaRecorder = new MediaRecorder();
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
 
-                initSupportedVideoSize(mCameraIds[i]);
+                initSupportedVideoSize(mCameraIdsUnderTest[i]);
 
                 int minFpsProfileId = -1, minFps = 1000;
                 int maxFpsProfileId = -1, maxFps = 0;
@@ -534,23 +537,23 @@
      */
     @Test
     public void testVideoPreviewSurfaceSharing() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIds[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
                 if (staticInfo.isHardwareLevelLegacy()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] + " is legacy, skipping");
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] + " is legacy, skipping");
                     continue;
                 }
                 if (!staticInfo.isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
                 // Re-use the MediaRecorder object for the same camera device.
                 mMediaRecorder = new MediaRecorder();
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
 
-                initSupportedVideoSize(mCameraIds[i]);
+                initSupportedVideoSize(mCameraIdsUnderTest[i]);
 
                 videoPreviewSurfaceSharingTestByCamera();
             } finally {
@@ -561,6 +564,128 @@
     }
 
     /**
+     * <p>
+     * Test recording with same recording surface and different preview surfaces.
+     * </p>
+     * <p>
+     * This test maintains persistent video surface while changing preview surface.
+     * This exercises format/dataspace override behavior of the camera device.
+     * </p>
+     */
+    @Test
+    public void testRecordingWithDifferentPreviewSizes() throws Exception {
+        if (!MediaUtils.checkCodecForDomain(true /* encoder */, "video")) {
+            return; // skipped
+        }
+        mPersistentSurface = MediaCodec.createPersistentInputSurface();
+        assertNotNull("Failed to create persistent input surface!", mPersistentSurface);
+
+        try {
+            doRecordingWithDifferentPreviewSizes();
+        } finally {
+            mPersistentSurface.release();
+            mPersistentSurface = null;
+        }
+    }
+
+    public void doRecordingWithDifferentPreviewSizes() throws Exception {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
+            try {
+                Log.i(TAG, "Testing recording with different preview sizes for camera " +
+                        mCameraIdsUnderTest[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
+                if (!staticInfo.isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
+                            " does not support color outputs, skipping");
+                    continue;
+                }
+                if (staticInfo.isExternalCamera()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
+                            " does not support CamcorderProfile, skipping");
+                    continue;
+                }
+                // Re-use the MediaRecorder object for the same camera device.
+                mMediaRecorder = new MediaRecorder();
+                openDevice(mCameraIdsUnderTest[i]);
+
+                initSupportedVideoSize(mCameraIdsUnderTest[i]);
+
+                Size maxPreviewSize = mOrderedPreviewSizes.get(0);
+                List<Range<Integer> > fpsRanges = Arrays.asList(
+                        mStaticInfo.getAeAvailableTargetFpsRangesChecked());
+                int cameraId = Integer.valueOf(mCamera.getId());
+                int maxVideoFrameRate = -1;
+                for (int profileId : mCamcorderProfileList) {
+                    if (!CamcorderProfile.hasProfile(cameraId, profileId)) {
+                        continue;
+                    }
+                    CamcorderProfile profile = CamcorderProfile.get(cameraId, profileId);
+
+                    Size videoSz = new Size(profile.videoFrameWidth, profile.videoFrameHeight);
+                    Range<Integer> fpsRange = new Range(
+                            profile.videoFrameRate, profile.videoFrameRate);
+                    if (maxVideoFrameRate < profile.videoFrameRate) {
+                        maxVideoFrameRate = profile.videoFrameRate;
+                    }
+
+                    if (allowedUnsupported(cameraId, profileId)) {
+                        continue;
+                    }
+
+                    if (mStaticInfo.isHardwareLevelLegacy() &&
+                            (videoSz.getWidth() > maxPreviewSize.getWidth() ||
+                             videoSz.getHeight() > maxPreviewSize.getHeight())) {
+                        // Skip. Legacy mode can only do recording up to max preview size
+                        continue;
+                    }
+                    assertTrue("Video size " + videoSz.toString() + " for profile ID " + profileId +
+                                    " must be one of the camera device supported video size!",
+                                    mSupportedVideoSizes.contains(videoSz));
+                    assertTrue("Frame rate range " + fpsRange + " (for profile ID " + profileId +
+                            ") must be one of the camera device available FPS range!",
+                            fpsRanges.contains(fpsRange));
+
+                    // Configure preview and recording surfaces.
+                    mOutMediaFileName = mDebugFileNameBase + "/test_video_surface_reconfig.mp4";
+
+                    // prepare preview surface by using video size.
+                    List<Size> previewSizes = getPreviewSizesForVideo(videoSz,
+                            profile.videoFrameRate);
+                    if (previewSizes.size() <= 1) {
+                        continue;
+                    }
+
+                    // 1. Do video recording using largest compatbile preview sizes
+                    prepareRecordingWithProfile(profile);
+                    updatePreviewSurface(previewSizes.get(0));
+                    SimpleCaptureCallback resultListener = new SimpleCaptureCallback();
+                    startRecording(
+                            /* useMediaRecorder */true, resultListener,
+                            /*useVideoStab*/false, fpsRange, false);
+                    SystemClock.sleep(RECORDING_DURATION_MS);
+                    stopRecording(/* useMediaRecorder */true, /* useIntermediateSurface */false,
+                            /* stopStreaming */false);
+
+                    // 2. Reconfigure with the same recording surface, but switch to a smaller
+                    // preview size.
+                    prepareRecordingWithProfile(profile);
+                    updatePreviewSurface(previewSizes.get(1));
+                    SimpleCaptureCallback resultListener2 = new SimpleCaptureCallback();
+                    startRecording(
+                            /* useMediaRecorder */true, resultListener2,
+                            /*useVideoStab*/false, fpsRange, false);
+                    SystemClock.sleep(RECORDING_DURATION_MS);
+                    stopRecording(/* useMediaRecorder */true);
+                    break;
+                }
+            } finally {
+                closeDevice();
+                releaseRecorder();
+            }
+        }
+    }
+
+    /**
      * Test camera preview and video surface sharing for maximum supported size.
      */
     private void videoPreviewSurfaceSharingTestByCamera() throws Exception {
@@ -652,7 +777,7 @@
      * </p>
      */
     private void slowMotionRecording() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing slow motion recording for camera " + id);
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
@@ -727,7 +852,7 @@
     }
 
     private void constrainedHighSpeedRecording() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing constrained high speed recording for camera " + id);
 
@@ -1027,7 +1152,8 @@
             SystemClock.sleep(RECORDING_DURATION_MS);
 
             // Stop recording and preview
-            stopRecording(/* useMediaRecorder */true, useIntermediateSurface);
+            stopRecording(/* useMediaRecorder */true, useIntermediateSurface,
+                    /* stopCameraStreaming */false);
             // Convert number of frames camera produced into the duration in unit of ms.
             float frameDurationMs = 1000.0f / profile.videoFrameRate;
             float durationMs = 0.f;
@@ -1142,7 +1268,7 @@
      * Simple wrapper to wrap normal/burst video snapshot tests
      */
     private void videoSnapshotHelper(boolean burstTest) throws Exception {
-            for (String id : mCameraIds) {
+            for (String id : mCameraIdsUnderTest) {
                 try {
                     Log.i(TAG, "Testing video snapshot for camera " + id);
 
@@ -1478,15 +1604,14 @@
     }
 
     /**
-     * Update preview size with video size.
+     * Find compatible preview sizes for video size and framerate.
      *
      * <p>Preview size will be capped with max preview size.</p>
      *
      * @param videoSize The video size used for preview.
      * @param videoFrameRate The video frame rate
-     *
      */
-    private void updatePreviewSurfaceWithVideo(Size videoSize, int videoFrameRate) {
+    private List<Size> getPreviewSizesForVideo(Size videoSize, int videoFrameRate) {
         if (mOrderedPreviewSizes == null) {
             throw new IllegalStateException("supported preview size list is not initialized yet");
         }
@@ -1496,7 +1621,7 @@
         HashMap<Size, Long> minFrameDurationMap = mStaticInfo.
                 getAvailableMinFrameDurationsForFormatChecked(ImageFormat.PRIVATE);
         Size maxPreviewSize = mOrderedPreviewSizes.get(0);
-        Size previewSize = null;
+        ArrayList<Size> previewSizes = new ArrayList<>();
         if (videoSize.getWidth() > maxPreviewSize.getWidth() ||
                 videoSize.getHeight() > maxPreviewSize.getHeight()) {
             for (Size s : mOrderedPreviewSizes) {
@@ -1510,18 +1635,32 @@
                 if (frameDuration <= videoFrameDuration &&
                         s.getWidth() <= videoSize.getWidth() &&
                         s.getHeight() <= videoSize.getHeight()) {
-                    Log.w(TAG, "Overwrite preview size from " + videoSize.toString() +
-                            " to " + s.toString());
-                    previewSize = s;
-                    break;
-                    // If all preview size doesn't work then we fallback to video size
+                    Log.v(TAG, "Add preview size " + s.toString() + " for video size " +
+                            videoSize.toString());
+                    previewSizes.add(s);
                 }
             }
         }
-        if (previewSize == null) {
-            previewSize = videoSize;
+
+        if (previewSizes.isEmpty()) {
+            previewSizes.add(videoSize);
         }
-        updatePreviewSurface(previewSize);
+
+        return previewSizes;
+    }
+
+    /**
+     * Update preview size with video size.
+     *
+     * <p>Preview size will be capped with max preview size.</p>
+     *
+     * @param videoSize The video size used for preview.
+     * @param videoFrameRate The video frame rate
+     *
+     */
+    private void updatePreviewSurfaceWithVideo(Size videoSize, int videoFrameRate) {
+        List<Size> previewSizes = getPreviewSizesForVideo(videoSize, videoFrameRate);
+        updatePreviewSurface(previewSizes.get(0));
     }
 
     private void prepareRecordingWithProfile(CamcorderProfile profile) throws Exception {
@@ -1734,15 +1873,18 @@
     }
 
     private int stopRecording(boolean useMediaRecorder) throws Exception {
-        return stopRecording(useMediaRecorder, false);
+        return stopRecording(useMediaRecorder, /*useIntermediateSurface*/false,
+                /*stopStreaming*/true);
     }
 
     // Stop recording and return the estimated video duration in milliseconds.
-    private int stopRecording(boolean useMediaRecorder, boolean useIntermediateSurface)
-            throws Exception {
+    private int stopRecording(boolean useMediaRecorder, boolean useIntermediateSurface,
+            boolean stopStreaming) throws Exception {
         long stopRecordingTime = SystemClock.elapsedRealtime();
         if (useMediaRecorder) {
-            stopCameraStreaming();
+            if (stopStreaming) {
+                stopCameraStreaming();
+            }
             if (useIntermediateSurface) {
                 mIntermediateReader.setOnImageAvailableListener(null, null);
                 mQueuer.expectInvalidSurface();
diff --git a/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
index bdf98f5..e59b161 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
@@ -43,11 +43,15 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 /**
  * <p>Tests for Reprocess API.</p>
  */
+
+@RunWith(Parameterized.class)
 public class ReprocessCaptureTest extends Camera2SurfaceViewTestCase  {
     private static final String TAG = "ReprocessCaptureTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -90,7 +94,7 @@
      */
     @Test
     public void testBasicYuvToYuvReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id)) {
                 continue;
             }
@@ -105,7 +109,7 @@
      */
     @Test
     public void testBasicYuvToJpegReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id)) {
                 continue;
             }
@@ -120,7 +124,7 @@
      */
     @Test
     public void testBasicYuvToHeicReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id)) {
                 continue;
             }
@@ -138,7 +142,7 @@
      */
     @Test
     public void testBasicOpaqueToYuvReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -153,7 +157,7 @@
      */
     @Test
     public void testBasicOpaqueToJpegReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -168,7 +172,7 @@
      */
     @Test
     public void testBasicOpaqueToHeicReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -186,7 +190,7 @@
      */
     @Test(timeout=400*60*1000) // timeout = 400 mins for long running reprocessing tests
     public void testReprocessingSizeFormat() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -208,7 +212,7 @@
      */
     @Test(timeout=400*60*1000) // timeout = 400 mins for long running reprocessing tests
     public void testReprocessingSizeFormatWithPreview() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -229,7 +233,7 @@
      */
     @Test
     public void testRecreateReprocessingSessions() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -267,7 +271,7 @@
      */
     @Test
     public void testCrossSessionCaptureException() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             // Test one supported input format -> JPEG
             int inputFormat;
             int reprocessOutputFormat = ImageFormat.JPEG;
@@ -333,11 +337,78 @@
     }
 
     /**
+     * Verify queued input images are cleared in new reprocessable capture session.
+     *
+     * This tests the case where an application receives onCaptureBufferLost() for an
+     * output stream, resulting in pending input buffers not having corresponding request.
+     *
+     * For subsequent new reprocessable capture session, ImageWriter.queueInputBuffer may become
+     * stuck due to stale buffers from previous session.
+     */
+    @Test
+    public void testQueueImageWithoutRequest() throws Exception {
+        final int MAX_IMAGES = 1;
+        final int ITERATIONS = MAX_IMAGES + 3;
+        for (String id : mCameraIdsUnderTest) {
+            // Test one supported input format -> JPEG
+            int inputFormat;
+            int reprocessOutputFormat = ImageFormat.JPEG;
+
+            if (isOpaqueReprocessSupported(id)) {
+                inputFormat = ImageFormat.PRIVATE;
+            } else if (isYuvReprocessSupported(id)) {
+                inputFormat = ImageFormat.YUV_420_888;
+            } else {
+                continue;
+            }
+
+            openDevice(id);
+
+            // Test the largest sizes
+            Size inputSize =
+                    getMaxSize(inputFormat, StaticMetadata.StreamDirection.Input);
+            Size reprocessOutputSize =
+                    getMaxSize(reprocessOutputFormat, StaticMetadata.StreamDirection.Output);
+
+            try {
+                if (VERBOSE) {
+                    Log.v(TAG, "testQueueImageWithoutRequest: cameraId: " + id +
+                            " inputSize: " + inputSize + " inputFormat: " + inputFormat +
+                            " reprocessOutputSize: " + reprocessOutputSize +
+                            " reprocessOutputFormat: " + reprocessOutputFormat);
+                }
+
+                setupImageReaders(inputSize, inputFormat, reprocessOutputSize,
+                        reprocessOutputFormat, MAX_IMAGES);
+
+                for (int i = 0; i < ITERATIONS; i++) {
+                    setupReprocessableSession(/*previewSurface*/null, /*numImageWriterImages*/1);
+
+                    TotalCaptureResult result = submitCaptureRequest(mFirstImageReader.getSurface(),
+                            /*inputResult*/null);
+                    Image image = mFirstImageReaderListener.getImage(CAPTURE_TIMEOUT_MS);
+
+                    // queue the image to image writer
+                    mImageWriter.queueInputImage(image);
+
+                    mInputSurface = null;
+                    mImageWriter.close();
+                    mImageWriter = null;
+                }
+            } finally {
+                closeReprossibleSession();
+                closeImageReaders();
+                closeDevice();
+            }
+        }
+    }
+
+    /**
      * Test burst reprocessing captures with and without preview.
      */
     @Test(timeout=400*60*1000) // timeout = 400 mins for long running reprocessing tests
     public void testBurstReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -361,7 +432,7 @@
      */
     @Test(timeout=400*60*1000) // timeout = 400 mins for long running reprocessing tests
     public void testMixedBurstReprocessing() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -387,7 +458,7 @@
      */
     @Test
     public void testReprocessAbort() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -417,7 +488,7 @@
      */
     @Test
     public void testReprocessTimestamps() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -448,7 +519,7 @@
      */
     @Test
     public void testReprocessJpegExif() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
@@ -479,7 +550,7 @@
 
     @Test
     public void testReprocessRequestKeys() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             if (!isYuvReprocessSupported(id) && !isOpaqueReprocessSupported(id)) {
                 continue;
             }
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index d108600e..e2bbb9c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -54,12 +54,18 @@
 import java.util.Map;
 import java.util.Set;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
 import static junit.framework.Assert.assertTrue;
 import static org.mockito.Mockito.*;
 
 /**
  * Tests exercising edge cases in camera setup, configuration, and usage.
  */
+
+@RunWith(Parameterized.class)
 public class RobustnessTest extends Camera2AndroidTestCase {
     private static final String TAG = "RobustnessTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -79,8 +85,9 @@
      * this surface are expected have the dimensions of the closest possible buffer size in the
      * available stream configurations for a surface with this format.
      */
+    @Test
     public void testBadSurfaceDimensions() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Camera " + id);
                 openDevice(id);
@@ -160,8 +167,9 @@
     /**
      * Test for making sure the mandatory stream combinations work as expected.
      */
+    @Test
     public void testMandatoryOutputCombinations() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             openDevice(id);
             MandatoryStreamCombination[] combinations =
                     mStaticInfo.getCharacteristics().get(
@@ -186,7 +194,7 @@
                     Set<String> physicalCameraIds =
                             mStaticInfo.getCharacteristics().getPhysicalCameraIds();
                     for (String physicalId : physicalCameraIds) {
-                        if (Arrays.asList(mCameraIds).contains(physicalId)) {
+                        if (Arrays.asList(mCameraIdsUnderTest).contains(physicalId)) {
                             // If physicalId is advertised in camera ID list, do not need to test
                             // its stream combination through logical camera.
                             continue;
@@ -480,8 +488,9 @@
      * Test for making sure the required reprocess input/output combinations for each hardware
      * level and capability work as expected.
      */
+    @Test
     public void testMandatoryReprocessConfigurations() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             openDevice(id);
             MandatoryStreamCombination[] combinations =
                     mStaticInfo.getCharacteristics().get(
@@ -716,9 +725,10 @@
         }
     }
 
+    @Test
     public void testBasicTriggerSequence() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s", id));
 
             try {
@@ -856,8 +866,9 @@
 
     }
 
+    @Test
     public void testSimultaneousTriggers() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s", id));
 
             try {
@@ -958,8 +969,9 @@
         }
     }
 
+    @Test
     public void testAfThenAeTrigger() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s", id));
 
             try {
@@ -1074,8 +1086,9 @@
         }
     }
 
+    @Test
     public void testAeThenAfTrigger() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s", id));
 
             try {
@@ -1190,9 +1203,10 @@
         }
     }
 
+    @Test
     public void testAeAndAfCausality() throws Exception {
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s", id));
 
             try {
@@ -1372,8 +1386,9 @@
 
     }
 
+    @Test
     public void testAbandonRepeatingRequestSurface() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format(
                     "Testing Camera %s for abandoning surface of a repeating request", id));
 
@@ -1441,8 +1456,9 @@
         }
     }
 
+    @Test
     public void testConfigureAbandonedSurface() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format(
                     "Testing Camera %s for configuring abandoned surface", id));
 
@@ -1498,10 +1514,11 @@
         }
     }
 
+    @Test
     public void testAfSceneChange() throws Exception {
         final int NUM_FRAMES_VERIFIED = 3;
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s for AF scene change", id));
 
             StaticMetadata staticInfo =
@@ -1548,10 +1565,11 @@
         }
     }
 
+    @Test
     public void testOisDataMode() throws Exception {
         final int NUM_FRAMES_VERIFIED = 3;
 
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             Log.i(TAG, String.format("Testing Camera %s for OIS mode", id));
 
             StaticMetadata staticInfo =
diff --git a/tests/camera/src/android/hardware/camera2/cts/StaticMetadataTest.java b/tests/camera/src/android/hardware/camera2/cts/StaticMetadataTest.java
index b56fcbf..1ffa501 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StaticMetadataTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StaticMetadataTest.java
@@ -41,6 +41,13 @@
 import java.util.List;
 import java.util.Set;
 
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
 /**
  * <p>
  * This class covers the {@link CameraCharacteristics} tests that are not
@@ -50,6 +57,8 @@
  * Note that most of the tests in this class don't require camera open.
  * </p>
  */
+
+@RunWith(Parameterized.class)
 public class StaticMetadataTest extends Camera2AndroidTestCase {
     private static final String TAG = "StaticMetadataTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -59,6 +68,7 @@
     /**
      * Test the available capability for different hardware support level devices.
      */
+    @Test
     public void testHwSupportedLevel() throws Exception {
         Key<StreamConfigurationMap> key =
                 CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP;
@@ -135,6 +145,7 @@
     /**
      * Test max number of output stream reported by device
      */
+    @Test
     public void testMaxNumOutputStreams() throws Exception {
         for (String id : mAllCameraIds) {
             initStaticMetadata(id);
@@ -163,6 +174,7 @@
     /**
      * Test advertised capability does match available keys and vice versa
      */
+    @Test
     public void testCapabilities() throws Exception {
         for (String id : mAllCameraIds) {
             initStaticMetadata(id);
@@ -533,6 +545,7 @@
     /**
      * Test lens facing.
      */
+    @Test
     public void testLensFacing() throws Exception {
         for (String id : mAllCameraIds) {
             initStaticMetadata(id);
diff --git a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
index e8d2812..25fde0e 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -57,8 +57,11 @@
 
 import junit.framework.Assert;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
+@RunWith(Parameterized.class)
 public class StillCaptureTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "StillCaptureTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -91,15 +94,15 @@
      */
     @Test
     public void testJpegExif() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing JPEG exif for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                Log.i(TAG, "Testing JPEG exif for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 Size maxJpegSize = mOrderedStillSizes.get(0);
                 stillExifTestByCamera(ImageFormat.JPEG, maxJpegSize);
             } finally {
@@ -114,25 +117,25 @@
      */
     @Test
     public void testHeicExif() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing HEIC exif for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                Log.i(TAG, "Testing HEIC exif for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                if (!mAllStaticInfo.get(mCameraIds[i]).isHeicSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isHeicSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support HEIC, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
 
                 // Test maximum Heic size capture
                 List<Size> orderedHeicSizes = CameraTestUtils.getSupportedHeicSizes(
-                        mCameraIds[i], mCameraManager, null/*bound*/);
+                        mCameraIdsUnderTest[i], mCameraManager, null/*bound*/);
                 Size maxHeicSize = orderedHeicSizes.get(0);
                 stillExifTestByCamera(ImageFormat.HEIC, maxHeicSize);
 
@@ -152,25 +155,25 @@
      */
     @Test
     public void testDynamicDepthCapture() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing dynamic depth for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                Log.i(TAG, "Testing dynamic depth for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                if (!mAllStaticInfo.get(mCameraIds[i]).isDepthJpegSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isDepthJpegSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support dynamic depth, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
 
                 // Check the maximum supported size.
                 List<Size> orderedDepthJpegSizes = CameraTestUtils.getSortedSizesForFormat(
-                        mCameraIds[i], mCameraManager, ImageFormat.DEPTH_JPEG, null/*bound*/);
+                        mCameraIdsUnderTest[i], mCameraManager, ImageFormat.DEPTH_JPEG, null/*bound*/);
                 Size maxDepthJpegSize = orderedDepthJpegSizes.get(0);
                 stillDynamicDepthTestByCamera(ImageFormat.DEPTH_JPEG, maxDepthJpegSize);
             } finally {
@@ -192,7 +195,7 @@
      */
     @Test
     public void testTakePicture() throws Exception{
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing basic take picture for Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -220,7 +223,7 @@
      */
     @Test
     public void testTakePictureZsl() throws Exception{
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing basic ZSL take picture for Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -246,18 +249,18 @@
      */
     @Test
     public void testBasicRawCapture()  throws Exception {
-       for (int i = 0; i < mCameraIds.length; i++) {
+       for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
            try {
-               Log.i(TAG, "Testing raw capture for Camera " + mCameraIds[i]);
+               Log.i(TAG, "Testing raw capture for Camera " + mCameraIdsUnderTest[i]);
 
-               if (!mAllStaticInfo.get(mCameraIds[i]).isCapabilitySupported(
+               if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isCapabilitySupported(
                        CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
-                   Log.i(TAG, "RAW capability is not supported in camera " + mCameraIds[i] +
+                   Log.i(TAG, "RAW capability is not supported in camera " + mCameraIdsUnderTest[i] +
                            ". Skip the test.");
                    continue;
                }
 
-               openDevice(mCameraIds[i]);
+               openDevice(mCameraIdsUnderTest[i]);
                rawCaptureTestByCamera(/*stillRequest*/null);
            } finally {
                closeDevice();
@@ -271,17 +274,17 @@
      */
     @Test
     public void testBasicRawZslCapture()  throws Exception {
-       for (int i = 0; i < mCameraIds.length; i++) {
+       for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
            try {
-               Log.i(TAG, "Testing raw ZSL capture for Camera " + mCameraIds[i]);
+               Log.i(TAG, "Testing raw ZSL capture for Camera " + mCameraIdsUnderTest[i]);
 
-               if (!mAllStaticInfo.get(mCameraIds[i]).isCapabilitySupported(
+               if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isCapabilitySupported(
                        CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
-                   Log.i(TAG, "RAW capability is not supported in camera " + mCameraIds[i] +
+                   Log.i(TAG, "RAW capability is not supported in camera " + mCameraIdsUnderTest[i] +
                            ". Skip the test.");
                    continue;
                }
-               openDevice(mCameraIds[i]);
+               openDevice(mCameraIdsUnderTest[i]);
                CaptureRequest.Builder stillRequest =
                        mCamera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
                stillRequest.set(CaptureRequest.CONTROL_ENABLE_ZSL, true);
@@ -304,17 +307,17 @@
      */
     @Test
     public void testFullRawCapture() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing raw+JPEG capture for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isCapabilitySupported(
+                Log.i(TAG, "Testing raw+JPEG capture for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isCapabilitySupported(
                         CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
-                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIds[i] +
+                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIdsUnderTest[i] +
                             ". Skip the test.");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 fullRawCaptureTestByCamera(/*stillRequest*/null);
             } finally {
                 closeDevice();
@@ -333,16 +336,16 @@
      */
     @Test
     public void testFullRawZSLCapture() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing raw+JPEG ZSL capture for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isCapabilitySupported(
+                Log.i(TAG, "Testing raw+JPEG ZSL capture for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isCapabilitySupported(
                         CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
-                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIds[i] +
+                    Log.i(TAG, "RAW capability is not supported in camera " + mCameraIdsUnderTest[i] +
                             ". Skip the test.");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 CaptureRequest.Builder stillRequest =
                         mCamera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
                 stillRequest.set(CaptureRequest.CONTROL_ENABLE_ZSL, true);
@@ -364,7 +367,7 @@
      */
     @Test
     public void testTouchForFocus() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing touch for focus for Camera " + id);
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
@@ -395,7 +398,7 @@
      */
     @Test(timeout=60*60*1000) // timeout = 60 mins for long running tests
     public void testStillPreviewCombination() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing Still preview capture combination for Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -423,7 +426,7 @@
      */
     @Test
     public void testAeCompensation() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing AE compensation for Camera " + id);
 
@@ -450,7 +453,7 @@
      */
     @Test
     public void testAeRegions() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing AE regions for Camera " + id);
                 openDevice(id);
@@ -476,7 +479,7 @@
      */
     @Test
     public void testAwbRegions() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing AE regions for Camera " + id);
                 openDevice(id);
@@ -502,7 +505,7 @@
      */
     @Test
     public void testAfRegions() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing AF regions for Camera " + id);
                 openDevice(id);
@@ -528,7 +531,7 @@
      */
     @Test
     public void testPreviewPersistence() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing preview persistence for Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -546,7 +549,7 @@
 
     @Test
     public void testAePrecaptureTriggerCancelJpegCapture() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing AE precapture cancel for jpeg capture for Camera " + id);
 
@@ -581,7 +584,7 @@
      */
     @Test
     public void testAllocateBitmap() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 Log.i(TAG, "Testing bitmap allocations for Camera " + id);
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
@@ -605,7 +608,7 @@
      */
     @Test
     public void testFocalLengths() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 StaticMetadata staticInfo = mAllStaticInfo.get(id);
                 if (staticInfo.isHardwareLevelLegacy()) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java b/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
index 3d84d388..1f2e93e 100644
--- a/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
@@ -52,11 +52,15 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.runners.Parameterized;
+import org.junit.runner.RunWith;
 import org.junit.Test;
 
 /**
  * CameraDevice preview test by using SurfaceView.
  */
+
+@RunWith(Parameterized.class)
 public class SurfaceViewPreviewTest extends Camera2SurfaceViewTestCase {
     private static final String TAG = "SurfaceViewPreviewTest";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
@@ -86,15 +90,15 @@
      */
     @Test
     public void testCameraPreview() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing preview for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                Log.i(TAG, "Testing preview for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 previewTestByCamera();
             } finally {
                 closeDevice();
@@ -111,15 +115,15 @@
      */
     @Test
     public void testBasicTestPatternPreview() throws Exception{
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                Log.i(TAG, "Testing preview for Camera " + mCameraIds[i]);
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                Log.i(TAG, "Testing preview for Camera " + mCameraIdsUnderTest[i]);
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
                 previewTestPatternTestByCamera();
             } finally {
                 closeDevice();
@@ -133,7 +137,7 @@
      */
     @Test
     public void testPreviewFpsRange() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
@@ -159,7 +163,7 @@
      */
     @Test
     public void testSurfaceSet() throws Exception {
-        for (String id : mCameraIds) {
+        for (String id : mCameraIdsUnderTest) {
             try {
                 if (!mAllStaticInfo.get(id).isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
@@ -184,15 +188,15 @@
      */
     @Test
     public void testPreparePerformance() throws Throwable {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
-                preparePerformanceTestByCamera(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
+                preparePerformanceTestByCamera(mCameraIdsUnderTest[i]);
             }
             finally {
                 closeDevice();
@@ -344,15 +348,15 @@
      */
     @Test
     public void testSurfaceEquality() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                if (!mAllStaticInfo.get(mCameraIdsUnderTest[i]).isColorOutputSupported()) {
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
-                openDevice(mCameraIds[i]);
-                surfaceEqualityTestByCamera(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
+                surfaceEqualityTestByCamera(mCameraIdsUnderTest[i]);
             }
             finally {
                 closeDevice();
@@ -435,21 +439,21 @@
      */
     @Test
     public void testDeferredSurfaces() throws Exception {
-        for (int i = 0; i < mCameraIds.length; i++) {
+        for (int i = 0; i < mCameraIdsUnderTest.length; i++) {
             try {
-                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIds[i]);
+                StaticMetadata staticInfo = mAllStaticInfo.get(mCameraIdsUnderTest[i]);
                 if (staticInfo.isHardwareLevelLegacy()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] + " is legacy, skipping");
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] + " is legacy, skipping");
                     continue;
                 }
                 if (!staticInfo.isColorOutputSupported()) {
-                    Log.i(TAG, "Camera " + mCameraIds[i] +
+                    Log.i(TAG, "Camera " + mCameraIdsUnderTest[i] +
                             " does not support color outputs, skipping");
                     continue;
                 }
 
-                openDevice(mCameraIds[i]);
-                testDeferredSurfacesByCamera(mCameraIds[i]);
+                openDevice(mCameraIdsUnderTest[i]);
+                testDeferredSurfacesByCamera(mCameraIdsUnderTest[i]);
             }
             finally {
                 closeDevice();
diff --git a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidBasicTestCase.java b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidBasicTestCase.java
new file mode 100644
index 0000000..c240065
--- /dev/null
+++ b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidBasicTestCase.java
@@ -0,0 +1,631 @@
+/*
+ * Copyright (C) 2019 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.hardware.camera2.cts.testcases;
+
+import static android.hardware.camera2.cts.CameraTestUtils.*;
+import static com.android.ex.camera2.blocking.BlockingStateCallback.*;
+
+import android.content.Context;
+import android.graphics.ImageFormat;
+import android.graphics.Rect;
+
+import android.hardware.camera2.cts.CameraTestUtils;
+import android.hardware.camera2.CameraCaptureSession;
+import android.hardware.camera2.CameraCaptureSession.CaptureCallback;
+import android.hardware.camera2.CameraCharacteristics;
+import android.hardware.camera2.CameraDevice;
+import android.hardware.camera2.CameraManager;
+import android.hardware.camera2.CaptureRequest;
+import android.hardware.camera2.params.OutputConfiguration;
+import android.hardware.camera2.params.SessionConfiguration;
+import android.util.Size;
+import android.hardware.camera2.cts.helpers.CameraErrorCollector;
+import android.hardware.camera2.cts.helpers.StaticMetadata;
+import android.hardware.camera2.cts.helpers.StaticMetadata.CheckLevel;
+import android.media.Image;
+import android.media.Image.Plane;
+import android.media.ImageReader;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.test.AndroidTestCase;
+import android.util.Log;
+import android.view.Surface;
+import android.view.WindowManager;
+
+import com.android.ex.camera2.blocking.BlockingSessionCallback;
+import com.android.ex.camera2.blocking.BlockingStateCallback;
+
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+public class Camera2AndroidBasicTestCase extends AndroidTestCase {
+    private static final String TAG = "Camera2AndroidBasicTestCase";
+    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
+
+    // Default capture size: VGA size is required by CDD.
+    protected static final Size DEFAULT_CAPTURE_SIZE = new Size(640, 480);
+    protected static final int CAPTURE_WAIT_TIMEOUT_MS = 5000;
+
+    protected CameraManager mCameraManager;
+    protected CameraDevice mCamera;
+    protected CameraCaptureSession mCameraSession;
+    protected BlockingSessionCallback mCameraSessionListener;
+    protected BlockingStateCallback mCameraListener;
+    protected String[] mCameraIdsUnderTest;
+    // include both standalone camera IDs and "hidden" physical camera IDs
+    protected String[] mAllCameraIds;
+    protected HashMap<String, StaticMetadata> mAllStaticInfo;
+    protected ImageReader mReader;
+    protected Surface mReaderSurface;
+    protected Handler mHandler;
+    protected HandlerThread mHandlerThread;
+    protected StaticMetadata mStaticInfo;
+    protected CameraErrorCollector mCollector;
+    protected List<Size> mOrderedPreviewSizes; // In descending order.
+    protected List<Size> mOrderedVideoSizes; // In descending order.
+    protected List<Size> mOrderedStillSizes; // In descending order.
+    protected String mDebugFileNameBase;
+
+    protected WindowManager mWindowManager;
+
+    @Override
+    public void setContext(Context context) {
+        super.setContext(context);
+        mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
+        assertNotNull("Can't connect to camera manager!", mCameraManager);
+        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
+    }
+
+    /**
+     * Set up the camera2 test case required environments, including CameraManager,
+     * HandlerThread, Camera IDs, and CameraStateCallback etc.
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        /**
+         * Workaround for mockito and JB-MR2 incompatibility
+         *
+         * Avoid java.lang.IllegalArgumentException: dexcache == null
+         * https://code.google.com/p/dexmaker/issues/detail?id=2
+         */
+        System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
+
+        mCameraIdsUnderTest = mCameraManager.getCameraIdListNoLazy();
+        assertNotNull("Camera ids shouldn't be null", mCameraIdsUnderTest);
+        mHandlerThread = new HandlerThread(TAG);
+        mHandlerThread.start();
+        mHandler = new Handler(mHandlerThread.getLooper());
+        mCameraListener = new BlockingStateCallback();
+        mCollector = new CameraErrorCollector();
+
+        File filesDir = mContext.getPackageManager().isInstantApp()
+                ? mContext.getFilesDir()
+                : mContext.getExternalFilesDir(null);
+
+        mDebugFileNameBase = filesDir.getPath();
+
+        mAllStaticInfo = new HashMap<String, StaticMetadata>();
+        List<String> hiddenPhysicalIds = new ArrayList<>();
+        for (String cameraId : mCameraIdsUnderTest) {
+            CameraCharacteristics props = mCameraManager.getCameraCharacteristics(cameraId);
+            StaticMetadata staticMetadata = new StaticMetadata(props,
+                    CheckLevel.ASSERT, /*collector*/null);
+            mAllStaticInfo.put(cameraId, staticMetadata);
+
+            for (String physicalId : props.getPhysicalCameraIds()) {
+                if (!Arrays.asList(mCameraIdsUnderTest).contains(physicalId) &&
+                        !hiddenPhysicalIds.contains(physicalId)) {
+                    hiddenPhysicalIds.add(physicalId);
+                    props = mCameraManager.getCameraCharacteristics(physicalId);
+                    staticMetadata = new StaticMetadata(
+                            mCameraManager.getCameraCharacteristics(physicalId),
+                            CheckLevel.ASSERT, /*collector*/null);
+                    mAllStaticInfo.put(physicalId, staticMetadata);
+                }
+            }
+        }
+        mAllCameraIds = new String[mCameraIdsUnderTest.length + hiddenPhysicalIds.size()];
+        System.arraycopy(mCameraIdsUnderTest, 0, mAllCameraIds, 0, mCameraIdsUnderTest.length);
+        for (int i = 0; i < hiddenPhysicalIds.size(); i++) {
+            mAllCameraIds[mCameraIdsUnderTest.length + i] = hiddenPhysicalIds.get(i);
+        }
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        String[] cameraIdsPostTest =
+                mCameraManager.getCameraIdListNoLazy();
+        assertNotNull("Camera ids shouldn't be null", cameraIdsPostTest);
+        Log.i(TAG, "Camera ids in setup:" + Arrays.toString(mCameraIdsUnderTest));
+        Log.i(TAG, "Camera ids in tearDown:" + Arrays.toString(cameraIdsPostTest));
+        assertTrue(
+                "Number of cameras changed from " + mCameraIdsUnderTest.length + " to " +
+                cameraIdsPostTest.length,
+                mCameraIdsUnderTest.length == cameraIdsPostTest.length);
+        mHandlerThread.quitSafely();
+        mHandler = null;
+        closeDefaultImageReader();
+
+        try {
+            mCollector.verify();
+        } catch (Throwable e) {
+            // When new Exception(e) is used, exception info will be printed twice.
+            throw new Exception(e.getMessage());
+        } finally {
+            super.tearDown();
+        }
+    }
+
+    /**
+     * Start capture with given {@link #CaptureRequest}.
+     *
+     * @param request The {@link #CaptureRequest} to be captured.
+     * @param repeating If the capture is single capture or repeating.
+     * @param listener The {@link #CaptureCallback} camera device used to notify callbacks.
+     * @param handler The handler camera device used to post callbacks.
+     */
+    protected void startCapture(CaptureRequest request, boolean repeating,
+            CaptureCallback listener, Handler handler) throws Exception {
+        if (VERBOSE) Log.v(TAG, "Starting capture from device");
+
+        if (repeating) {
+            mCameraSession.setRepeatingRequest(request, listener, handler);
+        } else {
+            mCameraSession.capture(request, listener, handler);
+        }
+    }
+
+    /**
+     * Stop the current active capture.
+     *
+     * @param fast When it is true, {@link CameraDevice#flush} is called, the stop capture
+     * could be faster.
+     */
+    protected void stopCapture(boolean fast) throws Exception {
+        if (VERBOSE) Log.v(TAG, "Stopping capture");
+
+        if (fast) {
+            /**
+             * Flush is useful for canceling long exposure single capture, it also could help
+             * to make the streaming capture stop sooner.
+             */
+            mCameraSession.abortCaptures();
+            mCameraSessionListener.getStateWaiter().
+                    waitForState(BlockingSessionCallback.SESSION_READY, CAMERA_IDLE_TIMEOUT_MS);
+        } else {
+            mCameraSession.close();
+            mCameraSessionListener.getStateWaiter().
+                    waitForState(BlockingSessionCallback.SESSION_CLOSED, CAMERA_IDLE_TIMEOUT_MS);
+        }
+    }
+
+    /**
+     * Open a {@link #CameraDevice camera device} and get the StaticMetadata for a given camera id.
+     * The default mCameraListener is used to wait for states.
+     *
+     * @param cameraId The id of the camera device to be opened.
+     */
+    protected void openDevice(String cameraId) throws Exception {
+        openDevice(cameraId, mCameraListener);
+    }
+
+    /**
+     * Open a {@link #CameraDevice} and get the StaticMetadata for a given camera id and listener.
+     *
+     * @param cameraId The id of the camera device to be opened.
+     * @param listener The {@link #BlockingStateCallback} used to wait for states.
+     */
+    protected void openDevice(String cameraId, BlockingStateCallback listener) throws Exception {
+        mCamera = CameraTestUtils.openCamera(
+                mCameraManager, cameraId, listener, mHandler);
+        mCollector.setCameraId(cameraId);
+        mStaticInfo = mAllStaticInfo.get(cameraId);
+        if (mStaticInfo.isColorOutputSupported()) {
+            mOrderedPreviewSizes = getSupportedPreviewSizes(
+                    cameraId, mCameraManager,
+                    getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
+            mOrderedVideoSizes = getSupportedVideoSizes(cameraId, mCameraManager, PREVIEW_SIZE_BOUND);
+            mOrderedStillSizes = getSupportedStillSizes(cameraId, mCameraManager, null);
+        }
+
+        if (VERBOSE) {
+            Log.v(TAG, "Camera " + cameraId + " is opened");
+        }
+    }
+
+    /**
+     * Create a {@link #CameraCaptureSession} using the currently open camera.
+     *
+     * @param outputSurfaces The set of output surfaces to configure for this session
+     */
+    protected void createSession(List<Surface> outputSurfaces) throws Exception {
+        mCameraSessionListener = new BlockingSessionCallback();
+        mCameraSession = CameraTestUtils.configureCameraSession(mCamera, outputSurfaces,
+                mCameraSessionListener, mHandler);
+    }
+
+    /**
+     * Create a {@link #CameraCaptureSession} using the currently open camera with
+     * OutputConfigurations.
+     *
+     * @param outputSurfaces The set of output surfaces to configure for this session
+     */
+    protected void createSessionByConfigs(List<OutputConfiguration> outputConfigs) throws Exception {
+        mCameraSessionListener = new BlockingSessionCallback();
+        mCameraSession = CameraTestUtils.configureCameraSessionWithConfig(mCamera, outputConfigs,
+                mCameraSessionListener, mHandler);
+    }
+
+    /**
+     * Close a {@link #CameraDevice camera device} and clear the associated StaticInfo field for a
+     * given camera id. The default mCameraListener is used to wait for states.
+     * <p>
+     * This function must be used along with the {@link #openDevice} for the
+     * same camera id.
+     * </p>
+     *
+     * @param cameraId The id of the {@link #CameraDevice camera device} to be closed.
+     */
+    protected void closeDevice(String cameraId) {
+        closeDevice(cameraId, mCameraListener);
+    }
+
+    /**
+     * Close a {@link #CameraDevice camera device} and clear the associated StaticInfo field for a
+     * given camera id and listener.
+     * <p>
+     * This function must be used along with the {@link #openDevice} for the
+     * same camera id.
+     * </p>
+     *
+     * @param cameraId The id of the camera device to be closed.
+     * @param listener The BlockingStateCallback used to wait for states.
+     */
+    protected void closeDevice(String cameraId, BlockingStateCallback listener) {
+        if (mCamera != null) {
+            if (!cameraId.equals(mCamera.getId())) {
+                throw new IllegalStateException("Try to close a device that is not opened yet");
+            }
+            mCamera.close();
+            listener.waitForState(STATE_CLOSED, CAMERA_CLOSE_TIMEOUT_MS);
+            mCamera = null;
+            mCameraSession = null;
+            mCameraSessionListener = null;
+            mStaticInfo = null;
+            mOrderedPreviewSizes = null;
+            mOrderedVideoSizes = null;
+            mOrderedStillSizes = null;
+
+            if (VERBOSE) {
+                Log.v(TAG, "Camera " + cameraId + " is closed");
+            }
+        }
+    }
+
+    /**
+     * Create an {@link ImageReader} object and get the surface.
+     * <p>
+     * This function creates {@link ImageReader} object and surface, then assign
+     * to the default {@link mReader} and {@link mReaderSurface}. It closes the
+     * current default active {@link ImageReader} if it exists.
+     * </p>
+     *
+     * @param size The size of this ImageReader to be created.
+     * @param format The format of this ImageReader to be created
+     * @param maxNumImages The max number of images that can be acquired
+     *            simultaneously.
+     * @param listener The listener used by this ImageReader to notify
+     *            callbacks.
+     */
+    protected void createDefaultImageReader(Size size, int format, int maxNumImages,
+            ImageReader.OnImageAvailableListener listener) throws Exception {
+        closeDefaultImageReader();
+
+        mReader = createImageReader(size, format, maxNumImages, listener);
+        mReaderSurface = mReader.getSurface();
+        if (VERBOSE) Log.v(TAG, "Created ImageReader size " + size.toString());
+    }
+
+    /**
+     * Create an {@link ImageReader} object and get the surface.
+     * <p>
+     * This function creates {@link ImageReader} object and surface, then assign
+     * to the default {@link mReader} and {@link mReaderSurface}. It closes the
+     * current default active {@link ImageReader} if it exists.
+     * </p>
+     *
+     * @param size The size of this ImageReader to be created.
+     * @param format The format of this ImageReader to be created
+     * @param maxNumImages The max number of images that can be acquired
+     *            simultaneously.
+     * @param usage The usage flag of the ImageReader
+     * @param listener The listener used by this ImageReader to notify
+     *            callbacks.
+     */
+    protected void createDefaultImageReader(Size size, int format, int maxNumImages, long usage,
+            ImageReader.OnImageAvailableListener listener) throws Exception {
+        closeDefaultImageReader();
+
+        mReader = createImageReader(size, format, maxNumImages, usage, listener);
+        mReaderSurface = mReader.getSurface();
+        if (VERBOSE) Log.v(TAG, "Created ImageReader size " + size.toString());
+    }
+
+    /**
+     * Create an {@link ImageReader} object.
+     *
+     * <p>This function creates image reader object for given format, maxImages, and size.</p>
+     *
+     * @param size The size of this ImageReader to be created.
+     * @param format The format of this ImageReader to be created
+     * @param maxNumImages The max number of images that can be acquired simultaneously.
+     * @param listener The listener used by this ImageReader to notify callbacks.
+     */
+
+    protected ImageReader createImageReader(Size size, int format, int maxNumImages,
+            ImageReader.OnImageAvailableListener listener) throws Exception {
+
+        ImageReader reader = null;
+        reader = ImageReader.newInstance(size.getWidth(), size.getHeight(),
+                format, maxNumImages);
+
+        reader.setOnImageAvailableListener(listener, mHandler);
+        if (VERBOSE) Log.v(TAG, "Created ImageReader size " + size.toString());
+        return reader;
+    }
+
+    /**
+     * Create an {@link ImageReader} object.
+     *
+     * <p>This function creates image reader object for given format, maxImages, usage and size.</p>
+     *
+     * @param size The size of this ImageReader to be created.
+     * @param format The format of this ImageReader to be created
+     * @param maxNumImages The max number of images that can be acquired simultaneously.
+     * @param usage The usage flag of the ImageReader
+     * @param listener The listener used by this ImageReader to notify callbacks.
+     */
+
+    protected ImageReader createImageReader(Size size, int format, int maxNumImages, long usage,
+            ImageReader.OnImageAvailableListener listener) throws Exception {
+        ImageReader reader = null;
+        reader = ImageReader.newInstance(size.getWidth(), size.getHeight(),
+                format, maxNumImages, usage);
+
+        reader.setOnImageAvailableListener(listener, mHandler);
+        if (VERBOSE) Log.v(TAG, "Created ImageReader size " + size.toString());
+        return reader;
+    }
+
+    /**
+     * Close the pending images then close current default {@link ImageReader} object.
+     */
+    protected void closeDefaultImageReader() {
+        closeImageReader(mReader);
+        mReader = null;
+        mReaderSurface = null;
+    }
+
+    /**
+     * Close an image reader instance.
+     *
+     * @param reader
+     */
+    protected void closeImageReader(ImageReader reader) {
+        if (reader != null) {
+            try {
+                // Close all possible pending images first.
+                Image image = reader.acquireLatestImage();
+                if (image != null) {
+                    image.close();
+                }
+            } finally {
+                reader.close();
+                reader = null;
+            }
+        }
+    }
+
+    protected void checkImageReaderSessionConfiguration(String msg) throws Exception {
+        List<OutputConfiguration> outputConfigs = new ArrayList<OutputConfiguration>();
+        outputConfigs.add(new OutputConfiguration(mReaderSurface));
+
+        checkSessionConfigurationSupported(mCamera, mHandler, outputConfigs, /*inputConfig*/ null,
+                SessionConfiguration.SESSION_REGULAR, /*expectedResult*/ true, msg);
+    }
+
+    protected CaptureRequest prepareCaptureRequest() throws Exception {
+        return prepareCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
+    }
+
+    protected CaptureRequest prepareCaptureRequest(int template) throws Exception {
+        List<Surface> outputSurfaces = new ArrayList<Surface>();
+        Surface surface = mReader.getSurface();
+        assertNotNull("Fail to get surface from ImageReader", surface);
+        outputSurfaces.add(surface);
+        return prepareCaptureRequestForSurfaces(outputSurfaces, template)
+                .build();
+    }
+
+    protected CaptureRequest.Builder prepareCaptureRequestForSurfaces(List<Surface> surfaces,
+            int template)
+            throws Exception {
+        createSession(surfaces);
+
+        CaptureRequest.Builder captureBuilder =
+                mCamera.createCaptureRequest(template);
+        assertNotNull("Fail to get captureRequest", captureBuilder);
+        for (Surface surface : surfaces) {
+            captureBuilder.addTarget(surface);
+        }
+
+        return captureBuilder;
+    }
+
+    protected CaptureRequest.Builder prepareCaptureRequestForConfigs(
+            List<OutputConfiguration> outputConfigs, int template) throws Exception {
+        createSessionByConfigs(outputConfigs);
+
+        CaptureRequest.Builder captureBuilder =
+                mCamera.createCaptureRequest(template);
+        assertNotNull("Fail to get captureRequest", captureBuilder);
+        for (OutputConfiguration config : outputConfigs) {
+            for (Surface s : config.getSurfaces()) {
+                captureBuilder.addTarget(s);
+            }
+        }
+
+        return captureBuilder;
+    }
+
+    /**
+     * Test the invalid Image access: accessing a closed image must result in
+     * {@link IllegalStateException}.
+     *
+     * @param closedImage The closed image.
+     * @param closedBuffer The ByteBuffer from a closed Image. buffer invalid
+     *            access will be skipped if it is null.
+     */
+    protected void imageInvalidAccessTestAfterClose(Image closedImage,
+            Plane closedPlane, ByteBuffer closedBuffer) {
+        if (closedImage == null) {
+            throw new IllegalArgumentException(" closedImage must be non-null");
+        }
+        if (closedBuffer != null && !closedBuffer.isDirect()) {
+            throw new IllegalArgumentException("The input ByteBuffer should be direct ByteBuffer");
+        }
+
+        if (closedPlane != null) {
+            // Plane#getBuffer test
+            try {
+                closedPlane.getBuffer(); // An ISE should be thrown here.
+                fail("Image should throw IllegalStateException when calling getBuffer"
+                        + " after the image is closed");
+            } catch (IllegalStateException e) {
+                // Expected.
+            }
+
+            // Plane#getPixelStride test
+            try {
+                closedPlane.getPixelStride(); // An ISE should be thrown here.
+                fail("Image should throw IllegalStateException when calling getPixelStride"
+                        + " after the image is closed");
+            } catch (IllegalStateException e) {
+                // Expected.
+            }
+
+            // Plane#getRowStride test
+            try {
+                closedPlane.getRowStride(); // An ISE should be thrown here.
+                fail("Image should throw IllegalStateException when calling getRowStride"
+                        + " after the image is closed");
+            } catch (IllegalStateException e) {
+                // Expected.
+            }
+        }
+
+        // ByteBuffer access test
+        if (closedBuffer != null) {
+            try {
+                closedBuffer.get(); // An ISE should be thrown here.
+                fail("Image should throw IllegalStateException when accessing a byte buffer"
+                        + " after the image is closed");
+            } catch (IllegalStateException e) {
+                // Expected.
+            }
+        }
+
+        // Image#getFormat test
+        try {
+            closedImage.getFormat();
+            fail("Image should throw IllegalStateException when calling getFormat"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#getWidth test
+        try {
+            closedImage.getWidth();
+            fail("Image should throw IllegalStateException when calling getWidth"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#getHeight test
+        try {
+            closedImage.getHeight();
+            fail("Image should throw IllegalStateException when calling getHeight"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#getTimestamp test
+        try {
+            closedImage.getTimestamp();
+            fail("Image should throw IllegalStateException when calling getTimestamp"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#getTimestamp test
+        try {
+            closedImage.getTimestamp();
+            fail("Image should throw IllegalStateException when calling getTimestamp"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#getCropRect test
+        try {
+            closedImage.getCropRect();
+            fail("Image should throw IllegalStateException when calling getCropRect"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#setCropRect test
+        try {
+            Rect rect = new Rect();
+            closedImage.setCropRect(rect);
+            fail("Image should throw IllegalStateException when calling setCropRect"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+
+        // Image#getPlanes test
+        try {
+            closedImage.getPlanes();
+            fail("Image should throw IllegalStateException when calling getPlanes"
+                    + " after the image is closed");
+        } catch (IllegalStateException e) {
+            // Expected.
+        }
+    }
+}
diff --git a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java
index 4cd0046..e4695e9 100644
--- a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java
+++ b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java
@@ -22,6 +22,7 @@
 import android.content.Context;
 import android.graphics.ImageFormat;
 import android.graphics.Rect;
+import android.hardware.cts.helpers.CameraParameterizedTestCase;
 import android.hardware.camera2.CameraCaptureSession;
 import android.hardware.camera2.CameraCaptureSession.CaptureCallback;
 import android.hardware.camera2.CameraCharacteristics;
@@ -31,6 +32,7 @@
 import android.hardware.camera2.params.OutputConfiguration;
 import android.hardware.camera2.params.SessionConfiguration;
 import android.util.Size;
+import android.hardware.camera2.cts.Camera2ParameterizedTestCase;
 import android.hardware.camera2.cts.CameraTestUtils;
 import android.hardware.camera2.cts.helpers.CameraErrorCollector;
 import android.hardware.camera2.cts.helpers.StaticMetadata;
@@ -44,6 +46,7 @@
 import android.util.Log;
 import android.view.Surface;
 import android.view.WindowManager;
+import androidx.test.InstrumentationRegistry;
 
 import com.android.ex.camera2.blocking.BlockingSessionCallback;
 import com.android.ex.camera2.blocking.BlockingStateCallback;
@@ -55,7 +58,11 @@
 import java.util.HashMap;
 import java.util.List;
 
-public class Camera2AndroidTestCase extends AndroidTestCase {
+import org.junit.Ignore;
+import org.junit.Test;
+
+// TODO: Can we de-duplicate this with Camera2AndroidBasicTestCase keeping in mind CtsVerifier ?
+public class Camera2AndroidTestCase extends Camera2ParameterizedTestCase {
     private static final String TAG = "Camera2AndroidTestCase";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
 
@@ -63,12 +70,10 @@
     protected static final Size DEFAULT_CAPTURE_SIZE = new Size(640, 480);
     protected static final int CAPTURE_WAIT_TIMEOUT_MS = 5000;
 
-    protected CameraManager mCameraManager;
     protected CameraDevice mCamera;
     protected CameraCaptureSession mCameraSession;
     protected BlockingSessionCallback mCameraSessionListener;
     protected BlockingStateCallback mCameraListener;
-    protected String[] mCameraIds;
     // include both standalone camera IDs and "hidden" physical camera IDs
     protected String[] mAllCameraIds;
     protected HashMap<String, StaticMetadata> mAllStaticInfo;
@@ -85,32 +90,15 @@
 
     protected WindowManager mWindowManager;
 
-    @Override
-    public void setContext(Context context) {
-        super.setContext(context);
-        mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
-        assertNotNull("Can't connect to camera manager!", mCameraManager);
-        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
-    }
-
     /**
      * Set up the camera2 test case required environments, including CameraManager,
      * HandlerThread, Camera IDs, and CameraStateCallback etc.
      */
     @Override
-    protected void setUp() throws Exception {
+    public void setUp() throws Exception {
         super.setUp();
+        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
 
-        /**
-         * Workaround for mockito and JB-MR2 incompatibility
-         *
-         * Avoid java.lang.IllegalArgumentException: dexcache == null
-         * https://code.google.com/p/dexmaker/issues/detail?id=2
-         */
-        System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
-
-        mCameraIds = mCameraManager.getCameraIdList();
-        assertNotNull("Camera ids shouldn't be null", mCameraIds);
         mHandlerThread = new HandlerThread(TAG);
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
@@ -125,14 +113,14 @@
 
         mAllStaticInfo = new HashMap<String, StaticMetadata>();
         List<String> hiddenPhysicalIds = new ArrayList<>();
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             CameraCharacteristics props = mCameraManager.getCameraCharacteristics(cameraId);
             StaticMetadata staticMetadata = new StaticMetadata(props,
                     CheckLevel.ASSERT, /*collector*/null);
             mAllStaticInfo.put(cameraId, staticMetadata);
 
             for (String physicalId : props.getPhysicalCameraIds()) {
-                if (!Arrays.asList(mCameraIds).contains(physicalId) &&
+                if (!Arrays.asList(mCameraIdsUnderTest).contains(physicalId) &&
                         !hiddenPhysicalIds.contains(physicalId)) {
                     hiddenPhysicalIds.add(physicalId);
                     props = mCameraManager.getCameraCharacteristics(physicalId);
@@ -143,23 +131,15 @@
                 }
             }
         }
-        mAllCameraIds = new String[mCameraIds.length + hiddenPhysicalIds.size()];
-        System.arraycopy(mCameraIds, 0, mAllCameraIds, 0, mCameraIds.length);
+        mAllCameraIds = new String[mCameraIdsUnderTest.length + hiddenPhysicalIds.size()];
+        System.arraycopy(mCameraIdsUnderTest, 0, mAllCameraIds, 0, mCameraIdsUnderTest.length);
         for (int i = 0; i < hiddenPhysicalIds.size(); i++) {
-            mAllCameraIds[mCameraIds.length + i] = hiddenPhysicalIds.get(i);
+            mAllCameraIds[mCameraIdsUnderTest.length + i] = hiddenPhysicalIds.get(i);
         }
     }
 
     @Override
-    protected void tearDown() throws Exception {
-        String[] cameraIdsPostTest = mCameraManager.getCameraIdList();
-        assertNotNull("Camera ids shouldn't be null", cameraIdsPostTest);
-        Log.i(TAG, "Camera ids in setup:" + Arrays.toString(mCameraIds));
-        Log.i(TAG, "Camera ids in tearDown:" + Arrays.toString(cameraIdsPostTest));
-        assertTrue(
-                "Number of cameras changed from " + mCameraIds.length + " to " +
-                cameraIdsPostTest.length,
-                mCameraIds.length == cameraIdsPostTest.length);
+    public void tearDown() throws Exception {
         mHandlerThread.quitSafely();
         mHandler = null;
         closeDefaultImageReader();
diff --git a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java
index c345b41..090aa6c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java
+++ b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java
@@ -28,6 +28,8 @@
 import android.graphics.RectF;
 import android.graphics.SurfaceTexture;
 import android.hardware.camera2.CameraCaptureSession;
+import android.hardware.camera2.cts.Camera2ParameterizedTestCase;
+import android.hardware.camera2.cts.CameraTestUtils;
 import android.hardware.camera2.CameraCaptureSession.CaptureCallback;
 import android.hardware.camera2.CameraDevice;
 import android.hardware.camera2.CameraManager;
@@ -58,6 +60,7 @@
 
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Rule;
 
 import java.util.Arrays;
@@ -67,7 +70,8 @@
 /**
  * Camera2 test case base class by using mixed SurfaceView and TextureView as rendering target.
  */
-public class Camera2MultiViewTestCase {
+
+public class Camera2MultiViewTestCase extends Camera2ParameterizedTestCase {
     private static final String TAG = "MultiViewTestCase";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
 
@@ -75,13 +79,10 @@
 
     protected TextureView[] mTextureView =
             new TextureView[Camera2MultiViewCtsActivity.MAX_TEXTURE_VIEWS];
-    protected String[] mCameraIds;
     protected Handler mHandler;
 
-    private CameraManager mCameraManager;
     private HandlerThread mHandlerThread;
     private Activity mActivity;
-    private Context mContext;
 
     private CameraHolder[] mCameraHolders;
     private HashMap<String, Integer> mCameraIdMap;
@@ -92,15 +93,10 @@
     public ActivityTestRule<Camera2MultiViewCtsActivity> mActivityRule =
             new ActivityTestRule<>(Camera2MultiViewCtsActivity.class);
 
-    @Before
+    @Override
     public void setUp() throws Exception {
+        super.setUp();
         mActivity = mActivityRule.getActivity();
-        mContext = mActivity.getApplicationContext();
-        assertNotNull("Unable to get activity", mContext);
-        mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
-        assertNotNull("Unable to get CameraManager", mCameraManager);
-        mCameraIds = mCameraManager.getCameraIdList();
-        assertNotNull("Unable to get camera ids", mCameraIds);
         mHandlerThread = new HandlerThread(TAG);
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
@@ -110,25 +106,17 @@
         }
         assertNotNull("Unable to get texture view", mTextureView);
         mCameraIdMap = new HashMap<String, Integer>();
-        int numCameras = mCameraIds.length;
+        int numCameras = mCameraIdsUnderTest.length;
         mCameraHolders = new CameraHolder[numCameras];
         for (int i = 0; i < numCameras; i++) {
-            mCameraHolders[i] = new CameraHolder(mCameraIds[i]);
-            mCameraIdMap.put(mCameraIds[i], i);
+            mCameraHolders[i] = new CameraHolder(mCameraIdsUnderTest[i]);
+            mCameraIdMap.put(mCameraIdsUnderTest[i], i);
         }
         mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
     }
 
-    @After
+    @Override
     public void tearDown() throws Exception {
-        String[] cameraIdsPostTest = mCameraManager.getCameraIdList();
-        assertNotNull("Camera ids shouldn't be null", cameraIdsPostTest);
-        Log.i(TAG, "Camera ids in setup:" + Arrays.toString(mCameraIds));
-        Log.i(TAG, "Camera ids in tearDown:" + Arrays.toString(cameraIdsPostTest));
-        assertTrue(
-                "Number of cameras changed from " + mCameraIds.length + " to " +
-                cameraIdsPostTest.length,
-                mCameraIds.length == cameraIdsPostTest.length);
         mHandlerThread.quitSafely();
         mHandler = null;
         for (CameraHolder camera : mCameraHolders) {
@@ -137,6 +125,7 @@
                 camera = null;
             }
         }
+        super.tearDown();
     }
 
     /**
diff --git a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
index 5a95d62..ecc87d6 100644
--- a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
+++ b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
@@ -19,6 +19,8 @@
 import static android.hardware.camera2.cts.CameraTestUtils.*;
 
 import static com.android.ex.camera2.blocking.BlockingStateCallback.STATE_CLOSED;
+import androidx.test.InstrumentationRegistry;
+import android.app.UiAutomation;
 
 import android.content.Context;
 import android.graphics.ImageFormat;
@@ -32,6 +34,7 @@
 import android.hardware.camera2.CaptureRequest;
 import android.hardware.camera2.CaptureResult;
 import android.hardware.camera2.cts.Camera2SurfaceViewCtsActivity;
+import android.hardware.camera2.cts.Camera2ParameterizedTestCase;
 import android.hardware.camera2.cts.CameraTestUtils;
 import android.hardware.camera2.cts.CameraTestUtils.SimpleCaptureCallback;
 import android.hardware.camera2.cts.helpers.CameraErrorCollector;
@@ -57,6 +60,7 @@
 
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Rule;
 
 import java.io.File;
@@ -64,6 +68,12 @@
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
 
 /**
  * Camera2 Preview test case base class by using SurfaceView as rendering target.
@@ -75,7 +85,7 @@
  * </p>
  */
 
-public class Camera2SurfaceViewTestCase {
+public class Camera2SurfaceViewTestCase extends Camera2ParameterizedTestCase {
     private static final String TAG = "SurfaceViewTestCase";
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
     private static final int WAIT_FOR_SURFACE_CHANGE_TIMEOUT_MS = 1000;
@@ -86,9 +96,6 @@
     protected static final int NUM_FRAMES_WAITED_FOR_UNKNOWN_LATENCY = 8;
     protected static final int MIN_FRAME_DURATION_ERROR_MARGIN = 100; // ns
 
-    protected Context mContext;
-    protected CameraManager mCameraManager;
-    protected String[] mCameraIds;
     protected HandlerThread mHandlerThread;
     protected Handler mHandler;
     protected BlockingStateCallback mCameraListener;
@@ -119,18 +126,7 @@
 
     @Before
     public void setUp() throws Exception {
-        mContext = mActivityRule.getActivity().getApplicationContext();
-        /**
-         * Workaround for mockito and JB-MR2 incompatibility
-         *
-         * Avoid java.lang.IllegalArgumentException: dexcache == null
-         * https://code.google.com/p/dexmaker/issues/detail?id=2
-         */
-        System.setProperty("dexmaker.dexcache", mContext.getCacheDir().toString());
-        mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
-        assertNotNull("Unable to get CameraManager", mCameraManager);
-        mCameraIds = mCameraManager.getCameraIdList();
-        assertNotNull("Unable to get camera ids", mCameraIds);
+        super.setUp();
         mHandlerThread = new HandlerThread(TAG);
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
@@ -145,14 +141,14 @@
 
         mAllStaticInfo = new HashMap<String, StaticMetadata>();
         List<String> hiddenPhysicalIds = new ArrayList<>();
-        for (String cameraId : mCameraIds) {
+        for (String cameraId : mCameraIdsUnderTest) {
             CameraCharacteristics props = mCameraManager.getCameraCharacteristics(cameraId);
             StaticMetadata staticMetadata = new StaticMetadata(props,
                     CheckLevel.ASSERT, /*collector*/null);
             mAllStaticInfo.put(cameraId, staticMetadata);
 
             for (String physicalId : props.getPhysicalCameraIds()) {
-                if (!Arrays.asList(mCameraIds).contains(physicalId) &&
+                if (!Arrays.asList(mCameraIdsUnderTest).contains(physicalId) &&
                         !hiddenPhysicalIds.contains(physicalId)) {
                     hiddenPhysicalIds.add(physicalId);
                     props = mCameraManager.getCameraCharacteristics(physicalId);
@@ -169,15 +165,6 @@
 
     @After
     public void tearDown() throws Exception {
-        String[] cameraIdsPostTest = mCameraManager.getCameraIdList();
-        assertNotNull("Camera ids shouldn't be null", cameraIdsPostTest);
-        Log.i(TAG, "Camera ids in setup:" + Arrays.toString(mCameraIds));
-        Log.i(TAG, "Camera ids in tearDown:" + Arrays.toString(cameraIdsPostTest));
-        assertTrue(
-                "Number of cameras changed from " + mCameraIds.length + " to " +
-                cameraIdsPostTest.length,
-                mCameraIds.length == cameraIdsPostTest.length);
-        // Teardown the camera preview required environments.
         mHandlerThread.quitSafely();
         mHandler = null;
         mCameraListener = null;
@@ -188,6 +175,7 @@
             // When new Exception(e) is used, exception info will be printed twice.
             throw new Exception(e.getMessage());
         }
+        super.tearDown();
     }
 
     /**
@@ -541,7 +529,7 @@
         List<Integer> expectedAeStates = new ArrayList<Integer>();
         expectedAeStates.add(new Integer(CaptureResult.CONTROL_AE_STATE_LOCKED));
         CameraTestUtils.waitForAnyResultValue(resultListener, CaptureResult.CONTROL_AE_STATE,
-                expectedAeStates, WAIT_FOR_RESULT_TIMEOUT_MS, NUM_RESULTS_WAIT_TIMEOUT);
+                expectedAeStates, NUM_RESULTS_WAIT_TIMEOUT, WAIT_FOR_RESULT_TIMEOUT_MS);
     }
 
     /**
diff --git a/tests/camera/src/android/hardware/multiprocess/camera/cts/Camera2Activity.java b/tests/camera/src/android/hardware/multiprocess/camera/cts/Camera2Activity.java
index 418eb7c..398ffb8 100644
--- a/tests/camera/src/android/hardware/multiprocess/camera/cts/Camera2Activity.java
+++ b/tests/camera/src/android/hardware/multiprocess/camera/cts/Camera2Activity.java
@@ -63,7 +63,7 @@
                         " could not connect camera service");
                 return;
             }
-            String[] cameraIds = manager.getCameraIdList();
+            String[] cameraIds = manager.getCameraIdListNoLazy();
 
             if (cameraIds == null || cameraIds.length == 0) {
                 mErrorServiceConnection.logAsync(TestConstants.EVENT_CAMERA_ERROR, TAG +
diff --git a/tests/camera/src/android/hardware/multiprocess/camera/cts/CameraEvictionTest.java b/tests/camera/src/android/hardware/multiprocess/camera/cts/CameraEvictionTest.java
index 2a69aed..14dbd92 100644
--- a/tests/camera/src/android/hardware/multiprocess/camera/cts/CameraEvictionTest.java
+++ b/tests/camera/src/android/hardware/multiprocess/camera/cts/CameraEvictionTest.java
@@ -165,7 +165,7 @@
     public void testBasicCamera2ActivityEviction() throws Throwable {
         CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
         assertNotNull(manager);
-        String[] cameraIds = manager.getCameraIdList();
+        String[] cameraIds = manager.getCameraIdListNoLazy();
 
         if (cameraIds.length == 0) {
             Log.i(TAG, "Skipping testBasicCamera2ActivityEviction, device has no cameras.");
@@ -269,7 +269,7 @@
         int PERMISSION_CALLBACK_TIMEOUT_MS = 2000;
         CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
         assertNotNull(manager);
-        String[] cameraIds = manager.getCameraIdList();
+        String[] cameraIds = manager.getCameraIdListNoLazy();
 
         if (cameraIds.length == 0) {
             Log.i(TAG, "Skipping testCamera2AccessCallback, device has no cameras.");
@@ -305,7 +305,7 @@
         int PERMISSION_CALLBACK_TIMEOUT_MS = 2000;
         CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
         assertNotNull(manager);
-        String[] cameraIds = manager.getCameraIdList();
+        String[] cameraIds = manager.getCameraIdListNoLazy();
 
         if (cameraIds.length == 0) {
             Log.i(TAG, "Skipping testBasicCamera2AccessCallback, device has no cameras.");
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/Camera2ParameterizedTestCase.java b/tests/camera/utils/src/android/hardware/camera2/cts/Camera2ParameterizedTestCase.java
new file mode 100644
index 0000000..c7deb5a
--- /dev/null
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/Camera2ParameterizedTestCase.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2019 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.hardware.camera2.cts;
+
+import android.content.Context;
+import android.hardware.cts.helpers.CameraParameterizedTestCase;
+import android.hardware.camera2.cts.CameraTestUtils;
+import android.hardware.camera2.CameraManager;
+import android.util.Log;
+
+import java.util.Arrays;
+
+import org.junit.Ignore;
+
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertTrue;
+
+public class Camera2ParameterizedTestCase extends CameraParameterizedTestCase {
+    private static final String TAG = "Camera2ParameterizedTestCase";
+    protected CameraManager mCameraManager;
+    // The list of camera ids we're testing. If we're testing system cameras
+    // (mAdoptShellPerm == true), we have only system camera ids in the array and not normal camera
+    // ids.
+    protected String[] mCameraIdsUnderTest;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        /**
+         * Workaround for mockito and JB-MR2 incompatibility
+         *
+         * Avoid java.lang.IllegalArgumentException: dexcache == null
+         * https://code.google.com/p/dexmaker/issues/detail?id=2
+         */
+        System.setProperty("dexmaker.dexcache", mContext.getCacheDir().toString());
+        mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
+        assertNotNull("Unable to get CameraManager", mCameraManager);
+        mCameraIdsUnderTest =
+                CameraTestUtils.getCameraIdListForTesting(mCameraManager, mAdoptShellPerm);
+        assertNotNull("Unable to get camera ids", mCameraIdsUnderTest);
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        String[] cameraIdsPostTest =
+                CameraTestUtils.getCameraIdListForTesting(mCameraManager, mAdoptShellPerm);
+        assertNotNull("Camera ids shouldn't be null", cameraIdsPostTest);
+        Log.i(TAG, "Camera ids in setup:" + Arrays.toString(mCameraIdsUnderTest));
+        Log.i(TAG, "Camera ids in tearDown:" + Arrays.toString(cameraIdsPostTest));
+        assertTrue(
+                "Number of cameras changed from " + mCameraIdsUnderTest.length + " to " +
+                cameraIdsPostTest.length,
+                mCameraIdsUnderTest.length == cameraIdsPostTest.length);
+        super.tearDown();
+    }
+}
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
index e408cb5..b49a0a6 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -704,6 +704,38 @@
         }
     }
 
+    public static boolean hasCapability(CameraCharacteristics characteristics, int capability) {
+        int [] capabilities =
+                characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
+        for (int c : capabilities) {
+            if (c == capability) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static boolean isSystemCamera(CameraManager manager, String cameraId)
+            throws CameraAccessException {
+        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
+        return hasCapability(characteristics,
+                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA);
+    }
+
+    public static String[] getCameraIdListForTesting(CameraManager manager,
+            boolean getSystemCameras)
+            throws CameraAccessException {
+        String [] ids = manager.getCameraIdListNoLazy();
+        List<String> idsForTesting = new ArrayList<String>();
+        for (String id : ids) {
+            boolean isSystemCamera = isSystemCamera(manager, id);
+            if (getSystemCameras == isSystemCamera) {
+                idsForTesting.add(id);
+            }
+        }
+        return idsForTesting.toArray(new String[idsForTesting.size()]);
+    }
+
     /**
      * Block until the camera is opened.
      *
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/CameraMetadataGetter.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/CameraMetadataGetter.java
index db75cdd..e0a956e 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/CameraMetadataGetter.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/CameraMetadataGetter.java
@@ -108,7 +108,7 @@
         CameraCharacteristics staticMetadata;
         String[] cameraIds;
         try {
-            cameraIds = mCameraManager.getCameraIdList();
+            cameraIds = mCameraManager.getCameraIdListNoLazy();
         } catch (CameraAccessException e) {
             Log.e(TAG, "Unable to get camera ids, skip this info, error: " + e.getMessage());
             return "";
@@ -180,7 +180,7 @@
         StringBuffer templates = new StringBuffer("{\"CameraRequestTemplates\":{");
         String[] cameraIds;
         try {
-            cameraIds = mCameraManager.getCameraIdList();
+            cameraIds = mCameraManager.getCameraIdListNoLazy();
         } catch (CameraAccessException e) {
             Log.e(TAG, "Unable to get camera ids, skip this info, error: " + e.getMessage());
             return "";
diff --git a/tests/camera/utils/src/android/hardware/cts/helpers/CameraParameterizedTestCase.java b/tests/camera/utils/src/android/hardware/cts/helpers/CameraParameterizedTestCase.java
new file mode 100644
index 0000000..b2f4c04
--- /dev/null
+++ b/tests/camera/utils/src/android/hardware/cts/helpers/CameraParameterizedTestCase.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2019 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.hardware.cts.helpers;
+
+import android.app.UiAutomation;
+import android.content.Context;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+import android.app.Activity;
+import androidx.test.rule.ActivityTestRule;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class CameraParameterizedTestCase {
+    protected UiAutomation mUiAutomation;
+    protected Context mContext;
+    @Parameter(0)
+    public boolean mAdoptShellPerm;
+
+    @Parameters
+    public static Iterable<? extends Object> data() {
+        List<Boolean> adoptShellPerm = new ArrayList<Boolean>();
+        adoptShellPerm.add(true);
+        adoptShellPerm.add(false);
+        return adoptShellPerm;
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        mUiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        mContext = InstrumentationRegistry.getTargetContext();
+        if (mAdoptShellPerm) {
+            mUiAutomation.adoptShellPermissionIdentity();
+        }
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        if (mAdoptShellPerm) {
+            mUiAutomation.dropShellPermissionIdentity();
+        }
+    }
+}
diff --git a/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java b/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java
index fe119a9..0c143a5 100644
--- a/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java
+++ b/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java
@@ -38,7 +38,7 @@
      */
     public static boolean isLegacyHAL(Context context, int cameraId) throws Exception {
         CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
-        String cameraIdStr = manager.getCameraIdList()[cameraId];
+        String cameraIdStr = manager.getCameraIdListNoLazy()[cameraId];
         CameraCharacteristics characteristics =
                 manager.getCameraCharacteristics(cameraIdStr);
 
@@ -56,7 +56,7 @@
      */
     public static boolean isExternal(Context context, int cameraId) throws Exception {
         CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
-        String cameraIdStr = manager.getCameraIdList()[cameraId];
+        String cameraIdStr = manager.getCameraIdListNoLazy()[cameraId];
         CameraCharacteristics characteristics =
                 manager.getCameraCharacteristics(cameraIdStr);
 
diff --git a/tests/contentcaptureservice/Android.mk b/tests/contentcaptureservice/Android.mk
index bca3c1f..586d269 100644
--- a/tests/contentcaptureservice/Android.mk
+++ b/tests/contentcaptureservice/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsContentCaptureServiceTestCases
 
diff --git a/tests/contentcaptureservice/OWNERS b/tests/contentcaptureservice/OWNERS
index 595c93d..2abf830 100644
--- a/tests/contentcaptureservice/OWNERS
+++ b/tests/contentcaptureservice/OWNERS
@@ -1,4 +1,4 @@
 # Bug component: 544200
-felipeal@google.com
 adamhe@google.com
-svetoslavganov@google.com
\ No newline at end of file
+svetoslavganov@google.com
+felipeal@google.com
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java
index e01ed72..75bf961 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java
@@ -111,6 +111,65 @@
     }
 
     /**
+     * Test for notifySessionLifecycle().
+     */
+    @Test
+    public void testNotifySessionLifecycle() throws Exception {
+        final CtsContentCaptureService service = enableService();
+        final ActivityWatcher watcher = startWatcher();
+        final AtomicReference<CustomView> customViewRef = new AtomicReference<>();
+
+        CustomViewActivity.setCustomViewDelegate((customView, structure) -> {
+            customViewRef.set(customView);
+            final ContentCaptureSession session = customView.getContentCaptureSession();
+            session.notifySessionLifecycle(true);
+            session.notifySessionLifecycle(false);
+        });
+
+        final CustomViewActivity activity = launchActivity();
+        watcher.waitFor(RESUMED);
+
+        activity.finish();
+        watcher.waitFor(DESTROYED);
+
+        final Session session = service.getOnlyFinishedSession();
+        Log.v(TAG, "session id: " + session.id);
+
+        assertRightActivity(session, session.id, activity);
+
+        final View grandpa1 = (View) activity.mCustomView.getParent();
+        final View grandpa2 = (View) grandpa1.getParent();
+        final View decorView = activity.getDecorView();
+        final AutofillId customViewId = activity.mCustomView.getAutofillId();
+        Log.v(TAG, "assertJustInitialViewsAppeared(): grandpa1=" + grandpa1.getAutofillId()
+                + ", grandpa2=" + grandpa2.getAutofillId() + ", decor="
+                + decorView.getAutofillId() + "customView=" + customViewId);
+
+        final List<ContentCaptureEvent> events = session.getEvents();
+        Log.v(TAG, "events(" + events.size() + "): " + events);
+        final int additionalEvents = 2;
+
+        assertThat(events.size()).isAtLeast(CustomViewActivity.MIN_EVENTS + additionalEvents);
+
+        // Assert just the relevant events
+        assertSessionResumed(events, 0);
+        assertViewTreeStarted(events, 1);
+        assertDecorViewAppeared(events, 2, decorView);
+        assertViewAppeared(events, 3, grandpa2, decorView.getAutofillId());
+        assertViewAppeared(events, 4, grandpa1, grandpa2.getAutofillId());
+
+        // Assert for notifySessionLifecycle
+        assertSessionResumed(events, 5);
+        assertSessionPaused(events, 6);
+
+        assertViewWithUnknownParentAppeared(events, 7, session.id, customViewRef.get());
+        assertViewTreeFinished(events, 8);
+        assertSessionPaused(events, 9);
+
+        activity.assertInitialViewsDisappeared(events, additionalEvents);
+    }
+
+    /**
      * Tests when the view has virtual children but it doesn't return right away and calls
      * the session notification methods instead - this is wrong because the main view will be
      * notified last, but we cannot prevent the apps from doing so...
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/LoginActivityTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/LoginActivityTest.java
index ea22140..aa4fa9e 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/LoginActivityTest.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/LoginActivityTest.java
@@ -122,6 +122,46 @@
     }
 
     @Test
+    public void testContentCaptureSessionCache() throws Exception {
+        final CtsContentCaptureService service = enableService();
+        final ActivityWatcher watcher = startWatcher();
+
+        final ContentCaptureContext clientContext = newContentCaptureContext();
+
+        final AtomicReference<ContentCaptureSession> mainSessionRef = new AtomicReference<>();
+        final AtomicReference<ContentCaptureSession> childSessionRef = new AtomicReference<>();
+
+        LoginActivity.onRootView((activity, rootView) -> {
+            final ContentCaptureSession mainSession = rootView.getContentCaptureSession();
+            mainSessionRef.set(mainSession);
+            final ContentCaptureSession childSession = mainSession
+                    .createContentCaptureSession(clientContext);
+            childSessionRef.set(childSession);
+
+            rootView.setContentCaptureSession(childSession);
+            // Already called getContentCaptureSession() earlier, use cached session (main).
+            assertThat(rootView.getContentCaptureSession()).isEqualTo(childSession);
+
+            rootView.setContentCaptureSession(mainSession);
+            assertThat(rootView.getContentCaptureSession()).isEqualTo(mainSession);
+
+            rootView.setContentCaptureSession(childSession);
+            assertThat(rootView.getContentCaptureSession()).isEqualTo(childSession);
+        });
+
+        final LoginActivity activity = launchActivity();
+        watcher.waitFor(RESUMED);
+
+        activity.finish();
+        watcher.waitFor(DESTROYED);
+
+        final ContentCaptureSessionId childSessionId = childSessionRef.get()
+                .getContentCaptureSessionId();
+
+        assertSessionId(childSessionId, activity.getRootView());
+    }
+
+    @Test
     public void testSimpleLifecycle_rootViewSession() throws Exception {
         final CtsContentCaptureService service = enableService();
         final ActivityWatcher watcher = startWatcher();
diff --git a/tests/filesystem/Android.bp b/tests/filesystem/Android.bp
index e091ca3..b60eb94 100644
--- a/tests/filesystem/Android.bp
+++ b/tests/filesystem/Android.bp
@@ -26,7 +26,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/fragment/Android.bp b/tests/fragment/Android.bp
index 30592c2..6ab9eb4 100644
--- a/tests/fragment/Android.bp
+++ b/tests/fragment/Android.bp
@@ -40,7 +40,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     sdk_version: "test_current",
diff --git a/tests/fragment/sdk26/Android.bp b/tests/fragment/sdk26/Android.bp
index 376a034..937a488 100644
--- a/tests/fragment/sdk26/Android.bp
+++ b/tests/fragment/sdk26/Android.bp
@@ -29,7 +29,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     sdk_version: "26",
diff --git a/tests/framework/base/windowmanager/Android.mk b/tests/framework/base/windowmanager/Android.mk
index 0f4ee57..e2823e8 100644
--- a/tests/framework/base/windowmanager/Android.mk
+++ b/tests/framework/base/windowmanager/Android.mk
@@ -43,7 +43,7 @@
     CtsMockInputMethodLib \
     metrics-helper-lib \
 
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := test_current
 
diff --git a/tests/framework/base/windowmanager/alertwindowapp/Android.mk b/tests/framework/base/windowmanager/alertwindowapp/Android.mk
index 28949a0..2ebd50b 100644
--- a/tests/framework/base/windowmanager/alertwindowapp/Android.mk
+++ b/tests/framework/base/windowmanager/alertwindowapp/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceAlertWindowTestApp
 
diff --git a/tests/framework/base/windowmanager/alertwindowappsdk25/Android.mk b/tests/framework/base/windowmanager/alertwindowappsdk25/Android.mk
index 77971f3..c91596a 100644
--- a/tests/framework/base/windowmanager/alertwindowappsdk25/Android.mk
+++ b/tests/framework/base/windowmanager/alertwindowappsdk25/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_SDK_VERSION := 25
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceAlertWindowTestAppSdk25
 
diff --git a/tests/framework/base/windowmanager/alertwindowservice/Android.mk b/tests/framework/base/windowmanager/alertwindowservice/Android.mk
index 686b701..9102afd 100644
--- a/tests/framework/base/windowmanager/alertwindowservice/Android.mk
+++ b/tests/framework/base/windowmanager/alertwindowservice/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_PACKAGE_NAME := CtsAlertWindowService
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_DEX_PREOPT := false
 
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
index 56aa319..5023481 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
@@ -46,6 +46,10 @@
                 "START_ACTIVITY_FROM_FG_ACTIVITY_DELAY_MS_EXTRA";
         public static final String START_ACTIVITY_FROM_FG_ACTIVITY_NEW_TASK_EXTRA =
                 "START_ACTIVITY_FROM_FG_ACTIVITY_NEW_TASK_EXTRA";
+        public static final String LAUNCH_INTENTS_EXTRA = "LAUNCH_INTENTS_EXTRA";
+
+        public static final String ACTION_LAUNCH_BACKGROUND_ACTIVITIES =
+                Components.class.getPackage().getName() + ".ACTION_LAUNCH_BACKGROUND_ACTIVITIES";
     }
 
     /** Extra key constants for {@link #APP_A_SEND_PENDING_INTENT_RECEIVER} */
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
index 377cabf..1413fbc 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
@@ -16,17 +16,25 @@
 
 package android.server.wm.backgroundactivity.appa;
 
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_LAUNCH_BACKGROUND_ACTIVITIES;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_BACKGROUND_ACTIVITY_EXTRA;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_INTENTS_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_SECOND_BACKGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.RELAUNCH_FOREGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.START_ACTIVITY_FROM_FG_ACTIVITY_DELAY_MS_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.START_ACTIVITY_FROM_FG_ACTIVITY_NEW_TASK_EXTRA;
 
 import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.os.Bundle;
+import android.os.Parcelable;
 import android.os.SystemClock;
 
+import java.util.Arrays;
+
 /**
  * Foreground activity that makes AppA as foreground.
  */
@@ -34,6 +42,16 @@
 
     private boolean mRelaunch = false;
 
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            // Need to copy as a new array instead of just casting to Intent[] since a new array of
+            // type Parcelable[] is created when deserializing.
+            Parcelable[] intents = intent.getParcelableArrayExtra(LAUNCH_INTENTS_EXTRA);
+            startActivities(Arrays.copyOf(intents, intents.length, Intent[].class));
+        }
+    };
+
     @Override
     public void onCreate(Bundle bundle) {
         super.onCreate(bundle);
@@ -66,6 +84,7 @@
             newIntent.setClass(this, SecondBackgroundActivity.class);
             startActivity(newIntent);
         }
+        registerReceiver(mReceiver, new IntentFilter(ACTION_LAUNCH_BACKGROUND_ACTIVITIES));
     }
 
     @Override
@@ -78,4 +97,10 @@
             startActivity(getIntent());
         }
     }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        unregisterReceiver(mReceiver);
+    }
 }
diff --git a/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java b/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
index b1a559f..58acf67 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
@@ -30,7 +30,9 @@
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SEND_PENDING_INTENT_RECEIVER;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SIMPLE_ADMIN_RECEIVER;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_START_ACTIVITY_RECEIVER;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_LAUNCH_BACKGROUND_ACTIVITIES;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_BACKGROUND_ACTIVITY_EXTRA;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_INTENTS_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_SECOND_BACKGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.RELAUNCH_FOREGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.START_ACTIVITY_FROM_FG_ACTIVITY_DELAY_MS_EXTRA;
@@ -134,16 +136,15 @@
         assertFalse("Should not able to launch background activity", result);
         assertTaskStack(null, APP_A_BACKGROUND_ACTIVITY);
 
-        // TODO(b/137134312): Bring this back once the stacks leakage issue is fixed
         // Make sure aborting activity starts won't have any empty task/stack leaks.
-        // List<ActivityManagerState.ActivityStack> stacks = mAmWmState.getAmState().getStacks();
-        // for (ActivityManagerState.ActivityStack stack : stacks) {
-        //     assertThat(stack.getTopTask()).isNotNull();
-        //     List<ActivityManagerState.ActivityTask> tasks = stack.getTasks();
-        //     for (ActivityManagerState.ActivityTask task : tasks) {
-        //         assertThat(task.getActivities().size()).isGreaterThan(0);
-        //     }
-        // }
+        List<ActivityManagerState.ActivityStack> stacks = mAmWmState.getAmState().getStacks();
+        for (ActivityManagerState.ActivityStack stack : stacks) {
+            assertThat(stack.getTopTask()).isNotNull();
+            List<ActivityManagerState.ActivityTask> tasks = stack.getTasks();
+            for (ActivityManagerState.ActivityTask task : tasks) {
+                assertThat(task.getActivities().size()).isGreaterThan(0);
+            }
+        }
     }
 
     @Test
@@ -216,9 +217,7 @@
         pressHomeButton();
         mAmWmState.waitForHomeActivityVisible();
 
-        // Any activity launch will be blocked for 5s because of app switching protection.
-        SystemClock.sleep(7000);
-
+        waitToPreventAppSwitchProtection();
         result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
         assertFalse("Previously foreground Activity should not be able to relaunch itself", result);
         result = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
@@ -248,9 +247,7 @@
         pressHomeButton();
         mAmWmState.waitForHomeActivityVisible();
 
-        // Any activity launch will be blocked for 5s because of app switching protection.
-        SystemClock.sleep(7000);
-
+        waitToPreventAppSwitchProtection();
         result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
         assertFalse("Previously foreground Activity should not be able to relaunch itself", result);
         result = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
@@ -276,9 +273,7 @@
         pressHomeButton();
         mAmWmState.waitForHomeActivityVisible();
 
-        // Any activity launch will be blocked for 5s because of app switching protection.
-        SystemClock.sleep(5000);
-
+        waitToPreventAppSwitchProtection();
         result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
         assertFalse("Previously foreground Activity should not be able to relaunch itself", result);
         assertTaskStack(new ComponentName[]{APP_A_FOREGROUND_ACTIVITY}, APP_A_FOREGROUND_ACTIVITY);
@@ -306,6 +301,39 @@
     }
 
     @Test
+    public void testSecondActivityBlockedWhenBackgroundActivityLaunch() throws Exception {
+        Intent baseActivityIntent = new Intent();
+        baseActivityIntent.setComponent(APP_A_FOREGROUND_ACTIVITY);
+        baseActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(baseActivityIntent);
+        boolean result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
+        assertTrue("Not able to start foreground activity", result);
+        assertTaskStack(new ComponentName[]{APP_A_FOREGROUND_ACTIVITY}, APP_A_FOREGROUND_ACTIVITY);
+        pressHomeButton();
+        mAmWmState.waitForHomeActivityVisible();
+        waitToPreventAppSwitchProtection();
+
+        // The activity, now in the background, will attempt to start 2 activities in quick
+        // succession
+        Intent broadcastIntent = new Intent(ACTION_LAUNCH_BACKGROUND_ACTIVITIES);
+        Intent bgActivity1 = new Intent();
+        bgActivity1.setComponent(APP_A_BACKGROUND_ACTIVITY);
+        Intent bgActivity2 = new Intent();
+        bgActivity2.setComponent(APP_A_SECOND_BACKGROUND_ACTIVITY);
+        broadcastIntent.putExtra(LAUNCH_INTENTS_EXTRA, new Intent[]{bgActivity1, bgActivity2});
+        mContext.sendBroadcast(broadcastIntent);
+
+        // There should be 2 activities in the background (not focused) INITIALIZING
+        result = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
+        assertFalse("Activity should not have been launched in the foreground", result);
+        result = waitForActivityFocused(APP_A_SECOND_BACKGROUND_ACTIVITY);
+        assertFalse("Second activity should not have been launched in the foreground", result);
+        assertTaskStack(
+                new ComponentName[]{APP_A_SECOND_BACKGROUND_ACTIVITY, APP_A_BACKGROUND_ACTIVITY,
+                        APP_A_FOREGROUND_ACTIVITY}, APP_A_FOREGROUND_ACTIVITY);
+    }
+
+    @Test
     public void testPendingIntentActivityBlocked() throws Exception {
         // Cannot start activity by pending intent, as both appA and appB are in background
         sendPendingIntentActivity();
@@ -399,6 +427,11 @@
         assertTaskStack(new ComponentName[]{APP_A_BACKGROUND_ACTIVITY}, APP_A_BACKGROUND_ACTIVITY);
     }
 
+    private void waitToPreventAppSwitchProtection() {
+        // Any activity launch will be blocked for 5s because of app switching protection.
+        SystemClock.sleep(7000);
+    }
+
     private void assertTaskStack(ComponentName[] expectedComponents,
             ComponentName sourceComponent) {
         if (expectedComponents == null) {
diff --git a/tests/framework/base/windowmanager/dndsourceapp/Android.mk b/tests/framework/base/windowmanager/dndsourceapp/Android.mk
index f40ccb6..c793075 100644
--- a/tests/framework/base/windowmanager/dndsourceapp/Android.mk
+++ b/tests/framework/base/windowmanager/dndsourceapp/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := cts-wm-app-base
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDragAndDropSourceApp
 
diff --git a/tests/framework/base/windowmanager/dndtargetapp/Android.mk b/tests/framework/base/windowmanager/dndtargetapp/Android.mk
index b29f7da..195b39d 100644
--- a/tests/framework/base/windowmanager/dndtargetapp/Android.mk
+++ b/tests/framework/base/windowmanager/dndtargetapp/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := cts-wm-app-base
 
diff --git a/tests/framework/base/windowmanager/dndtargetappsdk23/Android.mk b/tests/framework/base/windowmanager/dndtargetappsdk23/Android.mk
index b1fb35b..9d623a8 100644
--- a/tests/framework/base/windowmanager/dndtargetappsdk23/Android.mk
+++ b/tests/framework/base/windowmanager/dndtargetappsdk23/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SDK_VERSION := 23
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := cts-wm-app-base
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/ActivityManagerGetConfigTests.java b/tests/framework/base/windowmanager/src/android/server/wm/ActivityManagerGetConfigTests.java
index fe30e1a..8895b62 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/ActivityManagerGetConfigTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/ActivityManagerGetConfigTests.java
@@ -251,16 +251,11 @@
         assertEquals("Expected mnc does not match",
                 config.mnc, resConfig.configuration.mnc);
         LocaleList llist = config.getLocales();
-        LocaleProto[] lprotos = resConfig.configuration.locales;
-        assertEquals("Expected number of locales does not match",
-                llist.size(), lprotos.length);
+        LocaleList lprotos = LocaleList.forLanguageTags(resConfig.configuration.localeList);
+        assertEquals("Expected number of locales does not match", llist.size(), lprotos.size());
         for (int i = 0; i < llist.size(); i++) {
-            assertEquals("Expected locale #" + i + " language does not match",
-                    llist.get(i).getLanguage(), lprotos[i].language);
-            assertEquals("Expected locale #" + i + " country does not match",
-                    llist.get(i).getCountry(), lprotos[i].country);
-            assertEquals("Expected locale #" + i + " variant does not match",
-                    llist.get(i).getVariant(), lprotos[i].variant);
+            assertEquals("Expected locale #" + i + " does not match",
+                    llist.get(i).toLanguageTag(), lprotos.get(i).toLanguageTag());
         }
         assertEquals("Expected screen layout does not match",
                 config.screenLayout, resConfig.configuration.screenLayout);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AnimationBackgroundTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AnimationBackgroundTests.java
deleted file mode 100644
index b9de595..0000000
--- a/tests/framework/base/windowmanager/src/android/server/wm/AnimationBackgroundTests.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.server.wm;
-
-import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
-import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
-import static android.server.wm.app.Components.ANIMATION_TEST_ACTIVITY;
-import static android.server.wm.app.Components.LAUNCHING_ACTIVITY;
-import static android.view.Display.DEFAULT_DISPLAY;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeFalse;
-
-import android.content.ComponentName;
-import android.platform.test.annotations.Presubmit;
-import android.server.wm.WindowManagerState.Display;
-
-import org.junit.Test;
-
-/**
- * Build/Install/Run:
- *     atest CtsWindowManagerDeviceTestCases:AnimationBackgroundTests
- */
-@Presubmit
-public class AnimationBackgroundTests extends ActivityManagerTestBase {
-
-    @Test
-    public void testAnimationBackground_duringAnimation() throws Exception {
-        launchActivityOnDisplay(LAUNCHING_ACTIVITY, DEFAULT_DISPLAY);
-        getLaunchActivityBuilder()
-                .setTargetActivity(ANIMATION_TEST_ACTIVITY)
-                .setWaitForLaunched(false)
-                .execute();
-
-        // Make sure we're testing an activity that runs on fullscreen display. This animation API
-        // doesn't make much sense in freeform displays.
-        assumeActivityNotInFreeformDisplay(ANIMATION_TEST_ACTIVITY);
-
-        // Make sure we are in the middle of the animation.
-        assertTrue("window animation background needs to be showing",
-                mAmWmState.waitForWithWmState(state -> state
-                        .getStandardStackByWindowingMode(WINDOWING_MODE_FULLSCREEN)
-                        .isWindowAnimationBackgroundSurfaceShowing(),
-                        "animation background showing"));
-    }
-
-    @Test
-    public void testAnimationBackground_gone() throws Exception {
-        launchActivityOnDisplay(LAUNCHING_ACTIVITY, DEFAULT_DISPLAY);
-        getLaunchActivityBuilder().setTargetActivity(ANIMATION_TEST_ACTIVITY).execute();
-        mAmWmState.computeState(ANIMATION_TEST_ACTIVITY);
-        mAmWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY);
-
-        // Make sure we're testing an activity that runs on fullscreen display. This animation API
-        // doesn't make much sense in freeform displays.
-        assumeActivityNotInFreeformDisplay(ANIMATION_TEST_ACTIVITY);
-
-        assertFalse("window animation background needs to be gone", mAmWmState.getWmState()
-                .getStandardStackByWindowingMode(WINDOWING_MODE_FULLSCREEN)
-                .isWindowAnimationBackgroundSurfaceShowing());
-    }
-
-    private void assumeActivityNotInFreeformDisplay(ComponentName activity) throws Exception {
-        mAmWmState.waitForValidState(activity);
-        final int displayId = mAmWmState.getAmState().getDisplayByActivity(activity);
-        final Display display = mAmWmState.getWmState().getDisplay(displayId);
-        assumeFalse("Animation test activity is in freeform display. It may not run "
-                + "cross-task animations.", display.getWindowingMode() == WINDOWING_MODE_FREEFORM);
-    }
-}
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
index 2056380..9fffd6b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
@@ -256,7 +256,7 @@
         // Resize docked stack to fullscreen size. This will trigger activity relaunch with
         // non-empty override configuration corresponding to fullscreen size.
         separateTestJournal();
-        resizeStack(stack.mStackId, displayRect.left, displayRect.top, displayRect.width(),
+        resizeDockedStack(displayRect.left, displayRect.top, displayRect.width(),
                 displayRect.height());
 
         // Move activity back to fullscreen stack.
@@ -302,7 +302,7 @@
         final int smallWidthPx = dpToPx(SMALL_WIDTH_DP, density);
         final int smallHeightPx = dpToPx(SMALL_HEIGHT_DP, density);
 
-        resizeStack(stack.mStackId, 0, 0, smallWidthPx, smallHeightPx);
+        resizeDockedStack(0, 0, smallWidthPx, smallHeightPx);
         mAmWmState.waitForValidState(
                 new WaitForValidActivityState.Builder(DIALOG_WHEN_LARGE_ACTIVITY)
                         .setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY)
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPrivateDisplayTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPrivateDisplayTests.java
new file mode 100644
index 0000000..ee278d8
--- /dev/null
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPrivateDisplayTests.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.server.wm;
+
+import static android.server.wm.app.Components.LAUNCH_BROADCAST_RECEIVER;
+import static android.server.wm.app.Components.LaunchBroadcastReceiver.LAUNCH_BROADCAST_ACTION;
+import static android.server.wm.app.Components.TEST_ACTIVITY;
+import static android.view.Display.FLAG_PRIVATE;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeFalse;
+import static org.junit.Assume.assumeTrue;
+
+import android.app.ActivityManager;
+import android.content.Context;
+import android.content.Intent;
+import android.platform.test.annotations.Presubmit;
+import android.server.wm.ActivityManagerState.ActivityDisplay;
+import android.server.wm.TestJournalProvider.TestJournalContainer;
+import android.server.wm.WindowManagerState.Display;
+import android.util.Log;
+import android.view.View;
+
+import com.android.compatibility.common.util.SystemUtil;
+
+import java.util.ArrayList;
+
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Build/Install/Run:
+ *     atest CtsWindowManagerDeviceTestCases:MultiDisplayPrivateDisplayTests
+ *
+ * Tests if be allowed to launch/access an activity on private display
+ * in multi-display environment.
+ */
+@Presubmit
+public class MultiDisplayPrivateDisplayTests extends MultiDisplayTestBase {
+    private static final String TAG = "MultiDisplayPrivateDisplayTests";
+    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+    private static final String INTERNAL_SYSTEM_WINDOW =
+            "android.permission.INTERNAL_SYSTEM_WINDOW";
+    private ArrayList<Integer> mPrivateDisplayIds = new ArrayList<>();
+
+    @Before
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        assumeTrue(supportsMultiDisplay());
+        findPrivateDisplays();
+        assumeFalse("Skipping test: no physical private display found.",
+                mPrivateDisplayIds.isEmpty());
+    }
+
+    /** Saves physical private displays in mPrivateDisplayIds */
+    private void findPrivateDisplays() {
+        mPrivateDisplayIds.clear();
+        mAmWmState.computeState(true);
+
+        for (ActivityDisplay activityDisplay: getDisplaysStates()) {
+            int displayId = activityDisplay.mId;
+            Display display = mAmWmState.getWmState().getDisplay(displayId);
+            if ((display.getFlags() & FLAG_PRIVATE) != 0) {
+                mPrivateDisplayIds.add(displayId);
+            }
+        }
+    }
+
+    /**
+     * Tests launching an activity on a private display without special permission must not be
+     * allowed.
+     */
+    @Test
+    public void testCantLaunchOnPrivateDisplay() throws Exception {
+        // try on each private display
+        for (int displayId: mPrivateDisplayIds) {
+            separateTestJournal();
+
+            getLaunchActivityBuilder()
+                .setDisplayId(displayId)
+                .setTargetActivity(TEST_ACTIVITY)
+                .execute();
+
+            assertSecurityExceptionFromActivityLauncher();
+
+            mAmWmState.computeState(TEST_ACTIVITY);
+            assertFalse("Activity must not be launched on a private display",
+                mAmWmState.getAmState().containsActivity(TEST_ACTIVITY));
+        }
+    }
+
+    /**
+     * Tests
+     * {@link android.app.ActivityManager#isActivityStartAllowedOnDisplay(Context, int, Intent)}
+     * call to start an activity on private display is not allowed without special permission
+     */
+    @Test
+    public void testCantAccessPrivateDisplay() throws Exception {
+        final ActivityManager activityManager =
+            (ActivityManager) mTargetContext.getSystemService(Context.ACTIVITY_SERVICE);
+        final Intent intent = new Intent(Intent.ACTION_VIEW).setComponent(TEST_ACTIVITY);
+
+        for (int displayId: mPrivateDisplayIds) {
+            assertFalse(activityManager.isActivityStartAllowedOnDisplay(mTargetContext,
+                displayId, intent));
+        }
+    }
+
+    /**
+     * Tests
+     * {@link android.app.ActivityManager#isActivityStartAllowedOnDisplay(Context, int, Intent)}
+     * for a private display with INTERNAL_SYSTEM_WINDOW permission.
+     */
+    @Test
+    public void testCanAccessPrivateDisplayWithInternalPermission() throws Exception {
+        final ActivityManager activityManager =
+            (ActivityManager) mTargetContext.getSystemService(Context.ACTIVITY_SERVICE);
+        final Intent intent = new Intent(Intent.ACTION_VIEW)
+            .setComponent(TEST_ACTIVITY);
+
+        for (int displayId: mPrivateDisplayIds) {
+            SystemUtil.runWithShellPermissionIdentity(() ->
+                assertTrue(activityManager.isActivityStartAllowedOnDisplay(mTargetContext,
+                    displayId, intent)), INTERNAL_SYSTEM_WINDOW);
+        }
+    }
+}
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySecurityTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySecurityTests.java
index 46101f5..9ff341c 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySecurityTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySecurityTests.java
@@ -687,11 +687,6 @@
         }
     }
 
-    private static void assertSecurityExceptionFromActivityLauncher() {
-        waitForOrFail("SecurityException from " + ActivityLauncher.TAG,
-                ActivityLauncher::hasCaughtSecurityException);
-    }
-
     /**
      * Test that only private virtual display can show content with insecure keyguard.
      */
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java
index afd6ab9..0bc7fa9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayTestBase.java
@@ -247,6 +247,11 @@
         });
     }
 
+    void assertSecurityExceptionFromActivityLauncher() {
+        waitForOrFail("SecurityException from " + ActivityLauncher.TAG,
+            ActivityLauncher::hasCaughtSecurityException);
+    }
+
     /**
      * This class should only be used when you need to test virtual display created by a
      * non-privileged app.
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
index d6e8b3f..96649f9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
@@ -16,6 +16,7 @@
 
 package android.server.wm;
 
+import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
 import static android.app.ActivityTaskManager.INVALID_STACK_ID;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
@@ -290,7 +291,7 @@
         final int stackId = getPinnedStack().mStackId;
         final int top = 0;
         final int left = displayRect.width() - 200;
-        resizeStack(stackId, left, top, left + 500, top + 500);
+        resizePinnedStack(stackId, left, top, left + 500, top + 500);
 
         // Ensure that the surface insets are not negative
         windowState = getWindowState(PIP_ACTIVITY);
@@ -790,7 +791,6 @@
         assertPinnedStackExists();
     }
 
-    @FlakyTest(bugId = 139111392)
     @Test
     public void testDisallowEnterPipActivityLocked() throws Exception {
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP_ON_PAUSE, "true");
@@ -802,6 +802,9 @@
         SystemUtil.runWithShellPermissionIdentity(() -> {
             try {
                 mAtm.startSystemLockTaskMode(task.mTaskId);
+                waitForOrFail("Task in lock mode", () -> {
+                    return mAm.getLockTaskModeState() != LOCK_TASK_MODE_NONE;
+                });
                 mBroadcastActionTrigger.doAction(ACTION_ENTER_PIP);
                 waitForEnterPip(PIP_ACTIVITY);
                 assertPinnedStackDoesNotExist();
@@ -1010,7 +1013,8 @@
         // got resumed.
         separateTestJournal();
         SystemUtil.runWithShellPermissionIdentity(
-                () -> mAtm.resizeStack(stackId, new Rect(20, 20, 500, 500), true /* animate */));
+                () -> mAtm.resizePinnedStack(stackId, new Rect(20, 20, 500, 500),
+                        true /* animate */));
         mBroadcastActionTrigger.doAction(TEST_ACTIVITY_ACTION_FINISH_SELF);
         mAmWmState.waitFor((amState, wmState) ->
                         !amState.containsActivity(TRANSLUCENT_TEST_ACTIVITY),
@@ -1264,7 +1268,7 @@
         } else {
             offsetBoundsOut.offset(0, -offsetY);
         }
-        resizeStack(stack.mStackId, offsetBoundsOut.left, offsetBoundsOut.top,
+        resizePinnedStack(stack.mStackId, offsetBoundsOut.left, offsetBoundsOut.top,
                 offsetBoundsOut.right, offsetBoundsOut.bottom);
     }
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/TransitionSelectionTests.java b/tests/framework/base/windowmanager/src/android/server/wm/TransitionSelectionTests.java
index 2a04d2e..14a7059 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/TransitionSelectionTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/TransitionSelectionTests.java
@@ -39,8 +39,6 @@
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 
-import androidx.test.filters.FlakyTest;
-
 import org.junit.Assume;
 import org.junit.Before;
 import org.junit.Test;
@@ -187,7 +185,6 @@
                 true /*slowStop*/, TRANSIT_WALLPAPER_OPEN);
     }
 
-    @FlakyTest(bugId = 139111132)
     @Test
     public void testCloseTask_BothWallpaper_SlowStop() {
         testCloseTask(true /*bottomWallpaper*/, true /*topWallpaper*/,
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java
index 2fcafd8..0d0278e 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java
@@ -37,7 +37,6 @@
 import android.content.Intent;
 import android.platform.test.annotations.Presubmit;
 
-import androidx.test.filters.FlakyTest;
 import androidx.test.filters.MediumTest;
 
 import org.junit.Before;
@@ -248,7 +247,6 @@
     }
 
     @Test
-    @FlakyTest(bugId = 127741025)
     public void testPipAboveSplitScreen() throws Exception {
         // Launch first activity
         final Activity firstActivity =
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
index 8a4fbaf..5ec2c11 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
@@ -97,6 +97,9 @@
         thirdIntent.setFlags(FLAG_ACTIVITY_MULTIPLE_TASK | FLAG_ACTIVITY_NEW_TASK);
         mThirdActivityTestRule.launchActivity(thirdIntent);
 
+        // Wait for SecondActivity in primary split screen leave minimize dock.
+        waitAndAssertActivityStates(state(secondActivity, ON_RESUME));
+
         // Finish top activity
         secondActivity.finish();
 
@@ -112,7 +115,6 @@
     }
 
     @Test
-    @FlakyTest(bugId = 127741025)
     public void testOccludingMovedBetweenStacks() throws Exception {
         // Launch first activity
         final Activity firstActivity =
@@ -359,8 +361,7 @@
         waitForActivityTransitions(CallbackTrackingActivity.class, expectedEnterSequence);
         LifecycleVerifier.assertOrder(getLifecycleLog(), CallbackTrackingActivity.class,
                 Arrays.asList(ON_TOP_POSITION_LOST, ON_PAUSE, ON_STOP, ON_DESTROY, ON_CREATE,
-                        ON_RESUME, ON_TOP_POSITION_GAINED, ON_TOP_POSITION_LOST),
-                "moveToSplitScreen");
+                        ON_RESUME), "moveToSplitScreen");
         LifecycleVerifier.assertTransitionObserved(getLifecycleLog(),
                 transition(CallbackTrackingActivity.class, ON_MULTI_WINDOW_MODE_CHANGED),
                 "moveToSplitScreen");
@@ -401,9 +402,9 @@
 
         // Wait for the activity to receive the change
         waitForActivityTransitions(ConfigChangeHandlingActivity.class,
-                Arrays.asList(ON_MULTI_WINDOW_MODE_CHANGED, ON_TOP_POSITION_LOST));
+                Arrays.asList(ON_TOP_POSITION_LOST, ON_MULTI_WINDOW_MODE_CHANGED));
         LifecycleVerifier.assertOrder(getLifecycleLog(), ConfigChangeHandlingActivity.class,
-                Arrays.asList(ON_MULTI_WINDOW_MODE_CHANGED, ON_TOP_POSITION_LOST),
+                Arrays.asList(ON_TOP_POSITION_LOST, ON_MULTI_WINDOW_MODE_CHANGED),
                 "moveToSplitScreen");
 
         // Exit split-screen
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java
index 7d0b4b30..fd63fd0 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java
@@ -16,6 +16,7 @@
 
 package android.server.wm.lifecycle;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
 import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
 import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
@@ -1092,8 +1093,21 @@
 
         // Wait and assert lifecycle
         waitAndAssertActivityStates(state(pipActivity, ON_PAUSE));
-        // PipMenuActivity will start and briefly get the top position, so we ignore the rest
-        // of the possibilities.
+
+        // The PipMenuActivity could start anytime after moving pipActivity to pinned stack,
+        // however, we cannot control when would it start or finish, so this test could fail when
+        // PipMenuActivity just start and pipActivity call finish almost at the same time.
+        // So the strategy here is to wait the PipMenuActivity start and finish after pipActivity
+        // moved to pinned stack and paused, because pipActivity is not focusable but the
+        // PipMenuActivity is focusable, when the pinned stack gain top focus means the
+        // PipMenuActivity is launched and resumed, then when pinned stack lost top focus means the
+        // PipMenuActivity is finished.
+        mAmWmState.waitWindowingModeTopFocus(WINDOWING_MODE_PINNED, true /* topFocus */
+                , "wait PipMenuActivity get top focus");
+        mAmWmState.waitWindowingModeTopFocus(WINDOWING_MODE_PINNED, false /* topFocus */
+                , "wait PipMenuActivity lost top focus");
+        waitAndAssertActivityStates(state(activity, ON_TOP_POSITION_GAINED));
+
         LifecycleVerifier.assertOrder(getLifecycleLog(), Arrays.asList(
                 transition(CallbackTrackingActivity.class, ON_TOP_POSITION_LOST),
                 transition(CallbackTrackingActivity.class, ON_PAUSE),
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityAndWindowManagersState.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityAndWindowManagersState.java
index 928d618..d50bed9 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityAndWindowManagersState.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityAndWindowManagersState.java
@@ -324,6 +324,14 @@
         return waitFor((amState, wmState) -> waitCondition.test(wmState), message);
     }
 
+    public void waitWindowingModeTopFocus(int windowingMode, boolean topFocus, String message) {
+        waitForWithAmState(amState -> {
+            final ActivityStack stack = amState.getStandardStackByWindowingMode(windowingMode);
+            return stack != null
+                    && topFocus == (amState.getFocusedStackId() == stack.getStackId());
+        }, message);
+    }
+
     /** @return {@code true} if the wait is successful; {@code false} if timeout occurs. */
     boolean waitFor(
             BiPredicate<ActivityManagerState, WindowManagerState> waitCondition, String message) {
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index f9c66f7..9dd20e2 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -782,10 +782,10 @@
                         new Rect(0, 0, taskWidth, taskHeight)));
     }
 
-    protected void resizeStack(int stackId, int stackLeft, int stackTop, int stackWidth,
-            int stackHeight) {
-        SystemUtil.runWithShellPermissionIdentity(() -> mAtm.resizeStack(stackId,
-                new Rect(stackLeft, stackTop, stackWidth, stackHeight)));
+    protected void resizePinnedStack(
+            int stackId, int stackLeft, int stackTop, int stackWidth, int stackHeight) {
+        SystemUtil.runWithShellPermissionIdentity(() -> mAtm.resizePinnedStack(stackId,
+                new Rect(stackLeft, stackTop, stackWidth, stackHeight), false /* animate */));
     }
 
     protected void pressAppSwitchButtonAndWaitForRecents() {
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
index 2af720d..139af1e 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
@@ -609,7 +609,6 @@
 
         int mStackId;
         ArrayList<WindowTask> mTasks = new ArrayList<>();
-        boolean mWindowAnimationBackgroundSurfaceShowing;
         boolean mAnimatingBounds;
 
         WindowStack(StackProto proto) {
@@ -623,7 +622,6 @@
                 mTasks.add(task);
                 mSubWindows.addAll(task.getWindows());
             }
-            mWindowAnimationBackgroundSurfaceShowing = proto.animationBackgroundSurfaceIsDimming;
             mAnimatingBounds = proto.animatingBounds;
         }
 
@@ -635,10 +633,6 @@
             }
             return null;
         }
-
-        boolean isWindowAnimationBackgroundSurfaceShowing() {
-            return mWindowAnimationBackgroundSurfaceShowing;
-        }
     }
 
     static class WindowTask extends WindowContainer {
@@ -737,6 +731,7 @@
         private Rect mDisplayRect = new Rect();
         private Rect mAppRect = new Rect();
         private int mDpi;
+        private int mFlags;
         private Rect mStableBounds;
         private String mName;
         private int mSurfaceSize;
@@ -762,6 +757,7 @@
                 mDisplayRect.set(0, 0, infoProto.logicalWidth, infoProto.logicalHeight);
                 mAppRect.set(0, 0, infoProto.appWidth, infoProto.appHeight);
                 mName = infoProto.name;
+                mFlags = infoProto.flags;
             }
             final DisplayFramesProto displayFramesProto = proto.displayFrames;
             if (displayFramesProto != null) {
@@ -810,6 +806,10 @@
             return mName;
         }
 
+        int getFlags() {
+            return mFlags;
+        }
+
         int getSurfaceSize() {
             return mSurfaceSize;
         }
@@ -825,7 +825,7 @@
         @Override
         public String toString() {
             return "Display #" + mDisplayId + ": name=" + mName + " mDisplayRect=" + mDisplayRect
-                    + " mAppRect=" + mAppRect;
+                + " mAppRect=" + mAppRect + " mFlags=" + mFlags;
         }
     }
 
diff --git a/tests/inputmethod/Android.bp b/tests/inputmethod/Android.bp
index 1309bcb..53f0d05 100644
--- a/tests/inputmethod/Android.bp
+++ b/tests/inputmethod/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     compile_multilib: "both",
     libs: ["android.test.runner.stubs"],
diff --git a/tests/inputmethod/mockime/Android.bp b/tests/inputmethod/mockime/Android.bp
index 1b687645..42f057a 100644
--- a/tests/inputmethod/mockime/Android.bp
+++ b/tests/inputmethod/mockime/Android.bp
@@ -41,7 +41,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     static_libs: [
         "androidx.annotation_annotation",
diff --git a/tests/pdf/Android.bp b/tests/pdf/Android.bp
index dc589ee..1700e49 100644
--- a/tests/pdf/Android.bp
+++ b/tests/pdf/Android.bp
@@ -31,7 +31,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/sample/Android.bp b/tests/sample/Android.bp
index 8f0c264..40a04b0 100644
--- a/tests/sample/Android.bp
+++ b/tests/sample/Android.bp
@@ -35,7 +35,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/security/src/android/keystore/cts/Attestation.java b/tests/security/src/android/keystore/cts/Attestation.java
index bdfe00a..2285cad 100644
--- a/tests/security/src/android/keystore/cts/Attestation.java
+++ b/tests/security/src/android/keystore/cts/Attestation.java
@@ -17,12 +17,15 @@
 package android.keystore.cts;
 
 import com.google.common.base.CharMatcher;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.io.BaseEncoding;
 
 import org.bouncycastle.asn1.ASN1Sequence;
 
 import java.security.cert.CertificateParsingException;
 import java.security.cert.X509Certificate;
+import java.util.Set;
+import java.util.stream.Collectors;
 
 /**
  * Parses an attestation certificate and provides an easy-to-use interface for examining the
@@ -30,6 +33,7 @@
  */
 public class Attestation {
     static final String KEY_DESCRIPTION_OID = "1.3.6.1.4.1.11129.2.1.17";
+    static final String KEY_USAGE_OID = "2.5.29.15";  // Standard key usage extension.
     static final int ATTESTATION_VERSION_INDEX = 0;
     static final int ATTESTATION_SECURITY_LEVEL_INDEX = 1;
     static final int KEYMASTER_VERSION_INDEX = 2;
@@ -51,6 +55,7 @@
     private final byte[] uniqueId;
     private final AuthorizationList softwareEnforced;
     private final AuthorizationList teeEnforced;
+    private final Set<String> unexpectedExtensionOids;
 
 
     /**
@@ -62,6 +67,7 @@
      */
     public Attestation(X509Certificate x509Cert) throws CertificateParsingException {
         ASN1Sequence seq = getAttestationSequence(x509Cert);
+        unexpectedExtensionOids = retrieveUnexpectedExtensionOids(x509Cert);
 
         attestationVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_VERSION_INDEX));
         attestationSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_SECURITY_LEVEL_INDEX));
@@ -122,6 +128,10 @@
         return teeEnforced;
     }
 
+    public Set<String> getUnexpectedExtensionOids() {
+        return unexpectedExtensionOids;
+    }
+
     @Override
     public String toString() {
         StringBuilder s = new StringBuilder();
@@ -159,4 +169,16 @@
         return Asn1Utils.getAsn1SequenceFromBytes(attestationExtensionBytes);
     }
 
+    private Set<String> retrieveUnexpectedExtensionOids(X509Certificate x509Cert) {
+        return new ImmutableSet.Builder<String>()
+                .addAll(x509Cert.getCriticalExtensionOIDs()
+                        .stream()
+                        .filter(s -> !KEY_USAGE_OID.equals(s))
+                        .iterator())
+                .addAll(x509Cert.getNonCriticalExtensionOIDs()
+                        .stream()
+                        .filter(s -> !KEY_DESCRIPTION_OID.equals(s))
+                        .iterator())
+                .build();
+    }
 }
diff --git a/tests/sensor/OWNERS b/tests/sensor/OWNERS
index 90f4119..c0f3c7b 100644
--- a/tests/sensor/OWNERS
+++ b/tests/sensor/OWNERS
@@ -1,3 +1,4 @@
 # Bug component: 62965
+arthuri@google.com
 bduddie@google.com
-bstack@google.com
\ No newline at end of file
+stange@google.com
diff --git a/tests/signature/api-check/system-annotation/AndroidTest.xml b/tests/signature/api-check/system-annotation/AndroidTest.xml
index 70db574..63f324d 100644
--- a/tests/signature/api-check/system-annotation/AndroidTest.xml
+++ b/tests/signature/api-check/system-annotation/AndroidTest.xml
@@ -30,4 +30,8 @@
         <option name="instrumentation-arg" key="annotation-for-exact-match" value="android.annotation.SystemApi" />
         <option name="runtime-hint" value="30s" />
     </test>
+
+    <!-- Controller that will skip the module if a native bridge situation is detected -->
+    <!-- For example: module wants to run arm32 and device is x86 -->
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.NativeBridgeModuleController" />
 </configuration>
diff --git a/tests/tests/accounts/Android.bp b/tests/tests/accounts/Android.bp
index 94f7c79..eb8772b 100644
--- a/tests/tests/accounts/Android.bp
+++ b/tests/tests/accounts/Android.bp
@@ -33,6 +33,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp
index a9bc0e8..707d214 100644
--- a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp
+++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp
@@ -28,7 +28,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     certificate: ":cts-testkey2",
 }
diff --git a/tests/tests/animation/Android.bp b/tests/tests/animation/Android.bp
index d199cc2..20bffd4 100644
--- a/tests/tests/animation/Android.bp
+++ b/tests/tests/animation/Android.bp
@@ -33,7 +33,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     sdk_version: "test_current",
diff --git a/tests/tests/app.usage/Android.bp b/tests/tests/app.usage/Android.bp
index d249a76..a75225d 100644
--- a/tests/tests/app.usage/Android.bp
+++ b/tests/tests/app.usage/Android.bp
@@ -34,6 +34,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/app.usage/TestApp1/Android.bp b/tests/tests/app.usage/TestApp1/Android.bp
index fc09db7..1f866b7 100644
--- a/tests/tests/app.usage/TestApp1/Android.bp
+++ b/tests/tests/app.usage/TestApp1/Android.bp
@@ -34,6 +34,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/appenumeration/AndroidTest.xml b/tests/tests/appenumeration/AndroidTest.xml
index 8f6d37b..eb77b32 100644
--- a/tests/tests/appenumeration/AndroidTest.xml
+++ b/tests/tests/appenumeration/AndroidTest.xml
@@ -24,10 +24,16 @@
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsAppEnumerationTestCases.apk" />
-        <option name="test-file-name" value="CtsAppEnumerationForceQueryableApp.apk" />
-        <option name="test-file-name" value="CtsAppEnumerationFiltersApp.apk" />
-        <option name="test-file-name" value="CtsAppEnumerationNoApiApp.apk" />
-        <option name="test-file-name" value="CtsAppEnumerationQueriesNothingApp.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationForceQueryable.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationFilters.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationNoApi.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesNothing.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesActivityViaAction.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesServiceViaAction.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesProviderViaAuthority.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesPackage.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesNothingTargetsQ.apk" />
+        <option name="test-file-name" value="CtsAppEnumerationQueriesNothingHasPermission.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.appenumeration.cts" />
diff --git a/tests/tests/appenumeration/app/source/Android.bp b/tests/tests/appenumeration/app/source/Android.bp
index 8919822..1d23254 100644
--- a/tests/tests/appenumeration/app/source/Android.bp
+++ b/tests/tests/appenumeration/app/source/Android.bp
@@ -13,7 +13,7 @@
 // limitations under the License.
 
 android_test_helper_app {
-    name: "CtsAppEnumerationQueriesNothingApp",
+    name: "CtsAppEnumerationQueriesNothing",
     manifest: "AndroidManifest-queriesNothing.xml",
     defaults: ["cts_support_defaults"],
     srcs: ["src/**/*.java"],
@@ -24,4 +24,88 @@
         "general-tests",
     ],
     sdk_version: "test_current",
+}
+
+android_test_helper_app {
+    name: "CtsAppEnumerationQueriesActivityViaAction",
+    manifest: "AndroidManifest-queriesActivityAction.xml",
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
+
+android_test_helper_app {
+    name: "CtsAppEnumerationQueriesServiceViaAction",
+    manifest: "AndroidManifest-queriesServiceAction.xml",
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
+
+android_test_helper_app {
+    name: "CtsAppEnumerationQueriesProviderViaAuthority",
+    manifest: "AndroidManifest-queriesProviderAuthority.xml",
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
+
+android_test_helper_app {
+    name: "CtsAppEnumerationQueriesPackage",
+    manifest: "AndroidManifest-queriesPackage.xml",
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
+
+android_test_helper_app {
+    name: "CtsAppEnumerationQueriesNothingTargetsQ",
+    manifest: "AndroidManifest-queriesNothing-targetsQ.xml",
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
+
+android_test_helper_app {
+    name: "CtsAppEnumerationQueriesNothingHasPermission",
+    manifest: "AndroidManifest-queriesNothing-hasPermission.xml",
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
 }
\ No newline at end of file
diff --git a/tests/tests/appenumeration/app/source/AndroidManifest-queriesActivityAction.xml b/tests/tests/appenumeration/app/source/AndroidManifest-queriesActivityAction.xml
new file mode 100644
index 0000000..2eba524
--- /dev/null
+++ b/tests/tests/appenumeration/app/source/AndroidManifest-queriesActivityAction.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.appenumeration.queries.activity.action">
+
+    <queries>
+        <intent>
+            <action android:name="android.appenumeration.action.ACTIVITY" />
+        </intent>
+    </queries>
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.appenumeration.cts.query.TestActivity"
+                  android:exported="true" />
+    </application>
+</manifest>
diff --git a/tests/tests/appenumeration/app/source/AndroidManifest-queriesNothing-hasPermission.xml b/tests/tests/appenumeration/app/source/AndroidManifest-queriesNothing-hasPermission.xml
new file mode 100644
index 0000000..09c75ae
--- /dev/null
+++ b/tests/tests/appenumeration/app/source/AndroidManifest-queriesNothing-hasPermission.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.appenumeration.queries.nothing.haspermission">
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.appenumeration.cts.query.TestActivity"
+                  android:exported="true" />
+    </application>
+</manifest>
diff --git a/tests/tests/appenumeration/app/source/AndroidManifest-queriesNothing-targetsQ.xml b/tests/tests/appenumeration/app/source/AndroidManifest-queriesNothing-targetsQ.xml
new file mode 100644
index 0000000..2810c87
--- /dev/null
+++ b/tests/tests/appenumeration/app/source/AndroidManifest-queriesNothing-targetsQ.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.appenumeration.queries.nothing.q">
+    <uses-sdk android:targetSdkVersion="29" />
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.appenumeration.cts.query.TestActivity"
+                  android:exported="true" />
+    </application>
+</manifest>
diff --git a/tests/tests/appenumeration/app/source/AndroidManifest-queriesPackage.xml b/tests/tests/appenumeration/app/source/AndroidManifest-queriesPackage.xml
new file mode 100644
index 0000000..e4bc398
--- /dev/null
+++ b/tests/tests/appenumeration/app/source/AndroidManifest-queriesPackage.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.appenumeration.queries.pkg">
+
+    <queries>
+        <package android:name="android.appenumeration.noapi" />
+    </queries>
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.appenumeration.cts.query.TestActivity"
+                  android:exported="true" />
+    </application>
+</manifest>
diff --git a/tests/tests/appenumeration/app/source/AndroidManifest-queriesProviderAuthority.xml b/tests/tests/appenumeration/app/source/AndroidManifest-queriesProviderAuthority.xml
new file mode 100644
index 0000000..6ec5a96
--- /dev/null
+++ b/tests/tests/appenumeration/app/source/AndroidManifest-queriesProviderAuthority.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.appenumeration.queries.provider.authority">
+
+    <queries>
+        <intent>
+            <data android:scheme="content" android:host="android.appenumeration.testapp" />
+        </intent>
+    </queries>
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.appenumeration.cts.query.TestActivity"
+                  android:exported="true" />
+    </application>
+</manifest>
diff --git a/tests/tests/appenumeration/app/source/AndroidManifest-queriesServiceAction.xml b/tests/tests/appenumeration/app/source/AndroidManifest-queriesServiceAction.xml
new file mode 100644
index 0000000..b451455
--- /dev/null
+++ b/tests/tests/appenumeration/app/source/AndroidManifest-queriesServiceAction.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.appenumeration.queries.service.action">
+
+    <queries>
+        <intent>
+            <action android:name="android.appenumeration.action.SERVICE" />
+        </intent>
+    </queries>
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.appenumeration.cts.query.TestActivity"
+                  android:exported="true" />
+    </application>
+</manifest>
diff --git a/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java b/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java
index 260014d..03b288d 100644
--- a/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java
+++ b/tests/tests/appenumeration/app/source/src/android/appenumeration/cts/query/TestActivity.java
@@ -16,40 +16,95 @@
 
 package android.appenumeration.cts.query;
 
+import static android.content.Intent.EXTRA_RETURN_RESULT;
+
 import android.app.Activity;
+import android.content.ComponentName;
 import android.content.Intent;
 import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.os.RemoteCallback;
+import android.util.ArrayMap;
+import android.util.Log;
+import android.util.SparseArray;
+
+import java.util.Random;
 
 public class TestActivity extends Activity {
 
+    SparseArray<RemoteCallback> callbacks = new SparseArray<>();
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        RemoteCallback remoteCallback =
-                getIntent().getParcelableExtra("remoteCallback");
-        Bundle result = new Bundle();
-        try {
+        handleIntent(getIntent());
+    }
 
-            final String action = getIntent().getAction();
-            switch (action) {
-                case "android.appenumeration.cts.action.GET_PACKAGE_INFO":
-                    final String packageName = getIntent().getStringExtra(
-                            Intent.EXTRA_PACKAGE_NAME);
-                    final PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);
-                    result.putParcelable(Intent.EXTRA_RETURN_RESULT, pi);
-                    break;
-                default:
-                    result.putSerializable("error",
-                            new Exception("unknown action " + action));
-                    break;
+    private void handleIntent(Intent intent) {
+        RemoteCallback remoteCallback = intent.getParcelableExtra("remoteCallback");
+        Bundle result = new Bundle();
+        final String action = intent.getAction();
+        final String packageName = intent.getStringExtra(
+                Intent.EXTRA_PACKAGE_NAME);
+        if ("android.appenumeration.cts.action.GET_PACKAGE_INFO".equals(action)) {
+            sendPackageInfo(remoteCallback, packageName);
+        } else if ("android.appenumeration.cts.action.START_FOR_RESULT".equals(action)) {
+            int requestCode = RESULT_FIRST_USER + callbacks.size();
+            callbacks.put(requestCode, remoteCallback);
+            startActivityForResult(
+                    new Intent("android.appenumeration.cts.action.SEND_RESULT").setComponent(
+                            new ComponentName(packageName, getClass().getCanonicalName())),
+                    requestCode);
+            // don't send anything... await result callback
+        } else if ("android.appenumeration.cts.action.SEND_RESULT".equals(action)) {
+            try {
+                setResult(RESULT_OK,
+                        getIntent().putExtra(
+                                Intent.EXTRA_RETURN_RESULT,
+                                getPackageManager().getPackageInfo(getCallingPackage(), 0)));
+            } catch (PackageManager.NameNotFoundException e) {
+                setResult(RESULT_FIRST_USER, new Intent().putExtra("error", e));
             }
-        } catch (Exception failure) {
-            result.putSerializable("error", failure);
-        } finally {
-            remoteCallback.sendResult(result);
+            finish();
+        } else {
+            sendError(remoteCallback, new Exception("unknown action " + action));
         }
+    }
+
+    private void sendError(RemoteCallback remoteCallback, Exception failure) {
+        Bundle result = new Bundle();
+        result.putSerializable("error", failure);
+        remoteCallback.sendResult(result);
+        finish();
+    }
+
+    private void sendPackageInfo(RemoteCallback remoteCallback, String packageName) {
+        final PackageInfo pi;
+        try {
+            pi = getPackageManager().getPackageInfo(packageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            sendError(remoteCallback, e);
+            return;
+        }
+        Bundle result = new Bundle();
+        result.putParcelable(EXTRA_RETURN_RESULT, pi);
+        remoteCallback.sendResult(result);
+        finish();
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        final RemoteCallback remoteCallback = callbacks.get(requestCode);
+        if (resultCode != RESULT_OK) {
+            Exception e = (Exception) data.getSerializableExtra("error");
+            sendError(remoteCallback, e == null ? new Exception("Result was " + resultCode) : e);
+            return;
+        }
+        final Bundle result = new Bundle();
+        result.putParcelable(EXTRA_RETURN_RESULT, data.getParcelableExtra(EXTRA_RETURN_RESULT));
+        remoteCallback.sendResult(result);
         finish();
     }
 }
\ No newline at end of file
diff --git a/tests/tests/appenumeration/app/target/Android.bp b/tests/tests/appenumeration/app/target/Android.bp
index e4d494a..d5f9757 100644
--- a/tests/tests/appenumeration/app/target/Android.bp
+++ b/tests/tests/appenumeration/app/target/Android.bp
@@ -13,7 +13,7 @@
 // limitations under the License.
 
 android_test_helper_app {
-    name: "CtsAppEnumerationForceQueryableApp",
+    name: "CtsAppEnumerationForceQueryable",
     manifest: "AndroidManifest-forceQueryable.xml",
     defaults: ["cts_support_defaults"],
     srcs: ["src/**/*.java"],
@@ -27,7 +27,7 @@
 }
 
 android_test_helper_app {
-    name: "CtsAppEnumerationFiltersApp",
+    name: "CtsAppEnumerationFilters",
     manifest: "AndroidManifest-filters.xml",
     defaults: ["cts_support_defaults"],
     srcs: ["src/**/*.java"],
@@ -41,7 +41,7 @@
 }
 
 android_test_helper_app {
-    name: "CtsAppEnumerationNoApiApp",
+    name: "CtsAppEnumerationNoApi",
     manifest: "AndroidManifest-noapi.xml",
     defaults: ["cts_support_defaults"],
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/appenumeration/app/target/AndroidManifest-filters.xml b/tests/tests/appenumeration/app/target/AndroidManifest-filters.xml
index 04aae68..e6e61f7 100644
--- a/tests/tests/appenumeration/app/target/AndroidManifest-filters.xml
+++ b/tests/tests/appenumeration/app/target/AndroidManifest-filters.xml
@@ -30,7 +30,8 @@
             </intent-filter>
         </service>
         <provider android:name="android.appenumeration.testapp.DummyProvider"
-                  android:authorities="android.appenumeration.testapp" />
+                  android:authorities="android.appenumeration.testapp"
+                  android:exported="true" />
         <receiver android:name="android.appenumeration.testapp.DummyReceiver">
             <intent-filter>
                 <action android:name="android.appenumeration.action.BROADCAST" />
diff --git a/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java b/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
index 775b4a8..d3a74ea 100644
--- a/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
+++ b/tests/tests/appenumeration/src/android/appenumeration/cts/AppEnumerationTests.java
@@ -16,7 +16,8 @@
 
 package android.appenumeration.cts;
 
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
 import android.content.ComponentName;
@@ -24,7 +25,9 @@
 import android.content.Intent;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
+import android.net.Uri;
 import android.os.Bundle;
+import android.os.ConditionVariable;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.RemoteCallback;
@@ -34,14 +37,17 @@
 
 import com.android.compatibility.common.util.SystemUtil;
 
-import org.junit.After;
+import org.hamcrest.core.IsNull;
+import org.junit.AfterClass;
 import org.junit.Assert;
 import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TestName;
 import org.junit.runner.RunWith;
 
 import java.util.Objects;
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicReference;
@@ -49,88 +55,226 @@
 @RunWith(AndroidJUnit4.class)
 public class AppEnumerationTests {
 
-    private static final String TARGET_NO_API_NAME = "android.appenumeration.noapi";
-    private static final String TARGET_FORCEQUERYABLE_NAME = "android.appenumeration.forcequeryable";
-    private static final String TARGET_FILTERS_NAME = "android.appenumeration.filters";
+    private static final String PKG_BASE = "android.appenumeration.";
 
-    private static final String QUERIES_NOTHING_NAME = "android.appenumeration.queries.nothing";
+    /** A package with no published API and so isn't queryable by anything but package name */
+    private static final String TARGET_NO_API = PKG_BASE + "noapi";
+    /** A package that declares itself force queryable, making it visible to all other packages */
+    private static final String TARGET_FORCEQUERYABLE = PKG_BASE + "forcequeryable";
+    /** A package that exposes itself via various intent filters (activities, services, etc.) */
+    private static final String TARGET_FILTERS = PKG_BASE + "filters";
 
-    private Context mContext;
-    private Handler mResponseHandler;
-    private HandlerThread mResponseThread;
+    /** A package that has no queries tag or permission to query any specific packages */
+    private static final String QUERIES_NOTHING = PKG_BASE + "queries.nothing";
+    /** A package that has no queries tag or permissions but targets Q */
+    private static final String QUERIES_NOTHING_Q = PKG_BASE + "queries.nothing.q";
+    /** A package that has no queries but gets the QUERY_ALL_PACKAGES permission */
+    private static final String QUERIES_NOTHING_PERM = PKG_BASE + "queries.nothing.haspermission";
+    /** A package that queries for the action in {@link #TARGET_FILTERS} activity filter */
+    private static final String QUERIES_ACTIVITY_ACTION = PKG_BASE + "queries.activity.action";
+    /** A package that queries for the action in {@link #TARGET_FILTERS} service filter */
+    private static final String QUERIES_SERVICE_ACTION = PKG_BASE + "queries.service.action";
+    /** A package that queries for the authority in {@link #TARGET_FILTERS} provider */
+    private static final String QUERIES_PROVIDER_AUTH = PKG_BASE + "queries.provider.authority";
+    /** A package that queries for {@link #TARGET_NO_API} package */
+    private static final String QUERIES_PACKAGE = PKG_BASE + "queries.pkg";
 
-    private boolean mGlobalFeatureEnabled;
+    private static final String[] ALL_QUERIES_PACKAGES = {
+            QUERIES_NOTHING,
+            QUERIES_NOTHING_Q,
+            QUERIES_NOTHING_PERM,
+            QUERIES_ACTIVITY_ACTION,
+            QUERIES_SERVICE_ACTION,
+            QUERIES_PROVIDER_AUTH,
+            QUERIES_PACKAGE,
+    };
+
+    private static Context sContext;
+    private static Handler sResponseHandler;
+    private static HandlerThread sResponseThread;
+
+    private static boolean sGlobalFeatureEnabled;
+
+    @Rule
+    public TestName name = new TestName();
+
+    @BeforeClass
+    public static void setup() {
+        final String deviceConfigResponse =
+                SystemUtil.runShellCommand(
+                        "device_config get package_manager_service "
+                                + "package_query_filtering_enabled")
+                        .trim();
+        if ("null".equalsIgnoreCase(deviceConfigResponse) || deviceConfigResponse.isEmpty()) {
+            sGlobalFeatureEnabled = true;
+        } else {
+            sGlobalFeatureEnabled = Boolean.parseBoolean(deviceConfigResponse);
+        }
+        System.out.println("Feature enabled: " + sGlobalFeatureEnabled);
+        if (!sGlobalFeatureEnabled) return;
+
+        sContext = InstrumentationRegistry.getInstrumentation().getContext();
+        sResponseThread = new HandlerThread("response");
+        sResponseThread.start();
+        sResponseHandler = new Handler(sResponseThread.getLooper());
+    }
 
     @Before
-    public void setup() {
-        mGlobalFeatureEnabled = Boolean.parseBoolean(SystemUtil.runShellCommand(
-                "device_config get package_manager_service package_query_filtering_enabled"));
-        if (!mGlobalFeatureEnabled) return;
+    public void setupTest() {
+        if (!sGlobalFeatureEnabled) return;
 
-        mContext = InstrumentationRegistry.getInstrumentation().getContext();
-        mResponseThread = new HandlerThread("response");
-        mResponseThread.start();
-        mResponseHandler = new Handler(mResponseThread.getLooper());
-
-        enableFeatureForPackage(QUERIES_NOTHING_NAME);
+        setFeatureEnabledForAll(true);
     }
 
-    private void enableFeatureForPackage(String packageName) {
-        final String response =
-                SystemUtil.runShellCommand("am compat enable 135549675 " + packageName);
-        assertTrue(response.contains("Enabled"));
-    }
-
-    @After
-    public void tearDown() {
-        if (!mGlobalFeatureEnabled) return;
-        mResponseThread.quit();
+    @AfterClass
+    public static void tearDown() {
+        if (!sGlobalFeatureEnabled) return;
+        sResponseThread.quit();
     }
 
     @Test
-    public void queriesNothing_canSeeForceQueryable() throws Exception {
-        if (!mGlobalFeatureEnabled) return;
-        final PackageInfo packageInfo =
-                getPackageInfo(QUERIES_NOTHING_NAME, TARGET_FORCEQUERYABLE_NAME);
-        Assert.assertTrue(packageInfo != null);
+    public void all_canSeeForceQueryable() throws Exception {
+        assertVisible(QUERIES_NOTHING, TARGET_FORCEQUERYABLE);
+        assertVisible(QUERIES_ACTIVITY_ACTION, TARGET_FORCEQUERYABLE);
+        assertVisible(QUERIES_SERVICE_ACTION, TARGET_FORCEQUERYABLE);
+        assertVisible(QUERIES_PROVIDER_AUTH, TARGET_FORCEQUERYABLE);
+        assertVisible(QUERIES_PACKAGE, TARGET_FORCEQUERYABLE);
     }
 
     @Test
-    public void queriesNothing_cannotSeeNoApi() throws Exception {
-        if (!mGlobalFeatureEnabled) return;
+    public void queriesNothing_cannotSeeNonForceQueryable() throws Exception {
+        assertNotVisible(QUERIES_NOTHING, TARGET_NO_API);
+        assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesNothing_featureOff_canSeeAll() throws Exception {
+        setFeatureEnabledForAll(QUERIES_NOTHING, false);
+        assertVisible(QUERIES_NOTHING, TARGET_NO_API);
+        assertVisible(QUERIES_NOTHING, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesNothingTargetsQ_canSeeAll() throws Exception {
+        assertVisible(QUERIES_NOTHING_Q, TARGET_FORCEQUERYABLE);
+        assertVisible(QUERIES_NOTHING_Q, TARGET_NO_API);
+        assertVisible(QUERIES_NOTHING_Q, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesNothingHasPermission_canSeeAll() throws Exception {
+        assertVisible(QUERIES_NOTHING_PERM, TARGET_FORCEQUERYABLE);
+        assertVisible(QUERIES_NOTHING_PERM, TARGET_NO_API);
+        assertVisible(QUERIES_NOTHING_PERM, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesSomething_cannotSeeNoApi() throws Exception {
+        assertNotVisible(QUERIES_ACTIVITY_ACTION, TARGET_NO_API);
+        assertNotVisible(QUERIES_SERVICE_ACTION, TARGET_NO_API);
+        assertNotVisible(QUERIES_PROVIDER_AUTH, TARGET_NO_API);
+    }
+
+    @Test
+    public void queriesActivityAction_canSeeTarget() throws Exception {
+        assertVisible(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesServiceAction_canSeeTarget() throws Exception {
+        assertVisible(QUERIES_SERVICE_ACTION, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesProviderAuthority_canSeeTarget() throws Exception {
+        assertVisible(QUERIES_PROVIDER_AUTH, TARGET_FILTERS);
+    }
+
+    @Test
+    public void queriesPackage_canSeeTarget() throws Exception {
+        assertVisible(QUERIES_PACKAGE, TARGET_NO_API);
+
+    }
+    @Test
+    public void whenStarted_canSeeCaller() throws Exception {
+        // let's first make sure that the target cannot see the caller.
+        assertNotVisible(QUERIES_NOTHING, QUERIES_NOTHING_PERM);
+        // now let's start the target and make sure that it can see the caller as part of that call
+        PackageInfo packageInfo = startForResult(QUERIES_NOTHING_PERM, QUERIES_NOTHING);
+        assertThat(packageInfo, IsNull.notNullValue());
+        assertThat(packageInfo.packageName, is(QUERIES_NOTHING_PERM));
+        // and finally let's re-run the last check to make sure that the target can still see the
+        // caller
+        assertVisible(QUERIES_NOTHING, QUERIES_NOTHING_PERM);
+    }
+
+    private void assertVisible(String sourcePackageName, String targetPackageName)
+            throws Exception {
+        if (!sGlobalFeatureEnabled) return;
+        Assert.assertNotNull(sourcePackageName + " should be able to see " + targetPackageName,
+                getPackageInfo(sourcePackageName, targetPackageName));
+    }
+
+
+    private void setFeatureEnabledForAll(Boolean enabled) {
+        for (String pkgName : ALL_QUERIES_PACKAGES) {
+            setFeatureEnabledForAll(pkgName, enabled);
+        }
+    }
+
+    private void setFeatureEnabledForAll(String packageName, Boolean enabled) {
+        SystemUtil.runShellCommand(
+                "am compat " + (enabled == null ? "reset" : enabled ? "enable" : "disable")
+                        + " 135549675 " + packageName);
+    }
+
+    private void assertNotVisible(String sourcePackageName, String targetPackageName)
+            throws Exception {
+        if (!sGlobalFeatureEnabled) return;
         try {
-            getPackageInfo(QUERIES_NOTHING_NAME, TARGET_NO_API_NAME);
-            fail("App that queries nothing should not see other packages.");
-        } catch (PackageManager.NameNotFoundException e) {
+            getPackageInfo(sourcePackageName, targetPackageName);
+            fail(sourcePackageName + " should not be able to see " + targetPackageName);
+        } catch (PackageManager.NameNotFoundException ignored) {
         }
     }
 
     private PackageInfo getPackageInfo(String sourcePackageName, String targetPackageName)
             throws Exception {
         Bundle response = sendCommand(sourcePackageName, targetPackageName,
-                "android.appenumeration.cts.action.GET_PACKAGE_INFO");
+                PKG_BASE + "cts.action.GET_PACKAGE_INFO");
+        return response.getParcelable(Intent.EXTRA_RETURN_RESULT);
+    }
+
+    private PackageInfo startForResult(String sourcePackageName, String targetPackageName)
+            throws Exception {
+        Bundle response = sendCommand(sourcePackageName, targetPackageName,
+                PKG_BASE + "cts.action.START_FOR_RESULT");
         return response.getParcelable(Intent.EXTRA_RETURN_RESULT);
     }
 
     private Bundle sendCommand(String sourcePackageName, String targetPackageName, String action)
             throws Exception {
         Intent intent = new Intent(action)
-                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
-                .putExtra(Intent.EXTRA_PACKAGE_NAME, targetPackageName)
                 .setComponent(new ComponentName(
-                        sourcePackageName, "android.appenumeration.cts.query.TestActivity"));
-        final CountDownLatch countDownLatch = new CountDownLatch(1);
+                        sourcePackageName, PKG_BASE + "cts.query.TestActivity"))
+                // data uri unique to each activity start to ensure actual launch and not just
+                // redisplay
+                .setData(Uri.parse("test://" + name.getMethodName() + targetPackageName))
+                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
+                .putExtra(Intent.EXTRA_PACKAGE_NAME, targetPackageName);
+        final ConditionVariable latch = new ConditionVariable();
         final AtomicReference<Bundle> resultReference = new AtomicReference<>();
-        RemoteCallback callback = new RemoteCallback(
+        final RemoteCallback callback = new RemoteCallback(
                 bundle -> {
                     resultReference.set(bundle);
-                    countDownLatch.countDown();
+                    latch.open();
                 },
-                mResponseHandler);
+                sResponseHandler);
         intent.putExtra("remoteCallback", callback);
-        mContext.startActivity(intent);
-        if (!countDownLatch.await(5, TimeUnit.SECONDS)) {
-            throw new TimeoutException("Latch timed out!");
+        sContext.startActivity(intent);
+        if (!latch.block(TimeUnit.SECONDS.toMillis(10))) {
+            throw new TimeoutException(
+                    "Latch timed out while awiating a response from " + targetPackageName);
         }
         final Bundle bundle = resultReference.get();
         if (bundle != null && bundle.containsKey("error")) {
diff --git a/tests/tests/appop/src/android/app/appops/cts/AppOpsLoggingTest.kt b/tests/tests/appop/src/android/app/appops/cts/AppOpsLoggingTest.kt
index 985c73e..eec81df 100644
--- a/tests/tests/appop/src/android/app/appops/cts/AppOpsLoggingTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/AppOpsLoggingTest.kt
@@ -33,6 +33,7 @@
 import android.os.Handler
 import android.os.IBinder
 import android.os.Looper
+import android.platform.test.annotations.AppModeFull
 import androidx.test.platform.app.InstrumentationRegistry
 import com.google.common.truth.Truth.assertThat
 import org.junit.After
@@ -40,6 +41,7 @@
 import org.junit.Before
 import org.junit.Test
 import java.util.concurrent.CompletableFuture
+import java.util.concurrent.Executor
 import java.util.concurrent.TimeUnit.MILLISECONDS
 
 private const val TEST_SERVICE_PKG = "android.app.appops.cts.appthatusesappops"
@@ -53,6 +55,7 @@
     message: String
 )
 
+@AppModeFull(reason = "Test relies on other app to connect to. Instant apps can't see other apps")
 class AppOpsLoggingTest {
     private val context = InstrumentationRegistry.getInstrumentation().targetContext
     private val appOpsManager = context.getSystemService(AppOpsManager::class.java)
@@ -120,6 +123,11 @@
                     override fun onAsyncNoted(asyncOp: AsyncNotedAppOp) {
                         asyncNoted.add(asyncOp)
                     }
+
+                    override fun getAsyncNotedExecutor(): Executor {
+                        // Execute callbacks immediately
+                        return Executor { it.run() }
+                    }
                 })
     }
 
diff --git a/tests/tests/appop/src/android/app/appops/cts/HistoricalAppopsTest.kt b/tests/tests/appop/src/android/app/appops/cts/HistoricalAppopsTest.kt
index ffb95e6..62bc995 100644
--- a/tests/tests/appop/src/android/app/appops/cts/HistoricalAppopsTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/HistoricalAppopsTest.kt
@@ -21,6 +21,7 @@
 import android.app.AppOpsManager.HistoricalOps
 import android.os.Process
 import android.os.SystemClock
+import android.provider.DeviceConfig
 import androidx.test.InstrumentationRegistry
 import androidx.test.runner.AndroidJUnit4
 import com.google.common.truth.Truth.assertThat
@@ -35,12 +36,16 @@
 import androidx.test.uiautomator.UiDevice
 import org.junit.Rule
 
+const val PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled"
+
 @RunWith(AndroidJUnit4::class)
 class HistoricalAppopsTest {
     private val uid = Process.myUid()
     private lateinit var appOpsManager: AppOpsManager
     private lateinit var packageName: String
 
+    private var wasPermissionsHubEnabled = false
+
     // Start an activity to make sure this app counts as being in the foreground
     @Rule @JvmField
     var activityRule = ActivityTestRule(UidStateForceActivity::class.java)
@@ -57,6 +62,10 @@
         appOpsManager = context.getSystemService(AppOpsManager::class.java)!!
         packageName = context.packageName!!
         uiAutomation.adoptShellPermissionIdentity()
+        wasPermissionsHubEnabled = DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY,
+                PROPERTY_PERMISSIONS_HUB_ENABLED, false)
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_PRIVACY, PROPERTY_PERMISSIONS_HUB_ENABLED,
+                true.toString(), false)
         appOpsManager.clearHistory()
         appOpsManager.resetHistoryParameters()
     }
@@ -65,6 +74,8 @@
     fun tearDownTest() {
         appOpsManager.clearHistory()
         appOpsManager.resetHistoryParameters()
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_PRIVACY, PROPERTY_PERMISSIONS_HUB_ENABLED,
+                wasPermissionsHubEnabled.toString(), false)
         uiAutomation.dropShellPermissionIdentity()
     }
 
diff --git a/tests/tests/appwidget/Android.mk b/tests/tests/appwidget/Android.mk
index 493fcab..a193d34 100644
--- a/tests/tests/appwidget/Android.mk
+++ b/tests/tests/appwidget/Android.mk
@@ -35,7 +35,7 @@
 LOCAL_JAVA_LIBRARIES := android.test.base.stubs
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/appwidget/packages/launchermanifest/Android.mk b/tests/tests/appwidget/packages/launchermanifest/Android.mk
index 58d6960..f949836 100644
--- a/tests/tests/appwidget/packages/launchermanifest/Android.mk
+++ b/tests/tests/appwidget/packages/launchermanifest/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.appwidget.cts.packages.launcher1
 
@@ -54,7 +54,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.appwidget.cts.packages.launcher2
 
@@ -75,7 +75,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.appwidget.cts.packages.launcher3
 
diff --git a/tests/tests/appwidget/packages/widgetprovider/Android.mk b/tests/tests/appwidget/packages/widgetprovider/Android.mk
index ef5cc136..733a4a8 100644
--- a/tests/tests/appwidget/packages/widgetprovider/Android.mk
+++ b/tests/tests/appwidget/packages/widgetprovider/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
@@ -52,7 +52,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
@@ -73,6 +73,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
index 0e84505..6a79aba 100644
--- a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
+++ b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
@@ -74,6 +74,7 @@
 import java.util.Arrays;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.IntConsumer;
 
 public class AppWidgetTest extends AppWidgetTestCase {
 
@@ -739,6 +740,88 @@
 
     @AppModeFull(reason = "Instant apps cannot provide or host app widgets")
     @Test
+    public void testAppWidgetRemoved() throws Exception {
+
+        // We want to bind widgets.
+        grantBindAppWidgetPermission();
+
+        final AtomicInteger onAppWidgetRemovedCounter = new AtomicInteger();
+        IntConsumer callback = mock(IntConsumer.class);
+
+        // Create a host and start listening.
+        AppWidgetHost host = new AppWidgetHost(
+            getInstrumentation().getTargetContext(), 0) {
+            @Override
+            public void onAppWidgetRemoved(int widgetId) {
+                synchronized (mLock) {
+                    onAppWidgetRemovedCounter.incrementAndGet();
+                    mLock.notifyAll();
+                    callback.accept(widgetId);
+                }
+            }
+        };
+        host.deleteHost();
+        host.startListening();
+
+        int firstAppWidgetId = 0;
+        int secondAppWidgetId = 0;
+
+        try {
+            // Grab the provider we defined to be bound.
+            AppWidgetProviderInfo firstProviderInfo = getFirstAppWidgetProviderInfo();
+            AppWidgetProviderInfo secondProviderInfo = getSecondAppWidgetProviderInfo();
+
+            // Allocate widget id to bind.
+            firstAppWidgetId = host.allocateAppWidgetId();
+            secondAppWidgetId = host.allocateAppWidgetId();
+
+            //create listeners
+            MyAppWidgetHostView.OnUpdateAppWidgetListener secondAppHostViewListener =
+                mock(MyAppWidgetHostView.OnUpdateAppWidgetListener.class);
+
+            // Bind the first app widget.
+            getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
+                firstProviderInfo.getProfile(), firstProviderInfo.provider, null);
+            getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
+                secondProviderInfo.getProfile(), secondProviderInfo.provider, null);
+
+            // Disable the first widget while host is listening
+            PackageManager packageManager = getInstrumentation().getTargetContext()
+                .getApplicationContext().getPackageManager();
+            packageManager.setComponentEnabledSetting(firstProviderInfo.provider,
+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                PackageManager.DONT_KILL_APP);
+
+            waitForCallCount(onAppWidgetRemovedCounter, 1);
+
+            // Disable the second widget while host is paused
+            host.stopListening();
+            packageManager.setComponentEnabledSetting(secondProviderInfo.provider,
+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                PackageManager.DONT_KILL_APP);
+
+
+            assertEquals(onAppWidgetRemovedCounter.get(),1);
+            verify(callback).accept(eq(firstAppWidgetId));
+
+            // resume listening
+            host.startListening();
+
+            // Wait for the package change to propagate.
+            waitForCallCount(onAppWidgetRemovedCounter, 2);
+            verify(callback).accept(eq(secondAppWidgetId));
+
+        } finally {
+            // Clean up.
+            host.deleteAppWidgetId(firstAppWidgetId);
+            host.deleteAppWidgetId(secondAppWidgetId);
+            host.deleteHost();
+            revokeBindAppWidgetPermission();
+        }
+    }
+
+    @AppModeFull(reason = "Instant apps cannot provide or host app widgets")
+    @Test
     public void testUpdateAppWidgetViaComponentName() throws Exception {
         // We want to bind widgets.
         grantBindAppWidgetPermission();
@@ -1502,7 +1585,6 @@
     private static class MyAppWidgetHostView extends AppWidgetHostView {
         private OnUpdateAppWidgetListener mOnUpdateAppWidgetListener;
 
-
         public interface OnUpdateAppWidgetListener {
             public void onUpdateAppWidget(RemoteViews remoteViews);
         }
diff --git a/tests/tests/background/Android.bp b/tests/tests/background/Android.bp
index 485914b..0eaf61f 100644
--- a/tests/tests/background/Android.bp
+++ b/tests/tests/background/Android.bp
@@ -28,7 +28,6 @@
     test_suites: [
         "cts",
         "vts",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
index c8526ec..b05cba0 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
@@ -48,6 +48,12 @@
   AIBinder_decStrong(binder);
 }
 
+TEST_F(NdkBinderTest_AIBinder, AssociateUnrelatedClassWithSameDescriptorFails) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_FALSE(AIBinder_associateClass(binder, SampleData::kAnotherClassWithSameDescriptor));
+  AIBinder_decStrong(binder);
+}
+
 TEST_F(NdkBinderTest_AIBinder, AssociateWrongClassFails) {
   AIBinder* binder = SampleData::newBinder();
   EXPECT_FALSE(AIBinder_associateClass(binder, SampleData::kAnotherClass));
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
index fad9f6f..e5b317f 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
@@ -56,6 +56,9 @@
     AIBinder_Class_define(SampleData::kDescriptor, SampleClassOnCreate,
                           SampleClassOnDestroy, SampleClassOnTransact);
 
+const AIBinder_Class* SampleData::kAnotherClassWithSameDescriptor = AIBinder_Class_define(
+    SampleData::kDescriptor, SampleClassOnCreate, SampleClassOnDestroy, SampleClassOnTransact);
+
 const char* SampleData::kAnotherDescriptor = "this-is-another-arbitrary-thing";
 const AIBinder_Class* SampleData::kAnotherClass =
     AIBinder_Class_define(SampleData::kAnotherDescriptor, SampleClassOnCreate,
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
index 4699636..e9d6ad5 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
@@ -85,6 +85,7 @@
 struct SampleData : ThisShouldBeDestroyed {
   static const char* kDescriptor;
   static const AIBinder_Class* kClass;
+  static const AIBinder_Class* kAnotherClassWithSameDescriptor;
 
   static const char* kAnotherDescriptor;
   static const AIBinder_Class* kAnotherClass;
diff --git a/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java b/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
index 5f391e4..357f985 100644
--- a/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
@@ -22,6 +22,7 @@
 import android.car.Car;
 import android.car.CarNotConnectedException;
 import android.car.content.pm.CarPackageManager;
+import android.os.Build;
 import android.platform.test.annotations.RequiresDevice;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -77,6 +78,10 @@
     @Test
     public void testDistractionOptimizedActivityIsAllowed() throws CarNotConnectedException {
         // This test relies on test activity in installed apk, and AndroidManifest declaration.
+        if (Build.TYPE.equalsIgnoreCase("user")) {
+            // Skip this test on user build, which checks the install source for DO activity list.
+            return;
+        }
         assertTrue(mCarPm.isActivityDistractionOptimized("android.car.cts",
                 "android.car.cts.drivingstate.DistractionOptimizedActivity"));
     }
@@ -84,6 +89,10 @@
     @Test
     public void testNonDistractionOptimizedActivityNotAllowed() throws CarNotConnectedException {
         // This test relies on test activity in installed apk, and AndroidManifest declaration.
+        if (Build.TYPE.equalsIgnoreCase("user")) {
+            // Skip this test on user build, which checks the install source for DO activity list.
+            return;
+        }
         assertFalse(mCarPm.isActivityDistractionOptimized("android.car.cts",
                 "android.car.cts.drivingstate.NonDistractionOptimizedActivity"));
     }
diff --git a/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java b/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java
index ca7364b..4f80147 100644
--- a/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java
@@ -15,9 +15,13 @@
  */
 package android.car.cts;
 
+
+import static android.car.drivingstate.CarUxRestrictionsManager.UX_RESTRICTION_MODE_BASELINE;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import android.car.Car;
 import android.car.drivingstate.CarUxRestrictions;
@@ -27,6 +31,8 @@
 
 import androidx.test.runner.AndroidJUnit4;
 
+import com.google.common.collect.ImmutableList;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -87,4 +93,37 @@
         mManager.registerListener(restrictions -> {});
         mManager.unregisterListener();
     }
+
+    @Test
+    public void testSetRestrictionMode_missingPermission_throwsException() {
+        try {
+            mManager.setRestrictionMode(UX_RESTRICTION_MODE_BASELINE);
+            fail("Expected SecurityException. App does not have the change UX Restrictions "
+                    + "permission.");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
+
+    @Test
+    public void testGetRestrictionMode_missingPermission_throwsException() {
+        try {
+            mManager.getRestrictionMode();
+            fail("Expected SecurityException. App does not have the change UX Restrictions "
+                    + "permission.");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
+
+    @Test
+    public void testSaveUxRestrictionsConfigurationForNextBoot_missingPermission_throwsException() {
+        try {
+            mManager.saveUxRestrictionsConfigurationForNextBoot(ImmutableList.of());
+            fail("Expected SecurityException. App does not have the change UX Restrictions "
+                    + "permission.");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
 }
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java
index 69b364e9..98266ce 100644
--- a/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java
@@ -902,8 +902,6 @@
      * This test verifies that {@link TelephonyManager#setVoiceMailNumber(String, String)} correctly
      * sets the VoiceMail alpha tag and number when called.
      */
-    /* Disabling the test for now due to a bug in the code. Will re-enable it when the bug is
-       fixed.
     public void testVoiceMailNumber() {
         if (!hasCellular) return;
 
@@ -923,7 +921,7 @@
             // Reset original alpha tag and number values.
             mTelephonyManager.setVoiceMailNumber(originalAlphaTag, originalNumber);
         }
-    } */
+    }
 
     /**
      * This test verifies that {@link SubscriptionManager#createSubscriptionGroup(List)} correctly
diff --git a/tests/tests/classloaderfactory/test-memcl/Android.bp b/tests/tests/classloaderfactory/test-memcl/Android.bp
index 8bdf322..f190da2 100644
--- a/tests/tests/classloaderfactory/test-memcl/Android.bp
+++ b/tests/tests/classloaderfactory/test-memcl/Android.bp
@@ -20,6 +20,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/classloaderfactory/test-pathcl/Android.bp b/tests/tests/classloaderfactory/test-pathcl/Android.bp
index 924e298..93cd699 100644
--- a/tests/tests/classloaderfactory/test-pathcl/Android.bp
+++ b/tests/tests/classloaderfactory/test-pathcl/Android.bp
@@ -20,6 +20,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/colormode/Android.bp b/tests/tests/colormode/Android.bp
index 02268ed..5c7de68 100644
--- a/tests/tests/colormode/Android.bp
+++ b/tests/tests/colormode/Android.bp
@@ -28,7 +28,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "current",
 }
diff --git a/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java b/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java
index 457c1b6..47bc102 100644
--- a/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java
+++ b/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java
@@ -17,30 +17,16 @@
 package android.content.cts;
 
 import android.accounts.Account;
-import android.content.ComponentName;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import android.content.PeriodicSync;
-import android.content.res.Resources;
 import android.content.SyncStatusInfo;
-import android.os.Bundle;
 import android.os.Looper;
 import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
-import android.test.RenamingDelegatingContext;
-import android.test.mock.MockContentResolver;
-import android.test.mock.MockContext;
-import android.test.suitebuilder.annotation.LargeTest;
-import android.test.suitebuilder.annotation.MediumTest;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.util.AtomicFile;
+
 import com.android.server.content.SyncStorageEngine;
-import com.android.internal.os.AtomicFile;
 
 import java.io.File;
 import java.io.FileOutputStream;
-import java.util.List;
 
 @AppModeFull(reason = "Sync manager not supported")
 public class SyncStorageEngineTest extends AndroidTestCase {
diff --git a/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java b/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
index 2c4d0067..d0e24c6 100644
--- a/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
@@ -871,7 +871,7 @@
             return;
         }
         PackageInfo packageInfo = mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME,
-                PackageManager.MATCH_APEX);
+                PackageManager.MATCH_APEX | PackageManager.MATCH_FACTORY_ONLY);
         assertShimApexInfoIsCorrect(packageInfo);
     }
 
@@ -924,7 +924,7 @@
             return;
         }
         List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
-                PackageManager.MATCH_APEX);
+                PackageManager.MATCH_APEX | PackageManager.MATCH_FACTORY_ONLY);
         List<PackageInfo> shimApex = installedPackages.stream().filter(
                 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
                 Collectors.toList());
diff --git a/tests/tests/database/Android.bp b/tests/tests/database/Android.bp
index aad02e9..36f4fbd 100644
--- a/tests/tests/database/Android.bp
+++ b/tests/tests/database/Android.bp
@@ -33,7 +33,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     // Enforce public / test api only
     sdk_version: "test_current",
diff --git a/tests/tests/display/Android.bp b/tests/tests/display/Android.bp
index ac6c955..6765e97 100644
--- a/tests/tests/display/Android.bp
+++ b/tests/tests/display/Android.bp
@@ -29,7 +29,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/tests/dpi/Android.bp b/tests/tests/dpi/Android.bp
index 88706bb..3312570 100644
--- a/tests/tests/dpi/Android.bp
+++ b/tests/tests/dpi/Android.bp
@@ -33,7 +33,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
 
diff --git a/tests/tests/dreams/Android.bp b/tests/tests/dreams/Android.bp
index d1ba152..121c9d6 100644
--- a/tests/tests/dreams/Android.bp
+++ b/tests/tests/dreams/Android.bp
@@ -30,6 +30,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/gesture/Android.bp b/tests/tests/gesture/Android.bp
index 9344bb6..1f8c125 100644
--- a/tests/tests/gesture/Android.bp
+++ b/tests/tests/gesture/Android.bp
@@ -22,7 +22,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     sdk_version: "current",
 }
diff --git a/tests/tests/graphics/Android.bp b/tests/tests/graphics/Android.bp
index beed115..9ed18c2 100644
--- a/tests/tests/graphics/Android.bp
+++ b/tests/tests/graphics/Android.bp
@@ -28,6 +28,7 @@
         "ctstestrunner-axt",
         "androidx.annotation_annotation",
         "junit",
+        "junit-params",
         "testng",
         "androidx.core_core",
     ],
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
index b507bf9..1b934ac 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
@@ -36,6 +36,7 @@
 import android.graphics.Rect;
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
+import android.platform.test.annotations.LargeTest;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.util.DisplayMetrics;
@@ -43,7 +44,6 @@
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.compatibility.common.util.CddTest;
 
@@ -61,29 +61,36 @@
 import java.io.RandomAccessFile;
 import java.util.concurrent.CountDownLatch;
 
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
 @SmallTest
-@RunWith(AndroidJUnit4.class)
+@RunWith(JUnitParamsRunner.class)
 public class BitmapFactoryTest {
     // height and width of start.jpg
     private static final int START_HEIGHT = 31;
     private static final int START_WIDTH = 31;
 
-    // The test images, including baseline JPEG, a PNG, a GIF, a BMP AND a WEBP.
-    private static final int[] RES_IDS = new int[] {
-            R.drawable.baseline_jpeg, R.drawable.png_test, R.drawable.gif_test,
-            R.drawable.bmp_test, R.drawable.webp_test
-    };
+    static class TestImage {
+        TestImage(int id, int width, int height) {
+            this.id = id;
+            this.width = width;
+            this.height = height;
+        }
+        public final int id;
+        public final int width;
+        public final int height;
+    }
 
-    // The width and height of the above image.
-    private static final int WIDTHS[] = new int[] { 1280, 640, 320, 320, 640 };
-    private static final int HEIGHTS[] = new int[] { 960, 480, 240, 240, 480 };
-
-    // Configurations for BitmapFactory.Options
-    private static final Config[] COLOR_CONFIGS = new Config[] {Config.ARGB_8888, Config.RGB_565};
-    private static final int[] COLOR_TOLS = new int[] {16, 49, 576};
-
-    private static final Config[] COLOR_CONFIGS_RGBA = new Config[] {Config.ARGB_8888};
-    private static final int[] COLOR_TOLS_RGBA = new int[] {72, 124};
+    private Object[] testImages() {
+        return new Object[] {
+                new TestImage(R.drawable.baseline_jpeg, 1280, 960),
+                new TestImage(R.drawable.png_test, 640, 480),
+                new TestImage(R.drawable.gif_test, 320, 240),
+                new TestImage(R.drawable.bmp_test, 320, 240),
+                new TestImage(R.drawable.webp_test, 640, 480),
+        };
+    }
 
     private static final int[] RAW_COLORS = new int[] {
         // raw data from R.drawable.premul_data
@@ -206,88 +213,102 @@
     }
 
     @Test
-    public void testDecodeStream3() {
-        for (int i = 0; i < RES_IDS.length; ++i) {
-            InputStream is = obtainInputStream(RES_IDS[i]);
-            Bitmap b = BitmapFactory.decodeStream(is);
-            assertNotNull(b);
-            // Test the bitmap size
-            assertEquals(WIDTHS[i], b.getWidth());
-            assertEquals(HEIGHTS[i], b.getHeight());
-        }
+    @Parameters(method = "testImages")
+    public void testDecodeStream3(TestImage testImage) {
+        InputStream is = obtainInputStream(testImage.id);
+        Bitmap b = BitmapFactory.decodeStream(is);
+        assertNotNull(b);
+        // Test the bitmap size
+        assertEquals(testImage.width, b.getWidth());
+        assertEquals(testImage.height, b.getHeight());
+    }
+
+    private Object[] paramsForWebpDecodeEncode() {
+        return new Object[] {
+                new Object[] {Config.ARGB_8888, 16},
+                new Object[] {Config.RGB_565, 49}
+        };
+    }
+
+    private Bitmap decodeOpaqueImage(int resId, BitmapFactory.Options options) {
+        return decodeOpaqueImage(obtainInputStream(resId), options);
+    }
+
+    private Bitmap decodeOpaqueImage(InputStream stream, BitmapFactory.Options options) {
+        Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
+        assertNotNull(bitmap);
+        assertFalse(bitmap.isPremultiplied());
+        assertFalse(bitmap.hasAlpha());
+        return bitmap;
     }
 
     @Test
-    public void testDecodeStream4() {
+    @Parameters(method = "paramsForWebpDecodeEncode")
+    public void testWebpStreamDecode(Config config, int tolerance) {
         BitmapFactory.Options options = new BitmapFactory.Options();
-        for (int k = 0; k < COLOR_CONFIGS.length; ++k) {
-            options.inPreferredConfig = COLOR_CONFIGS[k];
+        options.inPreferredConfig = config;
 
-            // Decode the PNG & WebP test images. The WebP test image has been encoded from PNG test
-            // image and should have same similar (within some error-tolerance) Bitmap data.
-            InputStream iStreamPng = obtainInputStream(R.drawable.png_test);
-            Bitmap bPng = BitmapFactory.decodeStream(iStreamPng, null, options);
-            assertNotNull(bPng);
-            assertEquals(bPng.getConfig(), COLOR_CONFIGS[k]);
-            assertFalse(bPng.isPremultiplied());
-            assertFalse(bPng.hasAlpha());
+        // Decode the PNG & WebP test images. The WebP test image has been encoded from PNG test
+        // image and should have same similar (within some error-tolerance) Bitmap data.
+        Bitmap bPng = decodeOpaqueImage(R.drawable.png_test, options);
+        assertEquals(bPng.getConfig(), config);
+        Bitmap bWebp = decodeOpaqueImage(R.drawable.webp_test, options);
+        compareBitmaps(bPng, bWebp, tolerance, true, bPng.isPremultiplied());
+    }
 
-            InputStream iStreamWebp1 = obtainInputStream(R.drawable.webp_test);
-            Bitmap bWebp1 = BitmapFactory.decodeStream(iStreamWebp1, null, options);
-            assertNotNull(bWebp1);
-            assertFalse(bWebp1.isPremultiplied());
-            assertFalse(bWebp1.hasAlpha());
-            compareBitmaps(bPng, bWebp1, COLOR_TOLS[k], true, bPng.isPremultiplied());
+    @Test
+    @Parameters(method = "paramsForWebpDecodeEncode")
+    public void testWebpStreamEncode(Config config, int tolerance) {
+        BitmapFactory.Options options = new BitmapFactory.Options();
+        options.inPreferredConfig = config;
 
-            // Compress the PNG image to WebP format (Quality=90) and decode it back.
-            // This will test end-to-end WebP encoding and decoding.
-            ByteArrayOutputStream oStreamWebp = new ByteArrayOutputStream();
-            assertTrue(bPng.compress(CompressFormat.WEBP, 90, oStreamWebp));
-            InputStream iStreamWebp2 = new ByteArrayInputStream(oStreamWebp.toByteArray());
-            Bitmap bWebp2 = BitmapFactory.decodeStream(iStreamWebp2, null, options);
-            assertNotNull(bWebp2);
-            assertFalse(bWebp2.isPremultiplied());
-            assertFalse(bWebp2.hasAlpha());
-            compareBitmaps(bPng, bWebp2, COLOR_TOLS[k], true, bPng.isPremultiplied());
-        }
+        Bitmap bPng = decodeOpaqueImage(R.drawable.png_test, options);
+        assertEquals(bPng.getConfig(), config);
+
+        // Compress the PNG image to WebP format (Quality=90) and decode it back.
+        // This will test end-to-end WebP encoding and decoding.
+        ByteArrayOutputStream oStreamWebp = new ByteArrayOutputStream();
+        assertTrue(bPng.compress(CompressFormat.WEBP, 90, oStreamWebp));
+        InputStream iStreamWebp = new ByteArrayInputStream(oStreamWebp.toByteArray());
+        Bitmap bWebp2 = decodeOpaqueImage(iStreamWebp, options);
+        compareBitmaps(bPng, bWebp2, tolerance, true, bPng.isPremultiplied());
     }
 
     @Test
     public void testDecodeStream5() {
+        final int tolerance = 72;
         BitmapFactory.Options options = new BitmapFactory.Options();
-        for (int k = 0; k < COLOR_CONFIGS_RGBA.length; ++k) {
-            options.inPreferredConfig = COLOR_CONFIGS_RGBA[k];
+        options.inPreferredConfig = Config.ARGB_8888;
 
-            // Decode the PNG & WebP (google_logo) images. The WebP image has
-            // been encoded from PNG image.
-            InputStream iStreamPng = obtainInputStream(R.drawable.google_logo_1);
-            Bitmap bPng = BitmapFactory.decodeStream(iStreamPng, null, options);
-            assertNotNull(bPng);
-            assertEquals(bPng.getConfig(), COLOR_CONFIGS_RGBA[k]);
-            assertTrue(bPng.isPremultiplied());
-            assertTrue(bPng.hasAlpha());
+        // Decode the PNG & WebP (google_logo) images. The WebP image has
+        // been encoded from PNG image.
+        InputStream iStreamPng = obtainInputStream(R.drawable.google_logo_1);
+        Bitmap bPng = BitmapFactory.decodeStream(iStreamPng, null, options);
+        assertNotNull(bPng);
+        assertEquals(bPng.getConfig(), Config.ARGB_8888);
+        assertTrue(bPng.isPremultiplied());
+        assertTrue(bPng.hasAlpha());
 
-            // Decode the corresponding WebP (transparent) image (google_logo_2.webp).
-            InputStream iStreamWebP1 = obtainInputStream(R.drawable.google_logo_2);
-            Bitmap bWebP1 = BitmapFactory.decodeStream(iStreamWebP1, null, options);
-            assertNotNull(bWebP1);
-            assertEquals(bWebP1.getConfig(), COLOR_CONFIGS_RGBA[k]);
-            assertTrue(bWebP1.isPremultiplied());
-            assertTrue(bWebP1.hasAlpha());
-            compareBitmaps(bPng, bWebP1, COLOR_TOLS_RGBA[k], true, bPng.isPremultiplied());
+        // Decode the corresponding WebP (transparent) image (google_logo_2.webp).
+        InputStream iStreamWebP1 = obtainInputStream(R.drawable.google_logo_2);
+        Bitmap bWebP1 = BitmapFactory.decodeStream(iStreamWebP1, null, options);
+        assertNotNull(bWebP1);
+        assertEquals(bWebP1.getConfig(), Config.ARGB_8888);
+        assertTrue(bWebP1.isPremultiplied());
+        assertTrue(bWebP1.hasAlpha());
+        compareBitmaps(bPng, bWebP1, tolerance, true, bPng.isPremultiplied());
 
-            // Compress the PNG image to WebP format (Quality=90) and decode it back.
-            // This will test end-to-end WebP encoding and decoding.
-            ByteArrayOutputStream oStreamWebp = new ByteArrayOutputStream();
-            assertTrue(bPng.compress(CompressFormat.WEBP, 90, oStreamWebp));
-            InputStream iStreamWebp2 = new ByteArrayInputStream(oStreamWebp.toByteArray());
-            Bitmap bWebP2 = BitmapFactory.decodeStream(iStreamWebp2, null, options);
-            assertNotNull(bWebP2);
-            assertEquals(bWebP2.getConfig(), COLOR_CONFIGS_RGBA[k]);
-            assertTrue(bWebP2.isPremultiplied());
-            assertTrue(bWebP2.hasAlpha());
-            compareBitmaps(bPng, bWebP2, COLOR_TOLS_RGBA[k], true, bPng.isPremultiplied());
-        }
+        // Compress the PNG image to WebP format (Quality=90) and decode it back.
+        // This will test end-to-end WebP encoding and decoding.
+        ByteArrayOutputStream oStreamWebp = new ByteArrayOutputStream();
+        assertTrue(bPng.compress(CompressFormat.WEBP, 90, oStreamWebp));
+        InputStream iStreamWebp2 = new ByteArrayInputStream(oStreamWebp.toByteArray());
+        Bitmap bWebP2 = BitmapFactory.decodeStream(iStreamWebp2, null, options);
+        assertNotNull(bWebP2);
+        assertEquals(bWebP2.getConfig(), Config.ARGB_8888);
+        assertTrue(bWebP2.isPremultiplied());
+        assertTrue(bWebP2.hasAlpha());
+        compareBitmaps(bPng, bWebP2, tolerance, true, bPng.isPremultiplied());
     }
 
     @Test
@@ -315,47 +336,48 @@
         assertEquals(START_WIDTH, b.getWidth());
     }
 
+
+    // TODO: Better parameterize this and split it up.
     @Test
-    public void testDecodeFileDescriptor3() throws IOException {
+    @Parameters(method = "testImages")
+    public void testDecodeFileDescriptor3(TestImage testImage) throws IOException {
         // Arbitrary offsets to use. If the offset of the FD matches the offset of the image,
         // decoding should succeed, but if they do not match, decoding should fail.
-        long ACTUAL_OFFSETS[] = new long[] { 0, 17 };
-        for (int RES_ID : RES_IDS) {
-            for (int j = 0; j < ACTUAL_OFFSETS.length; ++j) {
-                // FIXME: The purgeable test should attempt to purge the memory
-                // to force a re-decode.
-                for (boolean TEST_PURGEABLE : new boolean[] { false, true }) {
-                    BitmapFactory.Options opts = new BitmapFactory.Options();
-                    opts.inPurgeable = TEST_PURGEABLE;
-                    opts.inInputShareable = TEST_PURGEABLE;
+        final long[] actual_offsets = new long[] { 0, 17 };
+        for (int j = 0; j < actual_offsets.length; ++j) {
+            // FIXME: The purgeable test should attempt to purge the memory
+            // to force a re-decode.
+            for (boolean purgeable : new boolean[] { false, true }) {
+                BitmapFactory.Options opts = new BitmapFactory.Options();
+                opts.inPurgeable = purgeable;
+                opts.inInputShareable = purgeable;
 
-                    long actualOffset = ACTUAL_OFFSETS[j];
-                    String path = obtainPath(RES_ID, actualOffset);
-                    RandomAccessFile file = new RandomAccessFile(path, "r");
-                    FileDescriptor fd = file.getFD();
-                    assertTrue(fd.valid());
+                long actualOffset = actual_offsets[j];
+                String path = obtainPath(testImage.id, actualOffset);
+                RandomAccessFile file = new RandomAccessFile(path, "r");
+                FileDescriptor fd = file.getFD();
+                assertTrue(fd.valid());
 
-                    // Set the offset to ACTUAL_OFFSET
-                    file.seek(actualOffset);
-                    assertEquals(file.getFilePointer(), actualOffset);
+                // Set the offset to ACTUAL_OFFSET
+                file.seek(actualOffset);
+                assertEquals(file.getFilePointer(), actualOffset);
 
-                    // Now decode. This should be successful and leave the offset
-                    // unchanged.
-                    Bitmap b = BitmapFactory.decodeFileDescriptor(fd, null, opts);
-                    assertNotNull(b);
-                    assertEquals(file.getFilePointer(), actualOffset);
+                // Now decode. This should be successful and leave the offset
+                // unchanged.
+                Bitmap b = BitmapFactory.decodeFileDescriptor(fd, null, opts);
+                assertNotNull(b);
+                assertEquals(file.getFilePointer(), actualOffset);
 
-                    // Now use the other offset. It should fail to decode, and
-                    // the offset should remain unchanged.
-                    long otherOffset = ACTUAL_OFFSETS[(j + 1) % ACTUAL_OFFSETS.length];
-                    assertFalse(otherOffset == actualOffset);
-                    file.seek(otherOffset);
-                    assertEquals(file.getFilePointer(), otherOffset);
+                // Now use the other offset. It should fail to decode, and
+                // the offset should remain unchanged.
+                long otherOffset = actual_offsets[(j + 1) % actual_offsets.length];
+                assertFalse(otherOffset == actualOffset);
+                file.seek(otherOffset);
+                assertEquals(file.getFilePointer(), otherOffset);
 
-                    b = BitmapFactory.decodeFileDescriptor(fd, null, opts);
-                    assertNull(b);
-                    assertEquals(file.getFilePointer(), otherOffset);
-                }
+                b = BitmapFactory.decodeFileDescriptor(fd, null, opts);
+                assertNull(b);
+                assertEquals(file.getFilePointer(), otherOffset);
             }
         }
     }
@@ -493,18 +515,17 @@
     }
 
     @Test
-    public void testDecodeReuseFormats() {
+    @Parameters(method = "testImages")
+    public void testDecodeReuseFormats(TestImage testImage) {
         // reuse should support all image formats
-        for (int i = 0; i < RES_IDS.length; ++i) {
-            Bitmap reuseBuffer = Bitmap.createBitmap(1000000, 1, Bitmap.Config.ALPHA_8);
+        Bitmap reuseBuffer = Bitmap.createBitmap(1000000, 1, Bitmap.Config.ALPHA_8);
 
-            BitmapFactory.Options options = new BitmapFactory.Options();
-            options.inBitmap = reuseBuffer;
-            options.inSampleSize = 4;
-            options.inScaled = false;
-            Bitmap decoded = BitmapFactory.decodeResource(mRes, RES_IDS[i], options);
-            assertSame(reuseBuffer, decoded);
-        }
+        BitmapFactory.Options options = new BitmapFactory.Options();
+        options.inBitmap = reuseBuffer;
+        options.inSampleSize = 4;
+        options.inScaled = false;
+        Bitmap decoded = BitmapFactory.decodeResource(mRes, testImage.id, options);
+        assertSame(reuseBuffer, decoded);
     }
 
     @Test
@@ -792,27 +813,29 @@
 
     @Test
     @CddTest(requirement = "5.1.5/C-0-6")
-    public void testDng() {
-        DNG[] dngs = new DNG[]{
-            new DNG(R.raw.sample_1mp, 600, 338),
-            new DNG(R.raw.sample_arw, 1616, 1080),
-            new DNG(R.raw.sample_cr2, 2304, 1536),
-            new DNG(R.raw.sample_nef, 4608, 3072),
-            new DNG(R.raw.sample_nrw, 4000, 3000),
-            new DNG(R.raw.sample_orf, 3200, 2400),
-            new DNG(R.raw.sample_pef, 4928, 3264),
-            new DNG(R.raw.sample_raf, 2048, 1536),
-            new DNG(R.raw.sample_rw2, 1920, 1440),
-            new DNG(R.raw.sample_srw, 5472, 3648),
-        };
+    @Parameters(method = "parametersForTestDng")
+    @LargeTest
+    public void testDng(DNG dng) {
+        // No scaling
+        Bitmap bm = BitmapFactory.decodeResource(mRes, dng.resId, mOpt1);
+        assertNotNull(bm);
+        assertEquals(dng.width, bm.getWidth());
+        assertEquals(dng.height, bm.getHeight());
+    }
 
-        for (DNG dng : dngs) {
-            // No scaling
-            Bitmap bm = BitmapFactory.decodeResource(mRes, dng.resId, mOpt1);
-            assertNotNull(bm);
-            assertEquals(dng.width, bm.getWidth());
-            assertEquals(dng.height, bm.getHeight());
-        }
+    private Object[] parametersForTestDng() {
+        return new Object[]{
+                new DNG(R.raw.sample_1mp, 600, 338),
+                new DNG(R.raw.sample_arw, 1616, 1080),
+                new DNG(R.raw.sample_cr2, 2304, 1536),
+                new DNG(R.raw.sample_nef, 4608, 3072),
+                new DNG(R.raw.sample_nrw, 4000, 3000),
+                new DNG(R.raw.sample_orf, 3200, 2400),
+                new DNG(R.raw.sample_pef, 4928, 3264),
+                new DNG(R.raw.sample_raf, 2048, 1536),
+                new DNG(R.raw.sample_rw2, 1920, 1440),
+                new DNG(R.raw.sample_srw, 5472, 3648),
+        };
     }
 
     @Test
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
index 232d087..ffc9d9e 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
@@ -2224,7 +2224,7 @@
     private static native void nFillRgbaHwBuffer(HardwareBuffer hwBuffer);
     private static native void nTestNullBitmap();
 
-    private static final int ANDROID_BITMAP_FORMAT_RGBA_8888 = 1;
+    static final int ANDROID_BITMAP_FORMAT_RGBA_8888 = 1;
     private static final int ANDROID_BITMAP_FORMAT_RGB_565 = 4;
     private static final int ANDROID_BITMAP_FORMAT_A_8 = 8;
     private static final int ANDROID_BITMAP_FORMAT_RGBA_F16 = 9;
@@ -2248,7 +2248,7 @@
         new ConfigToFormat(Bitmap.Config.RGBA_F16, ANDROID_BITMAP_FORMAT_RGBA_F16),
     };
 
-    private static native int nGetFormat(Bitmap bitmap);
+    static native int nGetFormat(Bitmap bitmap);
 
     private static HardwareBuffer createTestBuffer(int width, int height, boolean cpuAccess) {
         long usage = HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE;
diff --git a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
index 9ba5006..88fbe38 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
@@ -2190,9 +2190,9 @@
             for (ColorSpace cs : BitmapTest.getRgbColorSpaces()) {
                 try {
                     Bitmap bm = ImageDecoder.decodeBitmap(src, (decoder, info, s) -> {
-                        if (record.isF16) {
-                            // CTS infrastructure fails to create F16 HARDWARE Bitmaps, so this
-                            // switches to using software.
+                        if (record.isF16 || isExtended(cs)) {
+                            // CTS infrastructure and some devices fail to create F16
+                            // HARDWARE Bitmaps, so this switches to using software.
                             decoder.setAllocator(ImageDecoder.ALLOCATOR_SOFTWARE);
                         }
                         decoder.setTargetColorSpace(cs);
@@ -2205,6 +2205,39 @@
         }
     }
 
+    @Test
+    public void testTargetColorSpaceNoF16HARDWARE() {
+        final ColorSpace EXTENDED_SRGB = ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB);
+        final ColorSpace LINEAR_EXTENDED_SRGB = ColorSpace.get(
+                ColorSpace.Named.LINEAR_EXTENDED_SRGB);
+        AssetManager assets = mRes.getAssets();
+        for (AssetRecord record : ASSETS) {
+            ImageDecoder.Source src = ImageDecoder.createSource(assets, record.name);
+            for (ColorSpace cs : new ColorSpace[] { EXTENDED_SRGB, LINEAR_EXTENDED_SRGB }) {
+                try {
+                    Bitmap bm = ImageDecoder.decodeBitmap(src, (decoder, info, s) -> {
+                        decoder.setTargetColorSpace(cs);
+                    });
+                    // If the ColorSpace does not match the request, it should be because
+                    // F16 + HARDWARE is not supported. In that case, it should match the non-
+                    // EXTENDED variant.
+                    ColorSpace actual = bm.getColorSpace();
+                    if (actual != cs) {
+                        assertEquals(BitmapTest.ANDROID_BITMAP_FORMAT_RGBA_8888,
+                                     BitmapTest.nGetFormat(bm));
+                        if (cs == EXTENDED_SRGB) {
+                            assertSame(ColorSpace.get(ColorSpace.Named.SRGB), actual);
+                        } else {
+                            assertSame(ColorSpace.get(ColorSpace.Named.LINEAR_SRGB), actual);
+                        }
+                    }
+                } catch (IOException e) {
+                    fail("Failed to decode asset " + record.name + " to " + cs + " with " + e);
+                }
+            }
+        }
+    }
+
     private boolean isExtended(ColorSpace colorSpace) {
         return colorSpace == ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB)
             || colorSpace == ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB);
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/GradientDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/GradientDrawableTest.java
index 5516727..eb92789 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/GradientDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/GradientDrawableTest.java
@@ -48,6 +48,7 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.xmlpull.v1.XmlPullParser;
@@ -750,8 +751,14 @@
         assertEquals(Orientation.TOP_BOTTOM, drawable.getOrientation());
     }
 
+
+    @Ignore("Disabling temporarily while actual fix to maintain behavioral differences of "
+            + "orientation xml and programmatically defined GradientDrawables")
     @Test
     public void testGradientNoAngle() {
+        // Verify that the default orientation for a GradientDrawable defined in xml is
+        // LEFT_RIGHT. This differs from the default behavior of programmatically defined
+        // GradientDrawables
         final Context context = InstrumentationRegistry.getTargetContext();
         GradientDrawable drawable = (GradientDrawable)
                 context.getDrawable(R.drawable.gradientdrawable_no_angle);
@@ -759,6 +766,14 @@
     }
 
     @Test
+    public void testDynamicGradientDefaultOrientation() {
+        // Verify that the default orientation for a programmatically defined GradientDrawable is
+        // TOP_BOTTOM. This differs from the default behavior of xml inflated GradientDrawables
+        // that default to LEFT_RIGHT
+        assertEquals(Orientation.TOP_BOTTOM, new GradientDrawable().getOrientation());
+    }
+
+    @Test
     public void testGradientDrawableOrientationConstructor() {
         GradientDrawable drawable = new GradientDrawable(Orientation.TOP_BOTTOM, null);
         assertEquals(Orientation.TOP_BOTTOM, drawable.getOrientation());
diff --git a/tests/tests/hardware/res/raw/asus_gamepad_register.json b/tests/tests/hardware/res/raw/asus_gamepad_register.json
index cfd71eb..dd422a4 100644
--- a/tests/tests/hardware/res/raw/asus_gamepad_register.json
+++ b/tests/tests/hardware/res/raw/asus_gamepad_register.json
@@ -1,9 +1,9 @@
 {
   "id": 1,
   "command": "register",
-  "name": "Odie (Test)",
-  "vid": 0x18d1,
-  "pid": 0x2c40,
+  "name": "Asus Gamepad (Test)",
+  "vid": 0x0b05,
+  "pid": 0x4500,
   "descriptor": [0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01, 0x05, 0x09, 0x0a, 0x01, 0x00,
     0x0a, 0x02, 0x00, 0x0a, 0x04, 0x00, 0x0a, 0x05, 0x00, 0x0a, 0x07, 0x00, 0x0a, 0x08, 0x00,
     0x0a, 0x0e, 0x00, 0x0a, 0x0f, 0x00, 0x0a, 0x0d, 0x00, 0x05, 0x0c, 0x0a, 0x24, 0x02, 0x0a,
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 9e45b10..045d382 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -16,9 +16,6 @@
 
 package android.keystore.cts;
 
-import android.os.SystemProperties;
-import android.platform.test.annotations.RestrictedBuildTest;
-
 import static android.keystore.cts.Attestation.KM_SECURITY_LEVEL_SOFTWARE;
 import static android.keystore.cts.Attestation.KM_SECURITY_LEVEL_STRONG_BOX;
 import static android.keystore.cts.Attestation.KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
@@ -48,17 +45,18 @@
 import static android.security.keystore.KeyProperties.PURPOSE_VERIFY;
 import static android.security.keystore.KeyProperties.SIGNATURE_PADDING_RSA_PKCS1;
 import static android.security.keystore.KeyProperties.SIGNATURE_PADDING_RSA_PSS;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.either;
-import static org.junit.matchers.JUnitMatchers.hasItems;
 
-import com.google.common.collect.ImmutableSet;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.either;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.hasItems;
+
 import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.Context;
 import android.os.Build;
 import android.os.SystemProperties;
+import android.platform.test.annotations.RestrictedBuildTest;
 import android.security.KeyStoreException;
 import android.security.keystore.AttestationUtils;
 import android.security.keystore.DeviceIdAttestationException;
@@ -67,6 +65,8 @@
 import android.test.AndroidTestCase;
 import android.util.ArraySet;
 
+import com.google.common.collect.ImmutableSet;
+
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 
@@ -590,6 +590,7 @@
     private void checkKeyIndependentAttestationInfo(byte[] challenge, int purposes, Date startTime,
             boolean includesValidityDates, Attestation attestation)
             throws NoSuchAlgorithmException, NameNotFoundException {
+        checkUnexpectedOids(attestation);
         checkAttestationSecurityLevelDependentParams(attestation);
         assertNotNull(attestation.getAttestationChallenge());
         assertTrue(Arrays.equals(challenge, attestation.getAttestationChallenge()));
@@ -604,6 +605,11 @@
         checkAttestationApplicationId(attestation);
     }
 
+    private void checkUnexpectedOids(Attestation attestation) {
+        assertThat("Attestations must not contain any extra data",
+                attestation.getUnexpectedExtensionOids(), is(empty()));
+    }
+
     private int getSystemPatchLevel() {
         Matcher matcher = OS_PATCH_LEVEL_STRING_PATTERN.matcher(Build.VERSION.SECURITY_PATCH);
         assertTrue(matcher.matches());
diff --git a/tests/tests/location/Android.bp b/tests/tests/location/Android.bp
index 9d9e6c0..a960b1e 100644
--- a/tests/tests/location/Android.bp
+++ b/tests/tests/location/Android.bp
@@ -43,7 +43,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     libs: [
         "telephony-common",
diff --git a/tests/tests/location2/Android.bp b/tests/tests/location2/Android.bp
index 5cc43b1..0dc648d 100644
--- a/tests/tests/location2/Android.bp
+++ b/tests/tests/location2/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     static_libs: [
         "ctstestrunner-axt",
diff --git a/tests/tests/media/Android.bp b/tests/tests/media/Android.bp
index eec4cd8..0d2f5b9 100644
--- a/tests/tests/media/Android.bp
+++ b/tests/tests/media/Android.bp
@@ -72,7 +72,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
         "mts",
     ],
     host_required: ["cts-dynamic-config"],
diff --git a/tests/tests/media/src/android/media/cts/.goutputstream-9KZYJZ b/tests/tests/media/src/android/media/cts/.goutputstream-9KZYJZ
deleted file mode 100644
index c1769ac..0000000
--- a/tests/tests/media/src/android/media/cts/.goutputstream-9KZYJZ
+++ /dev/null
@@ -1,814 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.media.cts;
-
-import android.media.BufferingParams;
-import android.media.DataSourceDesc;
-import android.media.MediaFormat;
-import android.media.MediaPlayer2;
-import android.media.MediaPlayer2.TrackInfo;
-import android.media.TimedMetaData;
-import android.media.cts.TestUtils.Monitor;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Looper;
-import android.os.PowerManager;
-import android.os.SystemClock;
-import android.platform.test.annotations.AppModeFull;
-import android.test.InstrumentationTestRunner;
-import android.util.Log;
-import android.webkit.cts.CtsTestServer;
-
-import com.android.compatibility.common.util.DynamicConfigDeviceSide;
-import com.android.compatibility.common.util.MediaUtils;
-
-import java.net.HttpCookie;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.HashMap;
-import java.util.List;
-
-/**
- * Tests of MediaPlayer2 streaming capabilities.
- */
-@AppModeFull(reason = "TODO: evaluate and port to instant")
-public class StreamingMediaPlayer2Test extends MediaPlayer2TestBase {
-    // TODO: remove this flag to enable tests.
-    private static final boolean IGNORE_TESTS = true;
-
-    private static final String TAG = "StreamingMediaPlayer2Test";
-
-    private static final String HTTP_H263_AMR_VIDEO_1_KEY =
-            "streaming_media_player_test_http_h263_amr_video1";
-    private static final String HTTP_H263_AMR_VIDEO_2_KEY =
-            "streaming_media_player_test_http_h263_amr_video2";
-    private static final String HTTP_H264_BASE_AAC_VIDEO_1_KEY =
-            "streaming_media_player_test_http_h264_base_aac_video1";
-    private static final String HTTP_H264_BASE_AAC_VIDEO_2_KEY =
-            "streaming_media_player_test_http_h264_base_aac_video2";
-    private static final String HTTP_MPEG4_SP_AAC_VIDEO_1_KEY =
-            "streaming_media_player_test_http_mpeg4_sp_aac_video1";
-    private static final String HTTP_MPEG4_SP_AAC_VIDEO_2_KEY =
-            "streaming_media_player_test_http_mpeg4_sp_aac_video2";
-    private static final String MODULE_NAME = "CtsMediaTestCases";
-    private DynamicConfigDeviceSide dynamicConfig;
-
-    private CtsTestServer mServer;
-
-    private String mInputUrl;
-
-    @Override
-    protected void setUp() throws Exception {
-        // if launched with InstrumentationTestRunner to pass a command line argument
-        if (getInstrumentation() instanceof InstrumentationTestRunner) {
-            InstrumentationTestRunner testRunner =
-                    (InstrumentationTestRunner)getInstrumentation();
-
-            Bundle arguments = testRunner.getArguments();
-            mInputUrl = arguments.getString("url");
-            Log.v(TAG, "setUp: arguments: " + arguments);
-            if (mInputUrl != null) {
-                Log.v(TAG, "setUp: arguments[url] " + mInputUrl);
-            }
-        }
-
-        super.setUp();
-        dynamicConfig = new DynamicConfigDeviceSide(MODULE_NAME);
-    }
-
-/* RTSP tests are more flaky and vulnerable to network condition.
-   Disable until better solution is available
-    // Streaming RTSP video from YouTube
-    public void testRTSP_H263_AMR_Video1() throws Exception {
-        playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0x271de9756065677e"
-                + "&fmt=13&user=android-device-test", 176, 144);
-    }
-    public void testRTSP_H263_AMR_Video2() throws Exception {
-        playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0xc80658495af60617"
-                + "&fmt=13&user=android-device-test", 176, 144);
-    }
-
-    public void testRTSP_MPEG4SP_AAC_Video1() throws Exception {
-        playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0x271de9756065677e"
-                + "&fmt=17&user=android-device-test", 176, 144);
-    }
-    public void testRTSP_MPEG4SP_AAC_Video2() throws Exception {
-        playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0xc80658495af60617"
-                + "&fmt=17&user=android-device-test", 176, 144);
-    }
-
-    public void testRTSP_H264Base_AAC_Video1() throws Exception {
-        playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0x271de9756065677e"
-                + "&fmt=18&user=android-device-test", 480, 270);
-    }
-    public void testRTSP_H264Base_AAC_Video2() throws Exception {
-        playVideoTest("rtsp://v2.cache7.c.youtube.com/video.3gp?cid=0xc80658495af60617"
-                + "&fmt=18&user=android-device-test", 480, 270);
-    }
-*/
-    // Streaming HTTP video from YouTube
-    public void testHTTP_H263_AMR_Video1() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_H263,
-                  MediaFormat.MIMETYPE_AUDIO_AMR_NB)) {
-            return; // skip
-        }
-
-        String urlString = dynamicConfig.getValue(HTTP_H263_AMR_VIDEO_1_KEY);
-        playVideoTest(urlString, 176, 144);
-    }
-
-    public void testHTTP_H263_AMR_Video2() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_H263,
-                  MediaFormat.MIMETYPE_AUDIO_AMR_NB)) {
-            return; // skip
-        }
-
-        String urlString = dynamicConfig.getValue(HTTP_H263_AMR_VIDEO_2_KEY);
-        playVideoTest(urlString, 176, 144);
-    }
-
-    public void testHTTP_MPEG4SP_AAC_Video1() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_MPEG4)) {
-            return; // skip
-        }
-
-        String urlString = dynamicConfig.getValue(HTTP_MPEG4_SP_AAC_VIDEO_1_KEY);
-        playVideoTest(urlString, 176, 144);
-    }
-
-    public void testHTTP_MPEG4SP_AAC_Video2() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_MPEG4)) {
-            return; // skip
-        }
-
-        String urlString = dynamicConfig.getValue(HTTP_MPEG4_SP_AAC_VIDEO_2_KEY);
-        playVideoTest(urlString, 176, 144);
-    }
-
-    public void testHTTP_H264Base_AAC_Video1() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-
-        String urlString = dynamicConfig.getValue(HTTP_H264_BASE_AAC_VIDEO_1_KEY);
-        playVideoTest(urlString, 640, 360);
-    }
-
-    public void testHTTP_H264Base_AAC_Video2() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-
-        String urlString = dynamicConfig.getValue(HTTP_H264_BASE_AAC_VIDEO_2_KEY);
-        playVideoTest(urlString, 640, 360);
-    }
-
-    // Streaming HLS video from YouTube
-    public void testHLS() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-
-        // Play stream for 60 seconds
-        playLiveVideoTest("http://www.youtube.com/api/manifest/hls_variant/id/"
-                + "0168724d02bd9945/itag/5/source/youtube/playlist_type/DVR/ip/"
-                + "0.0.0.0/ipbits/0/expire/19000000000/sparams/ip,ipbits,expire"
-                + ",id,itag,source,playlist_type/signature/773AB8ACC68A96E5AA48"
-                + "1996AD6A1BBCB70DCB87.95733B544ACC5F01A1223A837D2CF04DF85A336"
-                + "0/key/ik0/file/m3u8", 60 * 1000);
-    }
-
-    public void testHlsWithHeadersCookies() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-
-        final Uri uri = Uri.parse(
-                "http://www.youtube.com/api/manifest/hls_variant/id/"
-                + "0168724d02bd9945/itag/5/source/youtube/playlist_type/DVR/ip/"
-                + "0.0.0.0/ipbits/0/expire/19000000000/sparams/ip,ipbits,expire"
-                + ",id,itag,source,playlist_type/signature/773AB8ACC68A96E5AA48"
-                + "1996AD6A1BBCB70DCB87.95733B544ACC5F01A1223A837D2CF04DF85A336"
-                + "0/key/ik0/file/m3u8");
-
-        // TODO: dummy values for headers/cookies till we find a server that actually needs them
-        HashMap<String, String> headers = new HashMap<>();
-        headers.put("header0", "value0");
-        headers.put("header1", "value1");
-
-        String cookieName = "auth_1234567";
-        String cookieValue = "0123456789ABCDEF0123456789ABCDEF";
-        HttpCookie cookie = new HttpCookie(cookieName, cookieValue);
-        cookie.setHttpOnly(true);
-        cookie.setDomain("www.youtube.com");
-        cookie.setPath("/");        // all paths
-        cookie.setSecure(false);
-        cookie.setDiscard(false);
-        cookie.setMaxAge(24 * 3600);  // 24hrs
-
-        java.util.Vector<HttpCookie> cookies = new java.util.Vector<HttpCookie>();
-        cookies.add(cookie);
-
-        // Play stream for 60 seconds
-        playLiveVideoTest(uri, headers, cookies, 60 * 1000);
-    }
-
-    public void testHlsSampleAes_bbb_audio_only_overridable() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-
-        String defaultUrl = "http://storage.googleapis.com/wvmedia/cenc/hls/sample_aes/" +
-                            "bbb_1080p_30fps_11min/audio_only/prog_index.m3u8";
-
-        // if url override provided
-        String testUrl = (mInputUrl != null) ? mInputUrl : defaultUrl;
-
-        // Play stream for 60 seconds
-        playLiveAudioOnlyTest(
-                testUrl,
-                60 * 1000);
-    }
-
-    public void testHlsSampleAes_bbb_unmuxed_1500k() throws Exception {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-
-        // Play stream for 60 seconds
-        playLiveVideoTest(
-                "http://storage.googleapis.com/wvmedia/cenc/hls/sample_aes/" +
-                "bbb_1080p_30fps_11min/unmuxed_1500k/prog_index.m3u8",
-                60 * 1000);
-    }
-
-
-    // Streaming audio from local HTTP server
-    public void testPlayMp3Stream1() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("ringer.mp3", false, false);
-    }
-    public void testPlayMp3Stream2() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("ringer.mp3", false, false);
-    }
-    public void testPlayMp3StreamRedirect() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("ringer.mp3", true, false);
-    }
-    public void testPlayMp3StreamNoLength() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("noiseandchirps.mp3", false, true);
-    }
-    public void testPlayOggStream() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("noiseandchirps.ogg", false, false);
-    }
-    public void testPlayOggStreamRedirect() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("noiseandchirps.ogg", true, false);
-    }
-    public void testPlayOggStreamNoLength() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpAudioStreamTest("noiseandchirps.ogg", false, true);
-    }
-    public void testPlayMp3Stream1Ssl() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        localHttpsAudioStreamTest("ringer.mp3", false, false);
-    }
-
-    private void localHttpAudioStreamTest(final String name, boolean redirect, boolean nolength)
-            throws Throwable {
-        mServer = new CtsTestServer(mContext);
-        try {
-            String stream_url = null;
-            if (redirect) {
-                // Stagefright doesn't have a limit, but we can't test support of infinite redirects
-                // Up to 4 redirects seems reasonable though.
-                stream_url = mServer.getRedirectingAssetUrl(name, 4);
-            } else {
-                stream_url = mServer.getAssetUrl(name);
-            }
-            if (nolength) {
-                stream_url = stream_url + "?" + CtsTestServer.NOLENGTH_POSTFIX;
-            }
-
-            if (!MediaUtils.checkCodecsForPath(mContext, stream_url)) {
-                return; // skip
-            }
-
-            final Uri uri = Uri.parse(stream_url);
-            mPlayer.setDataSource(new DataSourceDesc.Builder()
-                    .setDataSource(mContext, uri)
-                    .build());
-
-            mPlayer.setDisplay(getActivity().getSurfaceHolder());
-            mPlayer.setScreenOnWhilePlaying(true);
-
-            mOnBufferingUpdateCalled.reset();
-            MediaPlayer2.MediaPlayer2EventCallback ecb =
-                new MediaPlayer2.MediaPlayer2EventCallback() {
-                    @Override
-                    public void onError(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        fail("Media player had error " + what + " playing " + name);
-                    }
-
-                    @Override
-                    public void onInfo(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        if (what == MediaPlayer2.MEDIA_INFO_PREPARED) {
-                            mOnPrepareCalled.signal();
-                        } else if (what == MediaPlayer2.MEDIA_INFO_BUFFERING_UPDATE) {
-                            mOnBufferingUpdateCalled.signal();
-                        }
-                    }
-                };
-            mPlayer.setMediaPlayer2EventCallback(mExecutor, ecb);
-
-            assertFalse(mOnBufferingUpdateCalled.isSignalled());
-
-            mPlayer.prepare();
-            mOnPrepareCalled.waitForSignal();
-
-            if (nolength) {
-                mPlayer.play();
-                Thread.sleep(LONG_SLEEP_TIME);
-                assertFalse(mPlayer.isPlaying());
-            } else {
-                mOnBufferingUpdateCalled.waitForSignal();
-                mPlayer.play();
-                Thread.sleep(SLEEP_TIME);
-            }
-            mPlayer.stop();
-            mPlayer.reset();
-        } finally {
-            mServer.shutdown();
-        }
-    }
-    private void localHttpsAudioStreamTest(final String name, boolean redirect, boolean nolength)
-            throws Throwable {
-        mServer = new CtsTestServer(mContext, true);
-        try {
-            String stream_url = null;
-            if (redirect) {
-                // Stagefright doesn't have a limit, but we can't test support of infinite redirects
-                // Up to 4 redirects seems reasonable though.
-                stream_url = mServer.getRedirectingAssetUrl(name, 4);
-            } else {
-                stream_url = mServer.getAssetUrl(name);
-            }
-            if (nolength) {
-                stream_url = stream_url + "?" + CtsTestServer.NOLENGTH_POSTFIX;
-            }
-
-            final Uri uri = Uri.parse(stream_url);
-            mPlayer.setDataSource(new DataSourceDesc.Builder()
-                    .setDataSource(mContext, uri)
-                    .build());
-
-            mPlayer.setDisplay(getActivity().getSurfaceHolder());
-            mPlayer.setScreenOnWhilePlaying(true);
-
-            mOnBufferingUpdateCalled.reset();
-
-            MediaPlayer2.MediaPlayer2EventCallback ecb =
-                new MediaPlayer2.MediaPlayer2EventCallback() {
-                    @Override
-                    public void onError(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        mOnErrorCalled.signal();
-                    }
-
-                    @Override
-                    public void onInfo(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        if (what == MediaPlayer2.MEDIA_INFO_PREPARED) {
-                            mOnPrepareCalled.signal();
-                        } else if (what == MediaPlayer2.MEDIA_INFO_BUFFERING_UPDATE) {
-                            mOnBufferingUpdateCalled.signal();
-                        }
-                    }
-                };
-            mPlayer.setMediaPlayer2EventCallback(mExecutor, ecb);
-
-            assertFalse(mOnBufferingUpdateCalled.isSignalled());
-            try {
-                mPlayer.prepare();
-                mOnErrorCalled.waitForSignal();
-            } catch (Exception ex) {
-                return;
-            }
-        } finally {
-            mServer.shutdown();
-        }
-    }
-
-    // TODO: unhide this test when we sort out how to expose buffering control API.
-    private void doTestBuffering() throws Throwable {
-        final String name = "ringer.mp3";
-        mServer = new CtsTestServer(mContext);
-        try {
-            String stream_url = mServer.getAssetUrl(name);
-
-            if (!MediaUtils.checkCodecsForPath(mContext, stream_url)) {
-                Log.w(TAG, "can not find stream " + stream_url + ", skipping test");
-                return; // skip
-            }
-
-            Monitor onSetBufferingParamsCalled = new Monitor();
-            MediaPlayer2.MediaPlayer2EventCallback ecb =
-                new MediaPlayer2.MediaPlayer2EventCallback() {
-                    @Override
-                    public void onError(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        fail("Media player had error " + what + " playing " + name);
-                    }
-                    @Override
-                    public void onInfo(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        if (what == MediaPlayer2.MEDIA_INFO_BUFFERING_UPDATE) {
-                            mOnBufferingUpdateCalled.signal();
-                        }
-                    }
-                    @Override
-                    public void onCallCompleted(MediaPlayer2 mp, DataSourceDesc dsd,
-                            int what, int status) {
-                        if (what == MediaPlayer2.CALL_COMPLETED_SET_BUFFERING_PARAMS) {
-                            mCallStatus = status;
-                            onSetBufferingParamsCalled.signal();
-                        }
-                    }
-                };
-            mPlayer.setMediaPlayer2EventCallback(mExecutor, ecb);
-
-            // getBufferingParams should be called after setDataSource.
-            try {
-                BufferingParams params = mPlayer.getBufferingParams();
-                fail("MediaPlayer2 failed to check state for getBufferingParams");
-            } catch (IllegalStateException e) {
-                // expected
-            }
-
-            // setBufferingParams should be called after setDataSource.
-            BufferingParams params = new BufferingParams.Builder()
-                    .setInitialMarkMs(2)
-                    .setResumePlaybackMarkMs(3)
-                    .build();
-            mCallStatus = MediaPlayer2.CALL_STATUS_NO_ERROR;
-            onSetBufferingParamsCalled.reset();
-            mPlayer.setBufferingParams(params);
-            onSetBufferingParamsCalled.waitForSignal();
-            assertTrue(mCallStatus != MediaPlayer2.CALL_STATUS_NO_ERROR);
-
-            final Uri uri = Uri.parse(stream_url);
-            mPlayer.setDataSource(new DataSourceDesc.Builder()
-                    .setDataSource(mContext, uri)
-                    .build());
-
-            mPlayer.setDisplay(getActivity().getSurfaceHolder());
-            mPlayer.setScreenOnWhilePlaying(true);
-
-            mOnBufferingUpdateCalled.reset();
-
-            assertFalse(mOnBufferingUpdateCalled.isSignalled());
-
-            params = mPlayer.getBufferingParams();
-
-            int newMark = params.getInitialMarkMs() + 2;
-            BufferingParams newParams =
-                    new BufferingParams.Builder(params).setInitialMarkMs(newMark).build();
-
-            onSetBufferingParamsCalled.reset();
-            mPlayer.setBufferingParams(newParams);
-            onSetBufferingParamsCalled.waitForSignal();
-
-            int checkMark = -1;
-            BufferingParams checkParams = mPlayer.getBufferingParams();
-            checkMark = checkParams.getInitialMarkMs();
-            assertEquals("marks do not match", newMark, checkMark);
-
-            // TODO: add more dynamic checking, e.g., buffering shall not exceed pre-set mark.
-
-            mPlayer.reset();
-        } finally {
-            mServer.shutdown();
-        }
-    }
-
-    public void testPlayHlsStream() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-        localHlsTest("hls.m3u8", false, false);
-    }
-
-    public void testPlayHlsStreamWithQueryString() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-        localHlsTest("hls.m3u8", true, false);
-    }
-
-    public void testPlayHlsStreamWithRedirect() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            return; // skip
-        }
-        localHlsTest("hls.m3u8", false, true);
-    }
-
-    public void testPlayHlsStreamWithTimedId3() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) {
-            Log.d(TAG, "Device doesn't have video codec, skipping test");
-            return;
-        }
-
-        mServer = new CtsTestServer(mContext);
-        try {
-            // counter must be final if we want to access it inside onTimedMetaData;
-            // use AtomicInteger so we can have a final counter object with mutable integer value.
-            final AtomicInteger counter = new AtomicInteger();
-            String stream_url = mServer.getAssetUrl("prog_index.m3u8");
-            final Uri uri = Uri.parse(stream_url);
-            mPlayer.setDataSource(new DataSourceDesc.Builder()
-                    .setDataSource(mContext, uri)
-                    .build());
-            mPlayer.setDisplay(getActivity().getSurfaceHolder());
-            mPlayer.setScreenOnWhilePlaying(true);
-            mPlayer.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
-
-            final Object completion = new Object();
-            MediaPlayer2.MediaPlayer2EventCallback ecb =
-                new MediaPlayer2.MediaPlayer2EventCallback() {
-                    int run;
-                    @Override
-                    public void onInfo(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        if (what == MediaPlayer2.MEDIA_INFO_PREPARED) {
-                            mOnPrepareCalled.signal();
-                        } else if (what == MediaPlayer2.MEDIA_INFO_PLAYBACK_COMPLETE) {
-                            if (run++ == 0) {
-                                mPlayer.seekTo(0, MediaPlayer2.SEEK_PREVIOUS_SYNC);
-                                mPlayer.play();
-                            } else {
-                                mPlayer.stop();
-                                synchronized (completion) {
-                                    completion.notify();
-                                }
-                            }
-                        }
-                    }
-
-                @Override
-                public void onTimedMetaDataAvailable(MediaPlayer2 mp, DataSourceDesc dsd,
-                        TimedMetaData md) {
-                    counter.incrementAndGet();
-                    long pos = mp.getCurrentPosition();
-                    long timeUs = md.getTimestamp();
-                    byte[] rawData = md.getMetaData();
-                    // Raw data contains an id3 tag holding the decimal string representation of
-                    // the associated time stamp rounded to the closest half second.
-
-                    int offset = 0;
-                    offset += 3; // "ID3"
-                    offset += 2; // version
-                    offset += 1; // flags
-                    offset += 4; // size
-                    offset += 4; // "TXXX"
-                    offset += 4; // frame size
-                    offset += 2; // frame flags
-                    offset += 1; // "\x03" : UTF-8 encoded Unicode
-                    offset += 1; // "\x00" : null-terminated empty description
-
-                    int length = rawData.length;
-                    length -= offset;
-                    length -= 1; // "\x00" : terminating null
-
-                    String data = new String(rawData, offset, length);
-                    int dataTimeUs = Integer.parseInt(data);
-                    assertTrue("Timed ID3 timestamp does not match content",
-                            Math.abs(dataTimeUs - timeUs) < 500000);
-                    assertTrue("Timed ID3 arrives after timestamp", pos * 1000 < timeUs);
-                }
-
-                @Override
-                public void onCallCompleted(MediaPlayer2 mp, DataSourceDesc dsd,
-                        int what, int status) {
-                    if (what == MediaPlayer2.CALL_COMPLETED_PLAY) {
-                        mOnPlayCalled.signal();
-                    }
-                }
-            };
-            mPlayer.setMediaPlayer2EventCallback(mExecutor, ecb);
-
-            mPlayer.prepare();
-            mOnPrepareCalled.waitForSignal();
-
-            mOnPlayCalled.reset();
-            mPlayer.play();
-            mOnPlayCalled.waitForSignal();
-            assertTrue("MediaPlayer2 not playing", mPlayer.isPlaying());
-
-            int i = -1;
-            List<TrackInfo> trackInfos = mPlayer.getTrackInfo();
-            for (i = 0; i < trackInfos.size(); i++) {
-                TrackInfo trackInfo = trackInfos.get(i);
-                if (trackInfo.getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_METADATA) {
-                    break;
-                }
-            }
-            assertTrue("Stream has no timed ID3 track", i >= 0);
-            mPlayer.selectTrack(i);
-
-            synchronized (completion) {
-                completion.wait();
-            }
-
-            // There are a total of 19 metadata access units in the test stream; every one of them
-            // should be received twice: once before the seek and once after.
-            assertTrue("Incorrect number of timed ID3s recieved", counter.get() == 38);
-        } finally {
-            mServer.shutdown();
-        }
-    }
-
-    private static class WorkerWithPlayer implements Runnable {
-        private final Object mLock = new Object();
-        private Looper mLooper;
-        private MediaPlayer2 mPlayer;
-
-        /**
-         * Creates a worker thread with the given name. The thread
-         * then runs a {@link android.os.Looper}.
-         * @param name A name for the new thread
-         */
-        WorkerWithPlayer(String name) {
-            Thread t = new Thread(null, this, name);
-            t.setPriority(Thread.MIN_PRIORITY);
-            t.start();
-            synchronized (mLock) {
-                while (mLooper == null) {
-                    try {
-                        mLock.wait();
-                    } catch (InterruptedException ex) {
-                    }
-                }
-            }
-        }
-
-        public MediaPlayer2 getPlayer() {
-            return mPlayer;
-        }
-
-        @Override
-        public void run() {
-            synchronized (mLock) {
-                Looper.prepare();
-                mLooper = Looper.myLooper();
-                mPlayer = MediaPlayer2.create();
-                mLock.notifyAll();
-            }
-            Looper.loop();
-        }
-
-        public void quit() {
-            mLooper.quit();
-            mPlayer.close();
-        }
-    }
-
-    public void testBlockingReadRelease() throws Throwable {
-        if (IGNORE_TESTS) {
-            return;
-        }
-
-        mServer = new CtsTestServer(mContext);
-
-        WorkerWithPlayer worker = new WorkerWithPlayer("player");
-        final MediaPlayer2 mp = worker.getPlayer();
-
-        try {
-            String path = mServer.getDelayedAssetUrl("noiseandchirps.ogg", 15000);
-            final Uri uri = Uri.parse(path);
-            mp.setDataSource(new DataSourceDesc.Builder()
-                    .setDataSource(mContext, uri)
-                    .build());
-
-            MediaPlayer2.MediaPlayer2EventCallback ecb =
-                new MediaPlayer2.MediaPlayer2EventCallback() {
-                    @Override
-                    public void onInfo(MediaPlayer2 mp, DataSourceDesc dsd, int what, int extra) {
-                        if (what == MediaPlayer2.MEDIA_INFO_PREPARED) {
-                            fail("prepare should not succeed");
-                        }
-                    }
-                };
-            mp.setMediaPlayer2EventCallback(mExecutor, ecb);
-
-            mp.prepare();
-            Thread.sleep(1000);
-            long start = SystemClock.elapsedRealtime();
-            mp.close();
-            long end = SystemClock.elapsedRealtime();
-            long releaseDuration = (end - start);
-            assertTrue("release took too long: " + releaseDuration, releaseDuration < 1000);
-        } catch (IllegalArgumentException e) {
-            fail(e.getMessage());
-        } catch (SecurityException e) {
-            fail(e.getMessage());
-        } catch (IllegalStateException e) {
-            fail(e.getMessage());
-        } catch (InterruptedException e) {
-            fail(e.getMessage());
-        } finally {
-            mServer.shutdown();
-        }
-
-        // give the worker a bit of time to start processing the message before shutting it down
-        Thread.sleep(5000);
-        worker.quit();
-    }
-
-    private void localHlsTest(final String name, boolean appendQueryString, boolean redirect)
-            throws Throwable {
-        mServer = new CtsTestServer(mContext);
-        try {
-            String stream_url = null;
-            if (redirect) {
-                stream_url = mServer.getQueryRedirectingAssetUrl(name);
-            } else {
-                stream_url = mServer.getAssetUrl(name);
-            }
-            if (appendQueryString) {
-                stream_url += "?foo=bar/baz";
-            }
-
-            playLiveVideoTest(stream_url, 10);
-        } finally {
-            mServer.shutdown();
-        }
-    }
-}
diff --git a/tests/tests/media/src/android/media/cts/AudioRecordTest.java b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
index ddd1be7..a38f8a70 100644
--- a/tests/tests/media/src/android/media/cts/AudioRecordTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
@@ -42,6 +42,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.PersistableBundle;
+import android.os.Process;
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.util.Log;
@@ -631,12 +632,14 @@
         }
 
         AudioRecord recorder = null;
+        String packageName = InstrumentationRegistry.getTargetContext().getPackageName();
+        int currentUserId = Process.myUserHandle().getIdentifier();
 
         // We will record audio for 20 sec from active and idle state expecting
         // the recording from active state to have data while from idle silence.
         try {
             // Ensure no race and UID active
-            makeMyUidStateActive();
+            makeMyUidStateActive(packageName, currentUserId);
 
             // Setup a recorder
             final AudioRecord candidateRecorder = new AudioRecord.Builder()
@@ -670,7 +673,7 @@
             // Start clean
             buffer.clear();
             // Force idle the package
-            makeMyUidStateIdle();
+            makeMyUidStateIdle(packageName, currentUserId);
             // Read five seconds of data
             readDataTimed(recorder, 5000, buffer);
             // Ensure we read empty bytes
@@ -679,7 +682,7 @@
             // Start clean
             buffer.clear();
             // Reset to active
-            makeMyUidStateActive();
+            makeMyUidStateActive(packageName, currentUserId);
             // Read five seconds of data
             readDataTimed(recorder, 5000, buffer);
             // Ensure we read non-empty bytes
@@ -689,7 +692,7 @@
                 recorder.stop();
                 recorder.release();
             }
-            resetMyUidState();
+            resetMyUidState(packageName, currentUserId);
         }
     }
 
@@ -1629,21 +1632,21 @@
         return totalSilenceCount > valueCount / 2;
     }
 
-    private static void makeMyUidStateActive() throws IOException {
-        final String command = "cmd media.audio_policy set-uid-state "
-                + InstrumentationRegistry.getTargetContext().getPackageName() + " active";
+    private static void makeMyUidStateActive(String packageName, int userId) throws IOException {
+        final String command = String.format(
+                "cmd media.audio_policy set-uid-state %s active --user %d", packageName, userId);
         SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(), command);
     }
 
-    private static void makeMyUidStateIdle() throws IOException {
-        final String command = "cmd media.audio_policy set-uid-state "
-                + InstrumentationRegistry.getTargetContext().getPackageName() + " idle";
+    private static void makeMyUidStateIdle(String packageName, int userId) throws IOException {
+        final String command = String.format(
+                "cmd media.audio_policy set-uid-state %s idle --user %d", packageName, userId);
         SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(), command);
     }
 
-    private static void resetMyUidState() throws IOException {
-        final String command = "cmd media.audio_policy reset-uid-state "
-                +  InstrumentationRegistry.getTargetContext().getPackageName();
+    private static void resetMyUidState(String packageName, int userId) throws IOException {
+        final String command = String.format(
+                "cmd media.audio_policy reset-uid-state %s --user %d", packageName, userId);
         SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(), command);
     }
 
diff --git a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
index f7231fd..e1c3d28 100644
--- a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
@@ -138,10 +138,25 @@
                 "Test album",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
 
+        assertNull("Album artist was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST));
+
+        assertNull("Author was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR));
+
+        assertNull("Composer was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPOSER));
+
         assertEquals("Track number was other than expected",
                 "10",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER));
 
+        assertNull("Disc number was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER));
+
+        assertNull("Compilation was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPILATION));
+
         assertEquals("Year was other than expected",
                 "2013", mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR));
 
@@ -149,7 +164,59 @@
                 "19040101T000000.000Z",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE));
 
-        assertNull("Writer was unexpected present",
+        assertEquals("Bitrate was other than expected",
+                "365018",  // = 504045 (file size in byte) * 8e6 / 11047000 (duration in us)
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
+
+        assertNull("Capture frame rate was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE));
+
+        assertEquals("Duration was other than expected",
+                "11047",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
+
+        assertEquals("Number of tracks was other than expected",
+                "4",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+
+        assertEquals("Has audio was other than expected",
+                "yes",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO));
+
+        assertEquals("Has video was other than expected",
+                "yes",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO));
+
+        assertEquals("Video frame count was other than expected",
+                "172",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT));
+
+        assertEquals("Video height was other than expected",
+                "288",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
+
+        assertEquals("Video width was other than expected",
+                "352",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
+
+        assertEquals("Video rotation was other than expected",
+                "0",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
+
+        assertEquals("Mime type was other than expected",
+                "video/mp4",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE));
+
+        assertNull("Location was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
+
+        assertNull("EXIF length was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_EXIF_LENGTH));
+
+        assertNull("EXIF offset was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_EXIF_OFFSET));
+
+        assertNull("Writer was unexpectedly present",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_WRITER));
     }
 
@@ -167,10 +234,25 @@
                 "Test album",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
 
+        assertNull("Album artist was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST));
+
+        assertNull("Author was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR));
+
+        assertNull("Composer was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPOSER));
+
         assertEquals("Track number was other than expected",
                 "10",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER));
 
+        assertNull("Disc number was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER));
+
+        assertNull("Compilation was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPILATION));
+
         assertEquals("Year was other than expected",
                 "2013", mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR));
 
@@ -178,6 +260,58 @@
                 "19700101T000000.000Z",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE));
 
+        assertEquals("Bitrate was other than expected",
+                "499895",  // = 624869 (file size in byte) * 8e6 / 10000000 (duration in us)
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
+
+        assertNull("Capture frame rate was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE));
+
+        assertEquals("Duration was other than expected",
+                "10000",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
+
+        assertEquals("Number of tracks was other than expected",
+                "2",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS));
+
+        assertEquals("Has audio was other than expected",
+                "yes",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO));
+
+        assertEquals("Has video was other than expected",
+                "yes",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO));
+
+        assertEquals("Video frame count was other than expected",
+                "240",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT));
+
+        assertEquals("Video height was other than expected",
+                "360",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
+
+        assertEquals("Video width was other than expected",
+                "480",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
+
+        assertEquals("Video rotation was other than expected",
+                "0",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
+
+        assertEquals("Mime type was other than expected",
+                "video/mp4",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE));
+
+        assertNull("Location was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION));
+
+        assertNull("EXIF length was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_EXIF_LENGTH));
+
+        assertNull("EXIF offset was unexpectedly present",
+                mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_EXIF_OFFSET));
+
         assertNull("Writer was unexpectedly present",
                 mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_WRITER));
     }
@@ -195,7 +329,7 @@
 
     }
 
-    public void testLargeAlbumArt() {
+    public void testGetEmbeddedPicture() {
         setDataSourceFd(R.raw.largealbumart);
 
         assertNotNull("couldn't retrieve album art", mRetriever.getEmbeddedPicture());
diff --git a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
index d26587b..d36bb53 100644
--- a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
@@ -314,7 +314,8 @@
             // No start offsets for any track.
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, null);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, null, null);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, null, null);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -335,7 +336,8 @@
             // No start offsets for any track.
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, samplesDropSet, null);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, samplesDropSet, null);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, samplesDropSet, null);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -358,7 +360,8 @@
             // No start offsets for any track.
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, samplesDropSet, null);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, samplesDropSet, null);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, samplesDropSet, null);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -379,7 +382,8 @@
             // No start offsets for any track.
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, samplesDropSet, null);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, samplesDropSet, null);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, samplesDropSet, null);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -402,7 +406,8 @@
             // No start offsets for any track.
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, samplesDropSet, null);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, samplesDropSet, null);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, samplesDropSet, null);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -424,7 +429,8 @@
             startOffsetUsVect.add(0);
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, startOffsetUsVect);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, null, startOffsetUsVect);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, null, startOffsetUsVect);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -446,7 +452,104 @@
             startOffsetUsVect.add(400000);
             cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
                 MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, startOffsetUsVect);
-            verifyTimestampsWithSamplesDropSet(sourceId, outputFilePath, null, startOffsetUsVect);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, true /* has B frames */, outputFilePath, null, startOffsetUsVect);
+        } finally {
+            new File(outputFilePath).delete();
+        }
+    }
+
+    /**
+     * Test: make sure if audio/video muxing using MPEG4Writer works when audio
+     * samples start later than video.
+     */
+    public void testTimestampsStartOffsetAudio() throws Exception {
+        int sourceId = R.raw.video_480x360_mp4_h264_500kbps_30fps_aac_stereo_128kbps_44100hz;
+        String outputFilePath =
+                File.createTempFile("MediaMuxerTest_testTimestampsStartOffsetAudio", ".mp4")
+                        .getAbsolutePath();
+        try {
+            Vector<Integer> startOffsetUsVect = new Vector<Integer>();
+            // Video starts at 0us.
+            startOffsetUsVect.add(0);
+            // Audio starts at 50000us.
+            startOffsetUsVect.add(50000);
+            cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
+                    MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, startOffsetUsVect);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, false /* no B frames */, outputFilePath, null, startOffsetUsVect);
+        } finally {
+            new File(outputFilePath).delete();
+        }
+    }
+
+    /**
+     * Test: makes sure if audio/video muxing using MPEG4Writer works when video
+     * samples start later than audio.
+     */
+    public void testTimestampsStartOffsetVideo() throws Exception {
+        int sourceId = R.raw.video_480x360_mp4_h264_500kbps_30fps_aac_stereo_128kbps_44100hz;
+        String outputFilePath =
+                File.createTempFile("MediaMuxerTest_testTimestampsStartOffsetVideo", ".mp4")
+                        .getAbsolutePath();
+        try {
+            Vector<Integer> startOffsetUsVect = new Vector<Integer>();
+            // Video starts at 500000us.
+            startOffsetUsVect.add(500000);
+            // Audio starts at 0us.
+            startOffsetUsVect.add(0);
+            cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
+                    MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, startOffsetUsVect);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, false /* no B frames */, outputFilePath, null, startOffsetUsVect);
+        } finally {
+            new File(outputFilePath).delete();
+        }
+    }
+
+    /**
+     * Test: makes sure if audio/video muxing using MPEG4Writer works when audio and video
+     * tracks start at non-zero start offset and audio samples start later than video.
+     */
+    public void testTimestampsStartOffsetVideoAudio() throws Exception {
+        int sourceId = R.raw.video_480x360_mp4_h264_500kbps_30fps_aac_stereo_128kbps_44100hz;
+        String outputFilePath =
+                File.createTempFile("MediaMuxerTest_testTimestampsStartOffsetAudio", ".mp4")
+                        .getAbsolutePath();
+        try {
+            Vector<Integer> startOffsetUsVect = new Vector<Integer>();
+            // Video starts at 250000us.
+            startOffsetUsVect.add(250000);
+            // Audio starts at 500000us.
+            startOffsetUsVect.add(500000);
+            cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
+                    MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, startOffsetUsVect);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, false /* no B frames */, outputFilePath, null, startOffsetUsVect);
+        } finally {
+            new File(outputFilePath).delete();
+        }
+    }
+
+    /**
+     * Test: makes sure if audio/video muxing using MPEG4Writer works when audio and video
+     * tracks start at non-zero start offset and video samples start later than audio.
+     */
+    public void testTimestampsStartOffsetAudioVideo() throws Exception {
+        int sourceId = R.raw.video_480x360_mp4_h264_500kbps_30fps_aac_stereo_128kbps_44100hz;
+        String outputFilePath =
+                File.createTempFile("MediaMuxerTest_testTimestampsStartOffsetVideo", ".mp4")
+                        .getAbsolutePath();
+        try {
+            Vector<Integer> startOffsetUsVect = new Vector<Integer>();
+            // Video starts at 500000us.
+            startOffsetUsVect.add(500000);
+            // Audio starts at 250000us.
+            startOffsetUsVect.add(250000);
+            cloneMediaWithSamplesDropAndStartOffsets(sourceId, outputFilePath,
+                    MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, null, startOffsetUsVect);
+            verifyTSWithSamplesDropAndStartOffset(
+                    sourceId, false /* no B frames */, outputFilePath, null, startOffsetUsVect);
         } finally {
             new File(outputFilePath).delete();
         }
@@ -467,7 +570,8 @@
                 verifyLocationInFile(outputMediaFile);
             }
             // Verify timestamp of all samples.
-            verifyTimestampsWithSamplesDropSet(srcMedia, outputMediaFile, null, null);
+            verifyTSWithSamplesDropAndStartOffset(
+                    srcMedia, false /* no B frames */,outputMediaFile, null, null);
         } finally {
             new File(outputMediaFile).delete();
         }
@@ -779,7 +883,7 @@
                 if (trackIndex == 0) {
                     ++videoSampleCount;
                     if (VERBOSE) {
-                        Log.i(TAG, "videoSampleCount : " + videoSampleCount);
+                        Log.v(TAG, "videoSampleCount : " + videoSampleCount);
                     }
                     if (videoSampleCount <= muxAllTypeVideoFramesUntilIndex
                             || videoSampleCount == bFrameAfterPFrameIndex) {
@@ -957,10 +1061,15 @@
                 bufferInfo.presentationTimeUs = extractor.getSampleTime();
                 bufferInfo.flags = extractor.getSampleFlags();
                 int trackIndex = extractor.getSampleTrackIndex();
+                if (VERBOSE) {
+                    Log.v(TAG, "TrackIndex:" + trackIndex + " PresentationTimeUs:" +
+                                bufferInfo.presentationTimeUs + " Flags:" + bufferInfo.flags +
+                                " Size(bytes)" + bufferInfo.size);
+                }
                 if (trackIndex == videoTrackIndex) {
                     ++videoSampleCount;
                     if (VERBOSE) {
-                        Log.i(TAG, "videoSampleCount : " + videoSampleCount);
+                        Log.v(TAG, "videoSampleCount : " + videoSampleCount);
                     }
                     if (samplesDropSet == null || (!samplesDropSet.contains(videoSampleCount))) {
                         // Write video frame with start offset adjustment.
@@ -969,7 +1078,7 @@
                     }
                     else {
                         if (VERBOSE) {
-                            Log.i(TAG, "skipped this frame");
+                            Log.v(TAG, "skipped this frame");
                         }
                     }
                 } else {
@@ -1001,8 +1110,9 @@
      * Uses MediaExtractors and checks whether timestamps of all samples except in samplesDropSet
      *  and with start offsets adjustments for each track match.
      */
-    private void verifyTimestampsWithSamplesDropSet(int srcMediaId, String testMediaPath,
-            HashSet<Integer> samplesDropSet, Vector<Integer> startOffsetUsVect) throws IOException {
+    private void verifyTSWithSamplesDropAndStartOffset(int srcMediaId, boolean hasBframes,
+            String testMediaPath, HashSet<Integer> samplesDropSet,
+            Vector<Integer> startOffsetUsVect) throws IOException {
         AssetFileDescriptor srcFd = mResources.openRawResourceFd(srcMediaId);
         MediaExtractor extractorSrc = new MediaExtractor();
         extractorSrc.setDataSource(srcFd.getFileDescriptor(),
@@ -1012,8 +1122,19 @@
 
         int videoTrackIndex = -1;
         int videoStartOffsetUs = 0;
+        int minStartOffsetUs = Integer.MAX_VALUE;
         int trackCount = extractorSrc.getTrackCount();
 
+        // MPEG4Writer makes the start timestamp of an earliest track as zero and adjusts all
+        // other tracks' timestamp accordingly.
+        if (startOffsetUsVect != null) {
+            for (int startOffsetUs : startOffsetUsVect) {
+                minStartOffsetUs = Math.min(startOffsetUs, minStartOffsetUs);
+            }
+        } else {
+            minStartOffsetUs = 0;
+        }
+
         // Select video track.
         for (int i = 0; i < trackCount; i++) {
             MediaFormat format = extractorSrc.getTrackFormat(i);
@@ -1024,8 +1145,8 @@
                 }
                 extractorSrc.selectTrack(videoTrackIndex);
                 extractorTest.selectTrack(videoTrackIndex);
-                checkVideoSamplesTimeStamps(extractorSrc, extractorTest, samplesDropSet,
-                    videoStartOffsetUs);
+                checkVideoSamplesTimeStamps(extractorSrc, hasBframes, extractorTest, samplesDropSet,
+                        videoStartOffsetUs - minStartOffsetUs);
                 extractorSrc.unselectTrack(videoTrackIndex);
                 extractorTest.unselectTrack(videoTrackIndex);
             }
@@ -1044,7 +1165,8 @@
                 }
                 extractorSrc.selectTrack(audioTrackIndex);
                 extractorTest.selectTrack(audioTrackIndex);
-                checkAudioSamplesTimestamps(extractorSrc, extractorTest, audioStartOffsetUs);
+                checkAudioSamplesTimestamps(
+                        extractorSrc, extractorTest, audioStartOffsetUs - minStartOffsetUs);
             }
         }
 
@@ -1054,9 +1176,8 @@
     }
 
     // Check timestamps of all video samples.
-    private void checkVideoSamplesTimeStamps(MediaExtractor extractorSrc,
-                MediaExtractor extractorTest, HashSet<Integer> samplesDropSet,
-                int videoStartOffsetUs) {
+    private void checkVideoSamplesTimeStamps(MediaExtractor extractorSrc, boolean hasBFrames,
+            MediaExtractor extractorTest, HashSet<Integer> samplesDropSet, int videoStartOffsetUs) {
         long srcSampleTimeUs = -1;
         long testSampleTimeUs = -1;
         boolean srcAdvance = false;
@@ -1066,43 +1187,64 @@
         extractorSrc.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
         extractorTest.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
 
+        if (VERBOSE) {
+            Log.v(TAG, "videoSampleCount:" + videoSampleCount);
+            Log.v(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
+                        "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
+        }
+
         do {
             ++videoSampleCount;
             srcSampleTimeUs = extractorSrc.getSampleTime();
             testSampleTimeUs = extractorTest.getSampleTime();
             if (VERBOSE) {
-                Log.i(TAG, "videoSampleCount:" + videoSampleCount);
-                Log.i(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
-                            "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
                 Log.i(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
             }
             if (samplesDropSet == null || !samplesDropSet.contains(videoSampleCount)) {
                 if (srcSampleTimeUs == -1 || testSampleTimeUs == -1) {
                   if (VERBOSE) {
-                    Log.d(TAG, "videoSampleCount:" + videoSampleCount);
-                    Log.d(TAG, "srcUs:" + srcSampleTimeUs + "testUs:" + testSampleTimeUs);
+                      Log.v(TAG, "srcUs:" + srcSampleTimeUs + "testUs:" + testSampleTimeUs);
                   }
                   fail("either source or test track reached end of stream");
                 }
                 // Stts values within 0.1ms(100us) difference are fudged to save too many
                 // stts entries in MPEG4Writer.
-                else if (Math.abs(srcSampleTimeUs + videoStartOffsetUs - testSampleTimeUs) > 100) {
+                // If Bframes are not present, then we manage start offset of video track in the
+                // duration of the first video sample. Second sample onwards has original timestamp.
+                else if (!hasBFrames
+                        && ((videoSampleCount > 1
+                        && Math.abs(srcSampleTimeUs + videoStartOffsetUs - testSampleTimeUs) > 100)
+                        || (videoSampleCount == 1
+                        && Math.abs(srcSampleTimeUs - testSampleTimeUs) > 100))) {
                     if (VERBOSE) {
-                        Log.d(TAG, "Fail:video timestamps didn't match");
-                        Log.d(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
-                            "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
-                        Log.d(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
-                        Log.d(TAG, "videoSampleCount:" + videoSampleCount);
+                        Log.v(TAG, "Fail:video timestamps didn't match");
+                        Log.v(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
+                                    "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
+                        Log.v(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
                     }
                     fail("video timestamps didn't match");
                 }
+                // If Bframes are present, then we manage start offsert of a video track in the
+                // corresponding edit list entry.
+                else if (hasBFrames
+                        && Math.abs(srcSampleTimeUs + videoStartOffsetUs - testSampleTimeUs)
+                        > 100) {
+                    if (VERBOSE) {
+                        Log.v(TAG, "Fail:video timestamps with B frames didn't match");
+                        Log.v(TAG,  "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
+                                    "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
+                        Log.v(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
+                    }
+                    fail("video timestamps with B frames didn't match");
+                }
+
                 testAdvance = extractorTest.advance();
             }
             srcAdvance = extractorSrc.advance();
         } while(srcAdvance && testAdvance);
         if (srcAdvance != testAdvance) {
             if (VERBOSE) {
-                Log.d(TAG, "videoSampleCount:" + videoSampleCount);
+                Log.v(TAG, "videoSampleCount:" + videoSampleCount);
             }
             fail("either video track has not reached its last sample");
         }
@@ -1118,28 +1260,29 @@
 
         extractorSrc.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
         extractorTest.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
-
+        if (VERBOSE) {
+            Log.v(TAG, "audioStartOffsetUs: " + audioStartOffsetUs);
+            Log.v(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
+                        "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
+        }
         // Check timestamps of all audio samples.
         do {
             ++audioSampleCount;
             srcSampleTimeUs = extractorSrc.getSampleTime();
             testSampleTimeUs = extractorTest.getSampleTime();
             if(VERBOSE) {
-                Log.d(TAG, "audioSampleCount:" + audioSampleCount);
-                Log.v(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
-                            "  testTrackIndex:" + extractorTest.getSampleTrackIndex());
+                Log.v(TAG, "audioSampleCount:" + audioSampleCount);
                 Log.v(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
             }
 
             if (srcSampleTimeUs == -1 || testSampleTimeUs == -1) {
               if (VERBOSE) {
-                Log.d(TAG, "audioSampleCount:" + audioSampleCount);
-                Log.d(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
+                  Log.v(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
               }
               fail("either source or test track reached end of stream");
             }
-            // First audio sample would have zero timestamp and its start offset is implemented
-            // by assigning the first audio sample's duration as the offset. Second sample onwards
+            // First audio sample would be at zero.  Audio track's start offset is implemented
+            // by assigning the first audio sample's duration as that of the offset. Second sample
             // would play after the offset.  But video offset is achieved by edit list entry for
             // video tracks with BFrames. Need to revert the conditional check for first
             // audio sample once we implement empty edit list entry for audio.
diff --git a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
index f929e4b..4f24ec8 100644
--- a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
@@ -232,6 +232,7 @@
         int height;
         Camera camera = null;
         if (!hasCamera()) {
+            MediaUtils.skipTest("no camera");
             return;
         }
         // Try to get camera profile for QUALITY_LOW; if unavailable,
@@ -542,6 +543,7 @@
 
     public void testRecorderVideo() throws Exception {
         if (!hasCamera()) {
+            MediaUtils.skipTest("no camera");
             return;
         }
         mCamera = Camera.open(0);
@@ -566,6 +568,7 @@
 
     public void testSetOutputFile() throws Exception {
         if (!hasCamera()) {
+            MediaUtils.skipTest("no camera");
             return;
         }
         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
@@ -849,22 +852,22 @@
         return startTimeOffset + frameIndex * 1000000 / frameRate;
     }
 
-    private void testLevel(String mediaType, int width, int height, int framerate,
-            int bitrate, int profile, int requestedLevel, int... expectedLevels) throws Exception {
+    private int testLevel(String mediaType, int width, int height, int framerate, int bitrate,
+            int profile, int requestedLevel, int... expectedLevels) throws Exception {
         CodecCapabilities cap = getCapsForPreferredCodecForMediaType(mediaType);
         if (cap == null) { // not supported
-            return;
+            return 0;
         }
         MediaCodecInfo.VideoCapabilities vCap = cap.getVideoCapabilities();
         if (!vCap.areSizeAndRateSupported(width, height, framerate)
             || !vCap.getBitrateRange().contains(bitrate * 1000)) {
             Log.i(TAG, "Skip the test");
-            return;
+            return 0;
         }
 
         Surface surface = MediaCodec.createPersistentInputSurface();
         if (surface == null) {
-            return;
+            return 0;
         }
         InputSurface encSurface = new InputSurface(surface);
         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
@@ -949,9 +952,11 @@
             encSurface.release();
             encSurface = null;
         }
+        return 1;
     }
 
     public void testProfileAvcBaselineLevel1() throws Exception {
+        int testsRun = 0;
         int profile = AVCProfileBaseline;
 
         if (!hasH264()) {
@@ -960,16 +965,18 @@
         }
 
         /*              W    H   fps kbps  profile  request level   expected levels */
-        testLevel(AVC, 176, 144, 15, 64,   profile,  AVCLevel1, AVCLevel1);
+        testsRun += testLevel(AVC, 176, 144, 15, 64, profile, AVCLevel1, AVCLevel1);
         // Enable them when vendor fixes the failure
         //testLevel(AVC, 178, 144, 15, 64,   profile,  AVCLevel1, AVCLevel11);
         //testLevel(AVC, 178, 146, 15, 64,   profile,  AVCLevel1, AVCLevel11);
         //testLevel(AVC, 176, 144, 16, 64,   profile,  AVCLevel1, AVCLevel11);
         //testLevel(AVC, 176, 144, 15, 65,   profile,  AVCLevel1, AVCLevel1b);
-        testLevel(AVC, 176, 144, 15, 64,   profile,  AVCLevel1b, AVCLevel1,
-                AVCLevel1b);
+        testsRun += testLevel(AVC, 176, 144, 15, 64, profile, AVCLevel1b, AVCLevel1, AVCLevel1b);
         // testLevel(AVC, 176, 144, 15, 65,   profile,  AVCLevel2, AVCLevel1b,
         //        AVCLevel11, AVCLevel12, AVCLevel13, AVCLevel2);
+        if (testsRun == 0) {
+            MediaUtils.skipTest("VideoCapabilities or surface not found");
+        }
     }
 
 
diff --git a/tests/tests/media/src/android/media/cts/SoundPoolTest.java b/tests/tests/media/src/android/media/cts/SoundPoolTest.java
index 2c56acd..c426a31 100644
--- a/tests/tests/media/src/android/media/cts/SoundPoolTest.java
+++ b/tests/tests/media/src/android/media/cts/SoundPoolTest.java
@@ -39,9 +39,9 @@
 
     private static final int SOUNDPOOL_STREAMS = 4;
     private static final int PRIORITY = 1;
-    private static final int LOUD = 20;
-    private static final int QUIET = LOUD / 2;
-    private static final int SILENT = 0;
+    private static final float LOUD = 1.f;
+    private static final float QUIET = LOUD / 4.f;
+    private static final float SILENT = 0.f;
     private File mFile;
     private SoundPool mSoundPool;
 
diff --git a/tests/tests/media/src/android/media/cts/VideoEncoderTest.java b/tests/tests/media/src/android/media/cts/VideoEncoderTest.java
index c7018a2..81e6a4c 100644
--- a/tests/tests/media/src/android/media/cts/VideoEncoderTest.java
+++ b/tests/tests/media/src/android/media/cts/VideoEncoderTest.java
@@ -75,6 +75,10 @@
         private LinkedList<Pair<ByteBuffer, BufferInfo>> mStream;
         private MediaFormat mFormat;
         private int mInputBufferSize;
+        // Media buffers(no CSD, no EOS) enqueued.
+        private int mMediaBuffersEnqueuedCount;
+        // Media buffers decoded.
+        private int mMediaBuffersDecodedCount;
 
         public VideoStorage() {
             mStream = new LinkedList<Pair<ByteBuffer, BufferInfo>>();
@@ -93,6 +97,9 @@
             BufferInfo savedInfo = new BufferInfo();
             savedInfo.set(0, savedBuffer.position(), info.presentationTimeUs, info.flags);
             mStream.addLast(Pair.create(savedBuffer, savedInfo));
+            if (info.size > 0 && (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0) {
+                ++mMediaBuffersEnqueuedCount;
+            }
         }
 
         private void play(MediaCodec decoder, Surface surface) {
@@ -101,6 +108,9 @@
             final Iterator<Pair<ByteBuffer, BufferInfo>> it = mStream.iterator();
             decoder.setCallback(new MediaCodec.Callback() {
                 public void onOutputBufferAvailable(MediaCodec codec, int ix, BufferInfo info) {
+                    if (info.size > 0) {
+                        ++mMediaBuffersDecodedCount;
+                    }
                     codec.releaseOutputBuffer(ix, info.size > 0);
                     if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                         synchronized (condition) {
@@ -146,17 +156,25 @@
                 }
             }
             decoder.stop();
+            // All enqueued media data buffers should have got decoded.
+            if (mMediaBuffersEnqueuedCount != mMediaBuffersDecodedCount) {
+                Log.i(TAG, "mMediaBuffersEnqueuedCount:" + mMediaBuffersEnqueuedCount);
+                Log.i(TAG, "mMediaBuffersDecodedCount:" + mMediaBuffersDecodedCount);
+                fail("not all enqueued encoded media buffers were decoded");
+            }
+            mMediaBuffersDecodedCount = 0;
         }
 
-        public void playAll(Surface surface) {
+        public boolean playAll(Surface surface) {
+            boolean skipped = true;
             if (mFormat == null) {
                 Log.i(TAG, "no stream to play");
-                return;
+                return !skipped;
             }
             String mime = mFormat.getString(MediaFormat.KEY_MIME);
             MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
             for (MediaCodecInfo info : mcl.getCodecInfos()) {
-                if (info.isEncoder()) {
+                if (info.isEncoder() || info.isAlias()) {
                     continue;
                 }
                 MediaCodec codec = null;
@@ -171,7 +189,9 @@
                 }
                 play(codec, surface);
                 codec.release();
+                skipped = false;
             }
+            return !skipped;
         }
     }
 
@@ -405,9 +425,7 @@
             }
         }
 
-        public void playBack(Surface surface) {
-            mEncodedStream.playAll(surface);
-        }
+        public boolean playBack(Surface surface) { return mEncodedStream.playAll(surface); }
 
         public void setFrameAndBitRates(int frameRate, int bitRate) {
             mFrameRate = frameRate;
@@ -1147,7 +1165,7 @@
             boolean success = processor.processLoop(
                     SOURCE_URL, mMime, mName, width, height, optional);
             if (success) {
-                processor.playBack(getActivity().getSurfaceHolder().getSurface());
+                success = processor.playBack(getActivity().getSurfaceHolder().getSurface());
             }
             return success;
         }
@@ -1195,7 +1213,7 @@
         ArrayList<Encoder> result = new ArrayList<Encoder>();
 
         for (MediaCodecInfo info : mcl.getCodecInfos()) {
-            if (!info.isEncoder() || !info.isVendor() != goog) {
+            if (!info.isEncoder() || !info.isVendor() != goog || info.isAlias()) {
                 continue;
             }
             CodecCapabilities caps = null;
diff --git a/tests/tests/multiuser/Android.bp b/tests/tests/multiuser/Android.bp
index 51d6315..65c81ac 100644
--- a/tests/tests/multiuser/Android.bp
+++ b/tests/tests/multiuser/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     srcs: ["src/**/*.java"],
     static_libs: [
diff --git a/tests/tests/nativemidi/java/android/nativemidi/cts/NativeMidiEchoTest.java b/tests/tests/nativemidi/java/android/nativemidi/cts/NativeMidiEchoTest.java
index dc5e5af..32e46ac 100644
--- a/tests/tests/nativemidi/java/android/nativemidi/cts/NativeMidiEchoTest.java
+++ b/tests/tests/nativemidi/java/android/nativemidi/cts/NativeMidiEchoTest.java
@@ -76,6 +76,16 @@
         return pm.hasSystemFeature(PackageManager.FEATURE_MIDI);
     }
 
+    public static boolean hasLibAMidi() {
+        try {
+            System.loadLibrary("amidi");
+        } catch (UnsatisfiedLinkError ex) {
+            Log.e(TAG, "libamidi.so not found.");
+            return false;
+        }
+        return true;
+    }
+
     private byte[] generateRandomMessage(int len) {
         byte[] buffer = new byte[len];
         for(int index = 0; index < len; index++) {
@@ -131,7 +141,6 @@
     }
 
      protected void setUpEchoServer() throws Exception {
-        Log.i(TAG, "++ setUpEchoServer()");
         MidiDeviceInfo echoInfo = MidiEchoTestService.findEchoDevice(mContext);
 
         // Open device.
@@ -161,7 +170,6 @@
     }
 
     protected void tearDownEchoServer() throws IOException {
-        Log.i(TAG, "++ tearDownEchoServer()");
         // Query echo service directly to see if it is getting status updates.
         MidiEchoTestService echoService = MidiEchoTestService.getInstance();
 
@@ -209,11 +217,11 @@
 //
     @Before
     public void setUp() throws Exception {
-        Log.i(TAG, "++ setUp() mContext:" + mContext);
         if (!hasMidiSupport()) {
             Assert.assertTrue("FEATURE_MIDI Not Supported.", false);
             return; // Not supported so don't test it.
         }
+
         mMidiManager = (MidiManager)mContext.getSystemService(Context.MIDI_SERVICE);
         Assert.assertNotNull("Could not get the MidiManger.", mMidiManager);
 
@@ -228,14 +236,11 @@
         }
         tearDownEchoServer();
 
-        Log.i(TAG, "++ tearDown()");
         mMidiManager = null;
     }
 
     @Test
     public void test_A_MidiManager() throws Exception {
-        Log.i(TAG, "++++ test_A_MidiManager() this:" + System.identityHashCode(this));
-
         if (!hasMidiSupport()) {
             return; // Nothing to test
         }
@@ -246,14 +251,16 @@
         MidiDeviceInfo[] infos = mMidiManager.getDevices();
         Assert.assertNotNull("device list was null", infos);
         Assert.assertTrue("device list was empty", infos.length >= 1);
+    }
 
-        Log.i(TAG, "++++ test_A_MidiManager() - DONE");
+
+    @Test
+    public void test_AA_LibAMidiExists() throws Exception {
+        Assert.assertTrue("libamidi.so not found.", hasLibAMidi());
     }
 
     @Test
     public void test_B_SendData() throws Exception {
-        Log.i(TAG, "++++ test_B_SendData() this:" + System.identityHashCode(this));
-
         if (!hasMidiSupport()) {
             return; // Nothing to test
         }
@@ -270,13 +277,10 @@
         Assert.assertTrue("Didn't get 1 send", getNumBytesSent(mTestContext) == buffer.length);
         Assert.assertEquals("Didn't get right number of bytes sent",
                 buffer.length, getNumBytesSent(mTestContext));
-
-        Log.i(TAG, "++++ test_B_SendData() - DONE");
     }
 
     @Test
     public void test_C_EchoSmallMessage() throws Exception {
-        Log.i(TAG, "++++ test_C_EchoSmallMessage() this:" + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -299,13 +303,10 @@
 
         NativeMidiMessage message = getReceivedMessageAt(mTestContext, 0);
         compareMessages(buffer, timestamp, message);
-
-        Log.i(TAG, "++++ test_C_EchoSmallMessage() - DONE");
     }
 
     @Test
     public void test_D_EchoNMessages() throws Exception {
-        Log.i(TAG, "++++ test_D_EchoNMessages() this:" + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -333,13 +334,10 @@
             NativeMidiMessage message = getReceivedMessageAt(mTestContext, msgIndex);
             compareMessages(buffers[msgIndex], timestamps[msgIndex], message);
         }
-
-        Log.i(TAG, "++++ test_D_EchoNMessages() - DONE");
     }
 
     @Test
     public void test_E_FlushMessages() throws Exception {
-        Log.i(TAG, "++++ test_E_FlushMessages() this:" + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -370,13 +368,10 @@
             NativeMidiMessage message = getReceivedMessageAt(mTestContext, msgIndex);
             compareMessages(buffers[msgIndex], timestamps[msgIndex], message);
         }
-
-        Log.i(TAG, "++++ test_E_FlushMessages() - DONE");
     }
 
     @Test
     public void test_F_HugeMessage() throws Exception {
-        Log.i(TAG, "++++ test_F_HugeMessage() this:" + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -391,8 +386,6 @@
         buffer = generateRandomMessage(kindaHugeMessageLen);
         result = writeMidi(mTestContext, buffer, 0, buffer.length);
         Assert.assertEquals("Kinda big write failed.", kindaHugeMessageLen, result);
-
-        Log.i(TAG, "++++ test_F_HugeMessage() - DONE");
     }
 
     /**
@@ -401,7 +394,6 @@
      */
     @Test
     public void test_G_NativeEchoTime() throws Exception {
-        Log.i(TAG, "++++ test_G_NativeEchoTime() this:" + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -434,13 +426,10 @@
                     "timestamp:" + message.timestamp + " received:" + message.timeReceived,
                     (elapsedNanos < maxLatencyNanos));
         }
-
-        Log.i(TAG, "++++ test_G_NativeEchoTime() - DONE");
     }
 
     @Test
     public void test_H_EchoNMessages_PureNative() throws Exception {
-        Log.i(TAG, "++++ test_H_EchoNMessages_PureNative() this:" + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -461,8 +450,6 @@
 
         int result = matchNativeMessages(mTestContext);
         Assert.assertEquals("Native Compare Test Failed", result, 0);
-
-        Log.i(TAG, "++++ test_H_EchoNMessages_PureNative() - DONE");
     }
 
     /**
@@ -471,8 +458,6 @@
      */
     @Test
     public void test_I_NativeEchoTime_PureNative() throws Exception {
-        Log.i(TAG, "++++ test_I_NativeEchoTime_PureNative() this:"
-                + System.identityHashCode(this));
         if (!hasMidiSupport()) {
             return; // nothing to test
         }
@@ -495,8 +480,6 @@
 
         int result = checkNativeLatency(mTestContext, maxLatencyNanos);
         Assert.assertEquals("failed pure native latency test.", 0, result);
-
-        Log.i(TAG, "++++ test_I_NativeEchoTime_PureNative() - DONE");
     }
 
     // Native Routines
diff --git a/tests/tests/net/src/android/net/rtp/cts/AudioGroupTest.java b/tests/tests/net/src/android/net/rtp/cts/AudioGroupTest.java
index 1bd7fad..fee8621 100644
--- a/tests/tests/net/src/android/net/rtp/cts/AudioGroupTest.java
+++ b/tests/tests/net/src/android/net/rtp/cts/AudioGroupTest.java
@@ -62,7 +62,7 @@
         mSocketB.connect(mStreamB.getLocalAddress(), mStreamB.getLocalPort());
         mStreamB.associate(mSocketB.getLocalAddress(), mSocketB.getLocalPort());
 
-        mGroup = new AudioGroup();
+        mGroup = new AudioGroup(mContext);
     }
 
     @Override
diff --git a/tests/tests/packageinstaller/atomicinstall/Android.bp b/tests/tests/packageinstaller/atomicinstall/Android.bp
index c772572..8b24ee5 100644
--- a/tests/tests/packageinstaller/atomicinstall/Android.bp
+++ b/tests/tests/packageinstaller/atomicinstall/Android.bp
@@ -30,6 +30,7 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
 }
 
diff --git a/tests/tests/packageinstaller/atomicinstall/AndroidTest.xml b/tests/tests/packageinstaller/atomicinstall/AndroidTest.xml
index e248a62..88a142d 100644
--- a/tests/tests/packageinstaller/atomicinstall/AndroidTest.xml
+++ b/tests/tests/packageinstaller/atomicinstall/AndroidTest.xml
@@ -24,8 +24,10 @@
         <option name="test-file-name" value="CtsAtomicInstallTestCases.apk" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="teardown-command" value="pm uninstall com.android.tests.atomicinstall.testapp.A" />
-        <option name="teardown-command" value="pm uninstall com.android.tests.atomicinstall.testapp.B" />
+        <option name="run-command" value="pm uninstall com.android.cts.install.lib.testapp.A" />
+        <option name="run-command" value="pm uninstall com.android.cts.install.lib.testapp.B" />
+        <option name="teardown-command" value="pm uninstall com.android.cts.install.lib.testapp.A" />
+        <option name="teardown-command" value="pm uninstall com.android.cts.install.lib.testapp.B" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
diff --git a/tests/tests/permission/Android.mk b/tests/tests/permission/Android.mk
index aeaee7a..8d73210 100644
--- a/tests/tests/permission/Android.mk
+++ b/tests/tests/permission/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Include both the 32 and 64 bit versions
 LOCAL_MULTILIB := both
diff --git a/tests/tests/permission/AndroidTest.xml b/tests/tests/permission/AndroidTest.xml
index 8fcdc9c..a4ee42b 100644
--- a/tests/tests/permission/AndroidTest.xml
+++ b/tests/tests/permission/AndroidTest.xml
@@ -42,6 +42,8 @@
         <option name="push" value="CtsAppThatRequestsLocationPermission29v4.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsLocationPermission29v4.apk" />
         <option name="push" value="CtsAppThatRequestsLocationPermission28.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsLocationPermission28.apk" />
         <option name="push" value="CtsAppThatRequestsLocationPermission22.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsLocationPermission22.apk" />
+        <option name="push" value="CtsAppThatRequestsStoragePermission29.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsStoragePermission29.apk" />
+        <option name="push" value="CtsAppThatRequestsStoragePermission28.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsStoragePermission28.apk" />
         <option name="push" value="CtsAppThatRequestsLocationAndBackgroundPermission29.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsLocationAndBackgroundPermission29.apk" />
         <option name="push" value="CtsAppThatAccessesLocationOnCommand.apk->/data/local/tmp/cts/permissions/CtsAppThatAccessesLocationOnCommand.apk" />
         <option name="push" value="AppThatDoesNotHaveBgLocationAccess.apk->/data/local/tmp/cts/permissions/AppThatDoesNotHaveBgLocationAccess.apk" />
@@ -51,12 +53,22 @@
         <option name="push" value="CtsAppWithSharedUidThatRequestsLocationPermission29.apk->/data/local/tmp/cts/permissions/CtsAppWithSharedUidThatRequestsLocationPermission29.apk" />
         <option name="push" value="CtsAppThatRequestsCalendarContactsBodySensorCustomPermission.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsCalendarContactsBodySensorCustomPermission.apk" />
         <option name="push" value="CtsAppThatRunsRationaleTests.apk->/data/local/tmp/cts/permissions/CtsAppThatRunsRationaleTests.apk" />
+        <option name="push" value="CtsAdversarialPermissionUserApp.apk->/data/local/tmp/cts/permissions/CtsAdversarialPermissionUserApp.apk" />
+        <option name="push" value="CtsAdversarialPermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsAdversarialPermissionDefinerApp.apk" />
+        <option name="push" value="CtsVictimPermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsVictimPermissionDefinerApp.apk" />
+        <option name="push" value="CtsRuntimePermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsRuntimePermissionDefinerApp.apk" />
+        <option name="push" value="CtsRuntimePermissionUserApp.apk->/data/local/tmp/cts/permissions/CtsRuntimePermissionUserApp.apk" />
     </target_preparer>
 
     <!-- Remove additional apps if installed -->
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
         <option name="teardown-command" value="pm uninstall android.permission.cts.appthatrequestpermission" />
         <option name="teardown-command" value="pm uninstall android.permission.cts.appthatrequestnopermission" />
+        <option name="teardown-command" value="pm uninstall android.permission.cts.revokepermissionwhenremoved.AdversarialPermissionDefinerApp" />
+        <option name="teardown-command" value="pm uninstall android.permission.cts.revokepermissionwhenremoved.VictimPermissionDefinerApp" />
+        <option name="teardown-command" value="pm uninstall android.permission.cts.revokepermissionwhenremoved.userapp" />
+        <option name="teardown-command" value="pm uninstall android.permission.cts.revokepermissionwhenremoved.runtimepermissiondefinerapp" />
+        <option name="teardown-command" value="pm uninstall android.permission.cts.revokepermissionwhenremoved.runtimepermissionuserapp" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
diff --git a/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.mk b/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.mk
index 08b0c46..9a3f8e9 100644
--- a/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.mk
+++ b/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.mk b/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.mk
index fcc4b06..20d6859 100644
--- a/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.mk
+++ b/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := AppThatDoesNotHaveBgLocationAccess
 
diff --git a/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.mk b/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.mk
index cbbb3ec..37e0330 100644
--- a/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.mk
+++ b/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsContactsAndCallLogPermission16
 
diff --git a/tests/tests/permission/AppThatRequestContactsPermission15/Android.mk b/tests/tests/permission/AppThatRequestContactsPermission15/Android.mk
index b77ab88..bc95ffa 100644
--- a/tests/tests/permission/AppThatRequestContactsPermission15/Android.mk
+++ b/tests/tests/permission/AppThatRequestContactsPermission15/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsContactsPermission15
 
diff --git a/tests/tests/permission/AppThatRequestContactsPermission16/Android.mk b/tests/tests/permission/AppThatRequestContactsPermission16/Android.mk
index de95f0f..bd0ead0 100644
--- a/tests/tests/permission/AppThatRequestContactsPermission16/Android.mk
+++ b/tests/tests/permission/AppThatRequestContactsPermission16/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsContactsPermission16
 
diff --git a/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.mk b/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.mk
index 7929f54..b370ead 100644
--- a/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.mk
+++ b/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsLocationAndBackgroundPermission29
 
diff --git a/tests/tests/permission/AppThatRequestLocationPermission22/Android.mk b/tests/tests/permission/AppThatRequestLocationPermission22/Android.mk
index 4e88478..0158fa7 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission22/Android.mk
+++ b/tests/tests/permission/AppThatRequestLocationPermission22/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsLocationPermission22
 
diff --git a/tests/tests/permission/AppThatRequestLocationPermission28/Android.mk b/tests/tests/permission/AppThatRequestLocationPermission28/Android.mk
index d39f128..acc7fa2 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission28/Android.mk
+++ b/tests/tests/permission/AppThatRequestLocationPermission28/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsLocationPermission28
 
diff --git a/tests/tests/permission/AppThatRequestLocationPermission29/Android.mk b/tests/tests/permission/AppThatRequestLocationPermission29/Android.mk
index 56f36fb..d731d8b 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission29/Android.mk
+++ b/tests/tests/permission/AppThatRequestLocationPermission29/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsLocationPermission29
 
diff --git a/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.mk b/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.mk
index 95168c9..501055f 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.mk
+++ b/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppThatRequestsLocationPermission29v4
 
diff --git a/tests/tests/permission/AppThatRequestPermissionAandB/Android.mk b/tests/tests/permission/AppThatRequestPermissionAandB/Android.mk
index f34edab..04bd15a 100644
--- a/tests/tests/permission/AppThatRequestPermissionAandB/Android.mk
+++ b/tests/tests/permission/AppThatRequestPermissionAandB/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/permission/AppThatRequestPermissionAandC/Android.mk b/tests/tests/permission/AppThatRequestPermissionAandC/Android.mk
index e459558..ee3218d 100644
--- a/tests/tests/permission/AppThatRequestPermissionAandC/Android.mk
+++ b/tests/tests/permission/AppThatRequestPermissionAandC/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/AppThatRequestStoragePermission28/Android.mk
similarity index 77%
copy from tests/backup/app/permission22/Android.mk
copy to tests/tests/permission/AppThatRequestStoragePermission28/Android.mk
index 8790e19..365d385 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/AppThatRequestStoragePermission28/Android.mk
@@ -1,3 +1,4 @@
+#
 # Copyright (C) 2019 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -11,21 +12,19 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+LOCAL_PACKAGE_NAME := CtsAppThatRequestsStoragePermission28
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/permission/AppThatRequestStoragePermission28/AndroidManifest.xml b/tests/tests/permission/AppThatRequestStoragePermission28/AndroidManifest.xml
new file mode 100644
index 0000000..a847f39
--- /dev/null
+++ b/tests/tests/permission/AppThatRequestStoragePermission28/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission.cts.appthatrequestpermission"
+    android:versionCode="2">
+
+    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
+
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+
+    <application />
+</manifest>
+
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/AppThatRequestStoragePermission29/Android.mk
similarity index 77%
copy from tests/backup/app/permission22/Android.mk
copy to tests/tests/permission/AppThatRequestStoragePermission29/Android.mk
index 8790e19..740c900 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/AppThatRequestStoragePermission29/Android.mk
@@ -1,3 +1,4 @@
+#
 # Copyright (C) 2019 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -11,21 +12,19 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+LOCAL_PACKAGE_NAME := CtsAppThatRequestsStoragePermission29
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/permission/AppThatRequestStoragePermission29/AndroidManifest.xml b/tests/tests/permission/AppThatRequestStoragePermission29/AndroidManifest.xml
new file mode 100644
index 0000000..c783085
--- /dev/null
+++ b/tests/tests/permission/AppThatRequestStoragePermission29/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission.cts.appthatrequestpermission"
+    android:versionCode="1">
+
+    <uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
+
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+
+    <application />
+</manifest>
+
diff --git a/tests/tests/permission/AppThatRunsRationaleTests/Android.bp b/tests/tests/permission/AppThatRunsRationaleTests/Android.bp
index 6bd320b..3447de4 100644
--- a/tests/tests/permission/AppThatRunsRationaleTests/Android.bp
+++ b/tests/tests/permission/AppThatRunsRationaleTests/Android.bp
@@ -25,7 +25,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp
index 15da653..425c06b 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp
+++ b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp
@@ -25,6 +25,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp
index a369df7..54bc02b 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp
+++ b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp
@@ -25,6 +25,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 }
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.mk b/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.mk
index 98395d0..ea7a665 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.mk
+++ b/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.mk
@@ -20,7 +20,7 @@
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_PACKAGE_NAME := CtsAppWithSharedUidThatRequestsNoPermissions
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.mk b/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.mk
index 22ddf98..d5e7759 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.mk
+++ b/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.mk
@@ -20,7 +20,7 @@
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_PACKAGE_NAME := CtsAppWithSharedUidThatRequestsPermissions
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/permission/src/android/permission/cts/PermissionUpdateListenerTest.java b/tests/tests/permission/src/android/permission/cts/PermissionUpdateListenerTest.java
index a03b61d..afcd9e9 100644
--- a/tests/tests/permission/src/android/permission/cts/PermissionUpdateListenerTest.java
+++ b/tests/tests/permission/src/android/permission/cts/PermissionUpdateListenerTest.java
@@ -92,6 +92,7 @@
                 new LatchWithPermissionsChangedListener();
 
         runWithShellPermissionIdentity(() -> {
+            sPm.revokeRuntimePermission(PACKAGE_NAME, PERMISSION_NAME, sContext.getUser());
             sPm.addOnPermissionsChangeListener(listenerCalled);
             sPm.grantRuntimePermission(PACKAGE_NAME, PERMISSION_NAME, sContext.getUser());
         });
@@ -104,6 +105,7 @@
                 new LatchWithPermissionsChangedListener();
 
         runWithShellPermissionIdentity(() -> {
+            sPm.grantRuntimePermission(PACKAGE_NAME, PERMISSION_NAME, sContext.getUser());
             sPm.addOnPermissionsChangeListener(listenerCalled);
             sPm.revokeRuntimePermission(PACKAGE_NAME, PERMISSION_NAME, sContext.getUser());
         });
diff --git a/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java b/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java
new file mode 100644
index 0000000..ff0204b
--- /dev/null
+++ b/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2019 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.permission.cts;
+
+import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
+import static android.content.pm.PackageManager.GET_PERMISSIONS;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.app.Instrumentation;
+import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.SecurityTest;
+
+import androidx.test.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.SystemUtil;
+
+import org.junit.Before;
+import org.junit.Test;
+
+@AppModeFull(reason = "Instant apps cannot read state of other packages.")
+public class RemovePermissionTest {
+    private static final String APP_PKG_NAME = "android.permission.cts.revokepermissionwhenremoved";
+    private static final String USER_PKG_NAME =
+            "android.permission.cts.revokepermissionwhenremoved.userapp";
+    private static final String TEST_PERMISSION =
+            "android.permission.cts.revokepermissionwhenremoved.TestPermission";
+    private static final String RUNTIME_PERMISSION_USER_PKG_NAME =
+            "android.permission.cts.revokepermissionwhenremoved.runtimepermissionuserapp";
+    private static final String RUNTIME_PERMISSION_DEFINER_PKG_NAME =
+            "android.permission.cts.revokepermissionwhenremoved.runtimepermissiondefinerapp";
+    private static final String TEST_RUNTIME_PERMISSION =
+            "android.permission.cts.revokepermissionwhenremoved.TestRuntimePermission";
+
+    private Context mContext;
+    private Instrumentation mInstrumentation;
+    private Object mMySync = new Object();
+
+    @Before
+    public void setContextAndInstrumentation() {
+        mContext = InstrumentationRegistry.getTargetContext();
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+    }
+
+    @Before
+    public void wakeUpScreen() {
+        SystemUtil.runShellCommand("input keyevent KEYCODE_WAKEUP");
+    }
+
+    private boolean permissionGranted(String pkgName, String permName)
+            throws PackageManager.NameNotFoundException {
+        PackageInfo appInfo = mContext.getPackageManager().getPackageInfo(pkgName,
+                GET_PERMISSIONS);
+
+        for (int i = 0; i < appInfo.requestedPermissions.length; i++) {
+            if (appInfo.requestedPermissions[i].equals(permName)
+                    && ((appInfo.requestedPermissionsFlags[i] & REQUESTED_PERMISSION_GRANTED)
+                    != 0)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private void installApp(String apk) throws InterruptedException {
+        String installResult = SystemUtil.runShellCommand(
+                "pm install -r -d data/local/tmp/cts/permissions/" + apk + ".apk");
+        synchronized (mMySync) {
+            mMySync.wait(10000);
+        }
+        assertEquals("Success", installResult.trim());
+    }
+
+    private void uninstallApp(String pkg) throws InterruptedException {
+        String uninstallResult = SystemUtil.runShellCommand(
+                "pm uninstall " + pkg);
+        synchronized (mMySync) {
+            mMySync.wait(10000);
+        }
+        assertEquals("Success", uninstallResult.trim());
+    }
+
+    private void grantPermission(String pkg, String permission) {
+        mInstrumentation.getUiAutomation().grantRuntimePermission(
+                pkg, permission);
+    }
+
+    @SecurityTest
+    @Test
+    public void permissionShouldBeRevokedIfRemoved() throws Throwable {
+        installApp("CtsAdversarialPermissionDefinerApp");
+        installApp("CtsAdversarialPermissionUserApp");
+
+        grantPermission(USER_PKG_NAME, TEST_PERMISSION);
+        assertTrue(permissionGranted(USER_PKG_NAME, TEST_PERMISSION));
+
+        // Uninstall app which defines a permission with the same name as in victim app.
+        // Install the victim app.
+        uninstallApp(APP_PKG_NAME + ".AdversarialPermissionDefinerApp");
+        installApp("CtsVictimPermissionDefinerApp");
+        assertFalse(permissionGranted(USER_PKG_NAME, TEST_PERMISSION));
+        uninstallApp(APP_PKG_NAME + ".userapp");
+        uninstallApp(APP_PKG_NAME + ".VictimPermissionDefinerApp");
+    }
+
+    @Test
+    public void permissionShouldRemainGrantedAfterAppUpdate() throws Throwable {
+        installApp("CtsRuntimePermissionDefinerApp");
+        installApp("CtsRuntimePermissionUserApp");
+
+        grantPermission(RUNTIME_PERMISSION_USER_PKG_NAME, TEST_RUNTIME_PERMISSION);
+        assertTrue(permissionGranted(RUNTIME_PERMISSION_USER_PKG_NAME, TEST_RUNTIME_PERMISSION));
+
+        // Install app which defines a permission. This is similar to update the app
+        // operation
+        installApp("CtsRuntimePermissionDefinerApp");
+        assertTrue(permissionGranted(RUNTIME_PERMISSION_USER_PKG_NAME, TEST_RUNTIME_PERMISSION));
+        uninstallApp(RUNTIME_PERMISSION_USER_PKG_NAME);
+        uninstallApp(RUNTIME_PERMISSION_DEFINER_PKG_NAME);
+    }
+}
diff --git a/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java b/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java
index 7731a11..da075c0 100644
--- a/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java
@@ -18,8 +18,10 @@
 
 import static android.Manifest.permission.ACCESS_BACKGROUND_LOCATION;
 import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_MEDIA_LOCATION;
 import static android.Manifest.permission.READ_CALL_LOG;
 import static android.Manifest.permission.READ_CONTACTS;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
 import static android.app.AppOpsManager.MODE_FOREGROUND;
 import static android.app.AppOpsManager.MODE_IGNORED;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
@@ -71,6 +73,10 @@
             TMP_DIR + "CtsAppThatRequestsContactsPermission15.apk";
     private static final String APK_CONTACTS_CALLLOG_16 =
             TMP_DIR + "CtsAppThatRequestsContactsAndCallLogPermission16.apk";
+    private static final String APK_STORAGE_29 =
+            TMP_DIR + "CtsAppThatRequestsStoragePermission29.apk";
+    private static final String APK_STORAGE_28 =
+            TMP_DIR + "CtsAppThatRequestsStoragePermission28.apk";
     private static final String APK_LOCATION_29 =
             TMP_DIR + "CtsAppThatRequestsLocationPermission29.apk";
     private static final String APK_LOCATION_28 =
@@ -260,6 +266,22 @@
      * If a permission was granted before the split happens, the new permission should inherit the
      * granted state.
      *
+     * This is a duplicate of {@link #inheritGrantedPermissionState} but for the storage permission
+     */
+    @Test
+    public void inheritGrantedPermissionStateStorage() throws Exception {
+        install(APK_STORAGE_29);
+        grantPermission(APP_PKG, READ_EXTERNAL_STORAGE);
+
+        install(APK_STORAGE_28);
+
+        assertPermissionGranted(ACCESS_MEDIA_LOCATION);
+    }
+
+    /**
+     * If a permission was granted before the split happens, the new permission should inherit the
+     * granted state.
+     *
      * <p>App using a shared uid
      */
     @Test
diff --git a/tests/tests/permission/telephony/Android.mk b/tests/tests/permission/telephony/Android.mk
index f458633..80de31d 100644
--- a/tests/tests/permission/telephony/Android.mk
+++ b/tests/tests/permission/telephony/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Include both the 32 and 64 bit versions
 LOCAL_MULTILIB := both
diff --git a/tests/backup/app/Android.mk b/tests/tests/permission/testapps/Android.mk
similarity index 91%
rename from tests/backup/app/Android.mk
rename to tests/tests/permission/testapps/Android.mk
index cddf11e..1d314d2 100644
--- a/tests/backup/app/Android.mk
+++ b/tests/tests/permission/testapps/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2017 The Android Open Source Project
+# Copyright (C) 2019 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.
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.mk
similarity index 81%
copy from tests/backup/app/permission22/Android.mk
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.mk
index 8790e19..e81acdc 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.mk
@@ -11,21 +11,20 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
+LOCAL_PACKAGE_NAME := CtsAdversarialPermissionDefinerApp
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 66%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/AndroidManifest.xml
index a48cb1d..d28fba8
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/AndroidManifest.xml
@@ -16,10 +16,13 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
+    package="android.permission.cts.revokepermissionwhenremoved.AdversarialPermissionDefinerApp">
 
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
+    <permission android:name="android.permission.cts.revokepermissionwhenremoved.TestPermission"
+        android:protectionLevel="dangerous"
+        android:label="TestPermission"
+        android:description="@string/test_permission" />
 
+    <application>
+    </application>
 </manifest>
-
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/res/values/strings.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/res/values/strings.xml
new file mode 100644
index 0000000..bfb3e1e
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="test_permission">Test Permission</string>
+</resources>
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.mk
similarity index 81%
copy from tests/backup/app/permission22/Android.mk
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.mk
index 8790e19..8856eb8 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.mk
@@ -11,21 +11,19 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
+LOCAL_PACKAGE_NAME := CtsAdversarialPermissionUserApp
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 77%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/AndroidManifest.xml
index a48cb1d..f514d54
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/AndroidManifest.xml
@@ -16,10 +16,10 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
+    package="android.permission.cts.revokepermissionwhenremoved.userapp">
 
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
+    <uses-permission android:name="android.permission.cts.revokepermissionwhenremoved.TestPermission" />
 
+    <application>
+    </application>
 </manifest>
-
diff --git a/tests/backup/app/Android.mk b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/Android.mk
similarity index 91%
copy from tests/backup/app/Android.mk
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/Android.mk
index cddf11e..1d314d2 100644
--- a/tests/backup/app/Android.mk
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2017 The Android Open Source Project
+# Copyright (C) 2019 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.
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.mk
similarity index 81%
copy from tests/backup/app/permission22/Android.mk
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.mk
index 8790e19..8e22243 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.mk
@@ -11,21 +11,20 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
+LOCAL_PACKAGE_NAME := CtsRuntimePermissionDefinerApp
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 66%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/AndroidManifest.xml
index a48cb1d..d3cf6d0
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/AndroidManifest.xml
@@ -16,10 +16,13 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
+    package="android.permission.cts.revokepermissionwhenremoved.runtimepermissiondefinerapp">
 
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
+    <permission android:name="android.permission.cts.revokepermissionwhenremoved.TestRuntimePermission"
+        android:protectionLevel="dangerous"
+        android:label="TestPermission"
+        android:description="@string/test_permission" />
 
+    <application>
+    </application>
 </manifest>
-
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/res/values/strings.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/res/values/strings.xml
new file mode 100644
index 0000000..bfb3e1e
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="test_permission">Test Permission</string>
+</resources>
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.mk
similarity index 81%
rename from tests/backup/app/permission22/Android.mk
rename to tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.mk
index 8790e19..112a132 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.mk
@@ -11,21 +11,19 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
+LOCAL_PACKAGE_NAME := CtsRuntimePermissionUserApp
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 75%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/AndroidManifest.xml
index a48cb1d..d977e46
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/AndroidManifest.xml
@@ -16,10 +16,10 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
+    package="android.permission.cts.revokepermissionwhenremoved.runtimepermissionuserapp">
 
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
+    <uses-permission android:name="android.permission.cts.revokepermissionwhenremoved.TestRuntimePermission" />
 
+    <application>
+    </application>
 </manifest>
-
diff --git a/tests/backup/app/permission22/Android.mk b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.mk
similarity index 81%
copy from tests/backup/app/permission22/Android.mk
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.mk
index 8790e19..e7f4072 100644
--- a/tests/backup/app/permission22/Android.mk
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.mk
@@ -11,21 +11,21 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+#
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-
-LOCAL_PACKAGE_NAME := CtsPermissionBackupApp22
-LOCAL_SDK_VERSION := current
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+LOCAL_PACKAGE_NAME := CtsVictimPermissionDefinerApp
+
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 66%
copy from hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
copy to tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/AndroidManifest.xml
index a48cb1d..3fb0abd
--- a/hostsidetests/devicepolicy/app/NoLaunchableActivityApp/no_component_AndroidManifest.xml
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/AndroidManifest.xml
@@ -14,12 +14,12 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  -->
-
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.nocomponentapp">
-
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application />
-
+    package="android.permission.cts.revokepermissionwhenremoved.VictimPermissionDefinerApp">
+    <permission android:name="android.permission.cts.revokepermissionwhenremoved.TestPermission"
+        android:protectionLevel="signature"
+        android:label="Test Permission"
+        android:description="@string/test_permission" />
+    <application>
+    </application>
 </manifest>
-
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/res/values/strings.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/res/values/strings.xml
new file mode 100644
index 0000000..bfb3e1e
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="test_permission">Test Permission</string>
+</resources>
diff --git a/tests/tests/permission2/Android.bp b/tests/tests/permission2/Android.bp
index a816a55..840359f 100644
--- a/tests/tests/permission2/Android.bp
+++ b/tests/tests/permission2/Android.bp
@@ -22,7 +22,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     libs: ["android.test.base.stubs"],
     static_libs: [
@@ -34,7 +33,10 @@
         "truth-prebuilt",
         "permission-test-util-lib"
     ],
-    srcs: ["src/**/*.java"],
+    srcs: [
+        "src/**/*.java",
+        "src/**/*.kt"
+    ],
     sdk_version: "test_current",
     data: [
         ":CtsLocationPermissionsUserSdk22",
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index d345d4f..8d23365 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -1941,6 +1941,12 @@
     <permission android:name="android.permission.READ_PRECISE_PHONE_STATE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi Allows read access to emergency number information for ongoing calls or SMS
+         sessions.
+         @hide -->
+    <permission android:name="android.permission.READ_ACTIVE_EMERGENCY_SESSION"
+        android:protectionLevel="signature" />
+
     <!-- @SystemApi Allows read access to privileged phone state.
          @hide Used internally. -->
     <permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
@@ -2483,6 +2489,19 @@
         android:label="@string/permlab_readSyncStats"
         android:protectionLevel="normal" />
 
+    <!-- ==================================================== -->
+    <!-- Permissions related to accessibility                 -->
+    <!-- ==================================================== -->
+    <eat-comment />
+
+    <!-- Allows applications to define the accessibility shortcut target.
+         <p>Protection level: normal
+    -->
+    <permission android:name="android.permission.ACCESSIBILITY_SHORTCUT_TARGET"
+                android:description="@string/permdesc_accessibilityShortcutTarget"
+                android:label="@string/permlab_accessibilityShortcutTarget"
+                android:protectionLevel="normal" />
+
     <!-- ============================================ -->
     <!-- Permissions for low-level system interaction -->
     <!-- ============================================ -->
diff --git a/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt b/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt
new file mode 100644
index 0000000..e84e3af
--- /dev/null
+++ b/tests/tests/permission2/src/android/permission2/cts/RuntimePermissionProperties.kt
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2019 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.permission2.cts
+
+import android.Manifest.permission.ACCEPT_HANDOVER
+import android.Manifest.permission.ACCESS_COARSE_LOCATION
+import android.Manifest.permission.ACCESS_FINE_LOCATION
+import android.Manifest.permission.ACTIVITY_RECOGNITION
+import android.Manifest.permission.ADD_VOICEMAIL
+import android.Manifest.permission.ANSWER_PHONE_CALLS
+import android.Manifest.permission.BODY_SENSORS
+import android.Manifest.permission.CALL_PHONE
+import android.Manifest.permission.CAMERA
+import android.Manifest.permission.GET_ACCOUNTS
+import android.Manifest.permission.PROCESS_OUTGOING_CALLS
+import android.Manifest.permission.READ_CALENDAR
+import android.Manifest.permission.READ_CALL_LOG
+import android.Manifest.permission.READ_CELL_BROADCASTS
+import android.Manifest.permission.READ_CONTACTS
+import android.Manifest.permission.READ_EXTERNAL_STORAGE
+import android.Manifest.permission.READ_PHONE_NUMBERS
+import android.Manifest.permission.READ_PHONE_STATE
+import android.Manifest.permission.READ_SMS
+import android.Manifest.permission.RECEIVE_MMS
+import android.Manifest.permission.RECEIVE_SMS
+import android.Manifest.permission.RECEIVE_WAP_PUSH
+import android.Manifest.permission.RECORD_AUDIO
+import android.Manifest.permission.SEND_SMS
+import android.Manifest.permission.USE_SIP
+import android.Manifest.permission.WRITE_CALENDAR
+import android.Manifest.permission.WRITE_CALL_LOG
+import android.Manifest.permission.WRITE_CONTACTS
+import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
+import android.Manifest.permission_group.UNDEFINED
+import android.app.AppOpsManager.permissionToOp
+import android.content.pm.PackageManager.GET_PERMISSIONS
+import android.content.pm.PermissionInfo.PROTECTION_DANGEROUS
+import android.content.pm.PermissionInfo.PROTECTION_FLAG_APPOP
+import android.os.Build
+import android.permission.PermissionManager
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.runner.AndroidJUnit4
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class RuntimePermissionProperties {
+    private val context = InstrumentationRegistry.getInstrumentation().getTargetContext()
+    private val pm = context.packageManager
+
+    private val platformPkg = pm.getPackageInfo("android", GET_PERMISSIONS)
+    private val platformRuntimePerms = platformPkg.permissions
+            .filter { it.protection == PROTECTION_DANGEROUS }
+    private val platformBgPermNames = platformRuntimePerms.mapNotNull { it.backgroundPermission }
+
+    @Test
+    fun allRuntimeForegroundPermissionNeedAnAppOp() {
+        val platformFgPerms =
+            platformRuntimePerms.filter { !platformBgPermNames.contains(it.name) }
+
+        for (perm in platformFgPerms) {
+            assertThat(permissionToOp(perm.name)).named("AppOp for ${perm.name}").isNotNull()
+        }
+    }
+
+    @Test
+    fun groupOfRuntimePermissionsShouldBeUnknown() {
+        for (perm in platformRuntimePerms) {
+            assertThat(perm.group).named("Group of ${perm.name}").isEqualTo(UNDEFINED)
+        }
+    }
+
+    @Test
+    fun allAppOpPermissionNeedAnAppOp() {
+        val platformAppOpPerms = platformPkg.permissions
+                .filter { (it.protectionFlags and PROTECTION_FLAG_APPOP) != 0 }
+
+        for (perm in platformAppOpPerms) {
+            assertThat(permissionToOp(perm.name)).named("AppOp for ${perm.name}").isNotNull()
+        }
+    }
+
+    /**
+     * The permission of a background permission is the one of its foreground permission
+     */
+    @Test
+    fun allRuntimeBackgroundPermissionCantHaveAnAppOp() {
+        val platformBgPerms =
+            platformRuntimePerms.filter { platformBgPermNames.contains(it.name) }
+
+        for (perm in platformBgPerms) {
+            assertThat(permissionToOp(perm.name)).named("AppOp for ${perm.name}").isNull()
+        }
+    }
+
+    /**
+     * Commonly a new runtime permission is created by splitting an old one into twice
+     */
+    @Test
+    fun runtimePermissionsShouldHaveBeenSplitFromPreviousPermission() {
+        // Runtime permissions in Android P
+        val expectedPerms = mutableSetOf(READ_CONTACTS, WRITE_CONTACTS, GET_ACCOUNTS, READ_CALENDAR,
+            WRITE_CALENDAR, SEND_SMS, RECEIVE_SMS, READ_SMS, RECEIVE_MMS, RECEIVE_WAP_PUSH,
+            READ_CELL_BROADCASTS, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE,
+            ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION, READ_CALL_LOG, WRITE_CALL_LOG,
+            PROCESS_OUTGOING_CALLS, READ_PHONE_STATE, READ_PHONE_NUMBERS, CALL_PHONE,
+            ADD_VOICEMAIL, USE_SIP, ANSWER_PHONE_CALLS, ACCEPT_HANDOVER, RECORD_AUDIO, CAMERA,
+            BODY_SENSORS)
+
+        // Add permission split since P
+        for (sdkVersion in Build.VERSION_CODES.P + 1..Build.VERSION_CODES.CUR_DEVELOPMENT + 1) {
+            for (splitPerm in
+                context.getSystemService(PermissionManager::class.java)!!.splitPermissions) {
+                if (splitPerm.targetSdk == sdkVersion &&
+                    expectedPerms.contains(splitPerm.splitPermission)) {
+                    expectedPerms.addAll(splitPerm.newPermissions)
+                }
+            }
+        }
+
+        // Add runtime permission added in Q which were _not_ split from a previously existing
+        // runtime permission
+        expectedPerms.add(ACTIVITY_RECOGNITION)
+
+        assertThat(expectedPerms).containsExactlyElementsIn(platformRuntimePerms.map { it.name })
+    }
+}
diff --git a/tests/tests/preference/Android.bp b/tests/tests/preference/Android.bp
index 480c38d..ec71dee 100644
--- a/tests/tests/preference/Android.bp
+++ b/tests/tests/preference/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     static_libs: [
diff --git a/tests/tests/print/Android.bp b/tests/tests/print/Android.bp
index 1e610b3..43fd39d 100644
--- a/tests/tests/print/Android.bp
+++ b/tests/tests/print/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     srcs: ["src/**/*.java"],
     static_libs: ["print-test-util-lib"],
diff --git a/tests/tests/provider/Android.bp b/tests/tests/provider/Android.bp
index 489025e..0828f57 100644
--- a/tests/tests/provider/Android.bp
+++ b/tests/tests/provider/Android.bp
@@ -35,6 +35,7 @@
 
     srcs: ["src/**/*.java"],
 
-    sdk_version: "test_current",
+    // uncomment when b/140885436 is fixed
+    // sdk_version: "test_current",
     min_sdk_version: "21",
 }
diff --git a/tests/tests/provider/src/libcore/util/HexEncoding.java b/tests/tests/provider/src/libcore/util/HexEncoding.java
deleted file mode 100644
index 992acbd..0000000
--- a/tests/tests/provider/src/libcore/util/HexEncoding.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package libcore.util;
-
-/**
- * Hexadecimal encoding where each byte is represented by two hexadecimal digits.
- * @hide
- */
-public class HexEncoding {
-
-    /** Hidden constructor to prevent instantiation. */
-    private HexEncoding() {}
-
-    private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
-
-    /**
-     * Encodes the provided data as a sequence of hexadecimal characters.
-     */
-    public static char[] encode(byte[] data) {
-        return encode(data, 0, data.length);
-    }
-
-    /**
-     * Encodes the provided data as a sequence of hexadecimal characters.
-     */
-    public static char[] encode(byte[] data, int offset, int len) {
-        char[] result = new char[len * 2];
-        for (int i = 0; i < len; i++) {
-            byte b = data[offset + i];
-            int resultIndex = 2 * i;
-            result[resultIndex] = (HEX_DIGITS[(b >>> 4) & 0x0f]);
-            result[resultIndex + 1] = (HEX_DIGITS[b & 0x0f]);
-        }
-
-        return result;
-    }
-
-    /**
-     * Encodes the provided data as a sequence of hexadecimal characters.
-     */
-    public static String encodeToString(byte[] data) {
-        return new String(encode(data));
-    }
-
-    /**
-     * Decodes the provided hexadecimal string into a byte array.  Odd-length inputs
-     * are not allowed.
-     *
-     * Throws an {@code IllegalArgumentException} if the input is malformed.
-     */
-    public static byte[] decode(String encoded) throws IllegalArgumentException {
-        return decode(encoded.toCharArray());
-    }
-
-    /**
-     * Decodes the provided hexadecimal string into a byte array. If {@code allowSingleChar}
-     * is {@code true} odd-length inputs are allowed and the first character is interpreted
-     * as the lower bits of the first result byte.
-     *
-     * Throws an {@code IllegalArgumentException} if the input is malformed.
-     */
-    public static byte[] decode(String encoded, boolean allowSingleChar) throws IllegalArgumentException {
-        return decode(encoded.toCharArray(), allowSingleChar);
-    }
-
-    /**
-     * Decodes the provided hexadecimal string into a byte array.  Odd-length inputs
-     * are not allowed.
-     *
-     * Throws an {@code IllegalArgumentException} if the input is malformed.
-     */
-    public static byte[] decode(char[] encoded) throws IllegalArgumentException {
-        return decode(encoded, false);
-    }
-
-    /**
-     * Decodes the provided hexadecimal string into a byte array. If {@code allowSingleChar}
-     * is {@code true} odd-length inputs are allowed and the first character is interpreted
-     * as the lower bits of the first result byte.
-     *
-     * Throws an {@code IllegalArgumentException} if the input is malformed.
-     */
-    public static byte[] decode(char[] encoded, boolean allowSingleChar) throws IllegalArgumentException {
-        int resultLengthBytes = (encoded.length + 1) / 2;
-        byte[] result = new byte[resultLengthBytes];
-
-        int resultOffset = 0;
-        int i = 0;
-        if (allowSingleChar) {
-            if ((encoded.length % 2) != 0) {
-                // Odd number of digits -- the first digit is the lower 4 bits of the first result byte.
-                result[resultOffset++] = (byte) toDigit(encoded, i);
-                i++;
-            }
-        } else {
-            if ((encoded.length % 2) != 0) {
-                throw new IllegalArgumentException("Invalid input length: " + encoded.length);
-            }
-        }
-
-        for (int len = encoded.length; i < len; i += 2) {
-            result[resultOffset++] = (byte) ((toDigit(encoded, i) << 4) | toDigit(encoded, i + 1));
-        }
-
-        return result;
-    }
-
-    private static int toDigit(char[] str, int offset) throws IllegalArgumentException {
-        // NOTE: that this isn't really a code point in the traditional sense, since we're
-        // just rejecting surrogate pairs outright.
-        int pseudoCodePoint = str[offset];
-
-        if ('0' <= pseudoCodePoint && pseudoCodePoint <= '9') {
-            return pseudoCodePoint - '0';
-        } else if ('a' <= pseudoCodePoint && pseudoCodePoint <= 'f') {
-            return 10 + (pseudoCodePoint - 'a');
-        } else if ('A' <= pseudoCodePoint && pseudoCodePoint <= 'F') {
-            return 10 + (pseudoCodePoint - 'A');
-        }
-
-        throw new IllegalArgumentException("Illegal char: " + str[offset] +
-                " at offset " + offset);
-    }
-}
diff --git a/tests/tests/rcs/Android.bp b/tests/tests/rcs/Android.bp
index 07b4d3b..5de3331 100644
--- a/tests/tests/rcs/Android.bp
+++ b/tests/tests/rcs/Android.bp
@@ -30,7 +30,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     platform_apis: true,
 }
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp b/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp
new file mode 100644
index 0000000..ef5284b
--- /dev/null
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp
@@ -0,0 +1,19 @@
+//////////////////////////////////////////////////////////////////
+// Signed Package
+
+android_test_import {
+    name: "signed-CtsSecureElementAccessControlTestCases1",
+    apk: "apk/signed-CtsSecureElementAccessControlTestCases1.apk",
+
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+        "cts-instant",
+    ],
+    // Make sure the build system doesn't try to resign the APK
+    presigned: true,
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/Android.mk b/tests/tests/secure_element/access_control/AccessControlApp1/Android.mk
index ef992e6..feda0fd 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp1/Android.mk
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/Android.mk
@@ -32,23 +32,6 @@
 LOCAL_JAVA_LIBRARIES += android.test.runner
 LOCAL_JAVA_LIBRARIES += android.test.base
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
-
-##################################################################
-# Signed Package
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := signed-CtsSecureElementAccessControlTestCases1
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE_CLASS := APPS
-LOCAL_BUILT_MODULE_STEM := package.apk
-# Make sure the build system doesn't try to resign the APK
-LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
-
-LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/signed-CtsSecureElementAccessControlTestCases1.apk
-
-include $(BUILD_PREBUILT)
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp b/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp
new file mode 100644
index 0000000..3cfeb55
--- /dev/null
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp
@@ -0,0 +1,19 @@
+//////////////////////////////////////////////////////////////////
+// Signed Package
+
+android_test_import {
+    name: "signed-CtsSecureElementAccessControlTestCases2",
+    apk: "apk/signed-CtsSecureElementAccessControlTestCases2.apk",
+
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+        "cts-instant",
+    ],
+    // Make sure the build system doesn't try to resign the APK
+    presigned: true,
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/Android.mk b/tests/tests/secure_element/access_control/AccessControlApp2/Android.mk
index 38f12ee..7c85540 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp2/Android.mk
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/Android.mk
@@ -32,23 +32,6 @@
 LOCAL_JAVA_LIBRARIES += android.test.runner
 LOCAL_JAVA_LIBRARIES += android.test.base
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
-
-##################################################################
-# Signed Package
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := signed-CtsSecureElementAccessControlTestCases2
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE_CLASS := APPS
-LOCAL_BUILT_MODULE_STEM := package.apk
-# Make sure the build system doesn't try to resign the APK
-LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
-
-LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/signed-CtsSecureElementAccessControlTestCases2.apk
-
-include $(BUILD_PREBUILT)
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp b/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp
new file mode 100644
index 0000000..9225e5d
--- /dev/null
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp
@@ -0,0 +1,19 @@
+//////////////////////////////////////////////////////////////////
+// Signed Package
+
+android_test_import {
+    name: "signed-CtsSecureElementAccessControlTestCases3",
+    apk: "apk/signed-CtsSecureElementAccessControlTestCases3.apk",
+
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+        "cts-instant",
+    ],
+    // Make sure the build system doesn't try to resign the APK
+    presigned: true,
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/Android.mk b/tests/tests/secure_element/access_control/AccessControlApp3/Android.mk
index 335c08a..1520360 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp3/Android.mk
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/Android.mk
@@ -32,23 +32,6 @@
 LOCAL_JAVA_LIBRARIES += android.test.runner
 LOCAL_JAVA_LIBRARIES += android.test.base
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
-
-##################################################################
-# Signed Package
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := signed-CtsSecureElementAccessControlTestCases3
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE_CLASS := APPS
-LOCAL_BUILT_MODULE_STEM := package.apk
-# Make sure the build system doesn't try to resign the APK
-LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
-
-LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/signed-CtsSecureElementAccessControlTestCases3.apk
-
-include $(BUILD_PREBUILT)
diff --git a/tests/tests/secure_element/omapi/Android.mk b/tests/tests/secure_element/omapi/Android.mk
index a8438f4..1ac3720 100644
--- a/tests/tests/secure_element/omapi/Android.mk
+++ b/tests/tests/secure_element/omapi/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_JAVA_LIBRARIES += android.test.base
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts-instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/security/res/raw/cve_2019_2129.3gp b/tests/tests/security/res/raw/cve_2019_2129.3gp
new file mode 100644
index 0000000..c461081
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2129.3gp
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_2327.mkv b/tests/tests/security/res/raw/cve_2019_2327.mkv
new file mode 100644
index 0000000..48a8559
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2327.mkv
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/PackageSignatureTest.java b/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
index 1f4eba1..6280ce8 100644
--- a/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
+++ b/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
@@ -133,6 +133,8 @@
             // Test package to verify upgrades to privileged applications
             "com.android.cts.priv.ctsshim",
             "com.android.cts.ctsshim",
+            // Test APEX used in CTS tests.
+            "com.android.apex.cts.shim,",
 
             // Oom Catcher package to prevent tests from ooming device.
             "com.android.cts.oomcatcher"
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index 64707eb..633f6d3 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -78,6 +78,7 @@
 import android.security.cts.R;
 
 import android.security.NetworkSecurityPolicy;
+import android.media.TimedText;
 
 /**
  * Verify that the device is not vulnerable to any known Stagefright
@@ -393,7 +394,7 @@
     @SecurityTest(minPatchLevel = "2017-08")
     public void testBug_38014992() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.bug_38014992_framelen);
-        doStagefrightTestRawBlob(R.raw.bug_38014992_avc, "video/avc", 640, 480, frameSizes);
+        doStagefrightTestRawBlob(R.raw.bug_38014992_avc, "video/avc", 640, 480, frameSizes, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-07")
@@ -465,7 +466,7 @@
     @SecurityTest(minPatchLevel = "2017-03")
     public void testBug_33818500() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.bug_33818500_framelen);
-        doStagefrightTestRawBlob(R.raw.bug_33818500_avc, "video/avc", 64, 32, frameSizes);
+        doStagefrightTestRawBlob(R.raw.bug_33818500_avc, "video/avc", 64, 32, frameSizes, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-01")
@@ -816,7 +817,7 @@
 
     @SecurityTest(minPatchLevel = "2017-07")
     public void testStagefright_bug_36279112() throws Exception {
-        doStagefrightTest(R.raw.bug_36279112);
+        doStagefrightTest(R.raw.bug_36279112, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-06")
@@ -893,7 +894,7 @@
         };
         server.start();
         String uri = "http://127.0.0.1:8080/bug_68342866.m3u8";
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(false);
         LooperThread t = new LooperThread(new Runnable() {
             @Override
             public void run() {
@@ -997,6 +998,11 @@
         doStagefrightTest(R.raw.cve_2018_11287, 180000);
     }
 
+    @SecurityTest(minPatchLevel = "2019-07")
+    public void testStagefright_cve_2019_2327() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_2327);
+    }
+
     @SecurityTest(minPatchLevel = "2018-03")
     public void testStagefright_cve_2017_17773() throws Exception {
         doStagefrightTest(R.raw.cve_2017_17773);
@@ -1106,11 +1112,15 @@
     }
 
     private void doStagefrightTest(final int rid) throws Exception {
+        doStagefrightTest(rid, true); // check addresss by default
+    }
+
+    private void doStagefrightTest(final int rid, boolean checkMinCrashAddress) throws Exception {
         NetworkSecurityPolicy policy = NetworkSecurityPolicy.getInstance();
         policy.setCleartextTrafficPermitted(true);
-        doStagefrightTestMediaPlayer(rid);
-        doStagefrightTestMediaCodec(rid);
-        doStagefrightTestMediaMetadataRetriever(rid);
+        doStagefrightTestMediaPlayer(rid, checkMinCrashAddress);
+        doStagefrightTestMediaCodec(rid, checkMinCrashAddress);
+        doStagefrightTestMediaMetadataRetriever(rid, checkMinCrashAddress);
 
         Context context = getInstrumentation().getContext();
         CtsTestServer server = null;
@@ -1126,9 +1136,9 @@
         String rname = resources.getResourceEntryName(rid);
         String url = server.getAssetUrl("raw/" + rname);
         verifyServer(rid, url);
-        doStagefrightTestMediaPlayer(url);
-        doStagefrightTestMediaCodec(url);
-        doStagefrightTestMediaMetadataRetriever(url);
+        doStagefrightTestMediaPlayer(url, checkMinCrashAddress);
+        doStagefrightTestMediaCodec(url, checkMinCrashAddress);
+        doStagefrightTestMediaMetadataRetriever(url, checkMinCrashAddress);
         policy.setCleartextTrafficPermitted(false);
         server.shutdown();
     }
@@ -1159,11 +1169,16 @@
     }
 
     private void doStagefrightTest(final int rid, int timeout) throws Exception {
+        doStagefrightTest(rid, true, timeout); // check crash address by default
+    }
+
+    private void doStagefrightTest(
+            final int rid, boolean checkMinCrashAddress, int timeout) throws Exception {
         runWithTimeout(new Runnable() {
             @Override
             public void run() {
                 try {
-                  doStagefrightTest(rid);
+                  doStagefrightTest(rid, checkMinCrashAddress);
                 } catch (Exception e) {
                   fail(e.toString());
                 }
@@ -1172,6 +1187,11 @@
     }
 
     private void doStagefrightTestANR(final int rid) throws Exception {
+        doStagefrightTestANR(rid, true); // check crash address by default
+    }
+
+    private void doStagefrightTestANR(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
         doStagefrightTestMediaPlayerANR(rid, null);
     }
 
@@ -1206,6 +1226,8 @@
         MediaPlayer.OnPreparedListener,
         MediaPlayer.OnCompletionListener {
 
+        boolean checkMinAddress = true;
+
         private final Pattern[] validProcessPatterns = {
             Pattern.compile("adsprpcd"),
             Pattern.compile("android\\.hardware\\.cas@\\d+?\\.\\d+?-service"),
@@ -1225,6 +1247,13 @@
             Pattern.compile("vendor.*"),
         };
 
+        MediaPlayerCrashListener() {
+        }
+
+        MediaPlayerCrashListener(boolean checkMinAddress) {
+            this.checkMinAddress = checkMinAddress;
+        }
+
         @Override
         public boolean onError(MediaPlayer mp, int newWhat, int extra) {
             Log.i(TAG, "error: " + newWhat + "/" + extra);
@@ -1270,7 +1299,8 @@
                 if (crashes == null) {
                     Log.e(TAG, "Crash results not found for test " + getName());
                     return what;
-                } else if (CrashUtils.securityCrashDetected(crashes, true, validProcessPatterns)) {
+                } else if (CrashUtils.securityCrashDetected(
+                        crashes, checkMinAddress, validProcessPatterns)) {
                     return what;
                 } else {
                     Log.i(TAG, "Crash ignored due to no security crash found for test " +
@@ -1318,11 +1348,21 @@
     }
 
     private void doStagefrightTestMediaPlayer(final int rid) throws Exception {
-        doStagefrightTestMediaPlayer(rid, null);
+        doStagefrightTestMediaPlayer(rid, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayer(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaPlayer(rid, null, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaPlayer(final String url) throws Exception {
-        doStagefrightTestMediaPlayer(-1, url);
+        doStagefrightTestMediaPlayer(url, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayer(
+            final String url, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaPlayer(-1, url, checkMinCrashAddress);
     }
 
     private void closeQuietly(AutoCloseable closeable) {
@@ -1337,12 +1377,17 @@
     }
 
     private void doStagefrightTestMediaPlayer(final int rid, final String uri) throws Exception {
+        doStagefrightTestMediaPlayer(rid, uri, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayer(final int rid, final String uri,
+            boolean checkMinCrashAddress) throws Exception {
 
         String name = uri != null ? uri :
             getInstrumentation().getContext().getResources().getResourceEntryName(rid);
         Log.i(TAG, "start mediaplayer test for: " + name);
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread t = new LooperThread(new Runnable() {
             @Override
@@ -1388,17 +1433,106 @@
         t.join(); // wait for thread to exit so we're sure the player was released
     }
 
+    /*
+     * b/135207745
+     */
+    @SecurityTest(minPatchLevel = "2019-08")
+    public void testStagefright_cve_2019_2129() throws Exception {
+        final int rid = R.raw.cve_2019_2129;
+        String name = getInstrumentation().getContext().getResources().getResourceEntryName(rid);
+        Log.i(TAG, "start mediaplayer test for: " + name);
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener() {
+            @Override
+            public void onPrepared(MediaPlayer mp) {
+                super.onPrepared(mp);
+                mp.setLooping(true);
+            }
+        };
+
+        LooperThread t = new LooperThread(new Runnable() {
+            @Override
+            public void run() {
+                MediaPlayer mp = new MediaPlayer();
+                mp.setOnErrorListener(mpcl);
+                mp.setOnPreparedListener(mpcl);
+                mp.setOnCompletionListener(mpcl);
+                RenderTarget renderTarget = RenderTarget.create();
+                Surface surface = renderTarget.getSurface();
+                mp.setSurface(surface);
+                AssetFileDescriptor fd = null;
+                try {
+                    fd = getInstrumentation().getContext().getResources().openRawResourceFd(rid);
+                    mp.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
+                        @Override
+                        public void onTimedText(MediaPlayer p, TimedText text) {
+                            if (text != null) {
+                                Log.d(TAG, "text = " + text.getText());
+                            }
+                        }
+                    });
+                    mp.setDataSource(fd.getFileDescriptor(),
+                                     fd.getStartOffset(),
+                                     fd.getLength());
+                    //  keep the original as in poc by not using prepareAsync
+                    mp.prepare();
+                    mp.selectTrack(2);
+                } catch (Exception e) {
+                    Log.e(TAG, "Exception is caught " + e.getMessage());
+                    e.printStackTrace();
+                } finally {
+                    closeQuietly(fd);
+                }
+
+                try {
+                    //  here to catch & swallow the runtime crash in exception
+                    //  after the place where original poc failed in
+                    //  java.lang.IllegalArgumentException: parseParcel()
+                    //  which is beyond test control.
+                    Looper.loop();
+                } catch (RuntimeException e) {
+                    Log.e(TAG, "Exception is caught on Looper.loop() " + e.getMessage());
+                    e.printStackTrace();
+                }
+                mp.release();
+                renderTarget.destroy();
+            }
+        });
+
+        t.start();
+        String cve = name.replace("_", "-").toUpperCase();
+        assertFalse("Device *IS* vulnerable to " + cve,
+                    mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
+        t.stopLooper();
+        t.join(); // wait for thread to exit so we're sure the player was released
+    }
+
     private void doStagefrightTestMediaCodec(final int rid) throws Exception {
-        doStagefrightTestMediaCodec(rid, null);
+        doStagefrightTestMediaCodec(rid, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaCodec(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaCodec(rid, null, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaCodec(final String url) throws Exception {
-        doStagefrightTestMediaCodec(-1, url);
+        doStagefrightTestMediaCodec(url, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaCodec(
+            final String url, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaCodec(-1, url, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaCodec(final int rid, final String url) throws Exception {
+        doStagefrightTestMediaCodec(rid, url, true); // check crash address by default
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestMediaCodec(
+            final int rid, final String url, boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread thr = new LooperThread(new Runnable() {
             @Override
@@ -1556,17 +1690,31 @@
     }
 
     private void doStagefrightTestMediaMetadataRetriever(final int rid) throws Exception {
-        doStagefrightTestMediaMetadataRetriever(rid, null);
+        doStagefrightTestMediaMetadataRetriever(rid, true); // check crash address by default
+    }
+    private void doStagefrightTestMediaMetadataRetriever(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaMetadataRetriever(rid, null, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaMetadataRetriever(final String url) throws Exception {
-        doStagefrightTestMediaMetadataRetriever(-1, url);
+        doStagefrightTestMediaMetadataRetriever(url, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaMetadataRetriever(
+            final String url, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaMetadataRetriever(-1, url, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaMetadataRetriever(
             final int rid, final String url) throws Exception {
+        doStagefrightTestMediaMetadataRetriever(rid, url, true); // check crash address by default
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestMediaMetadataRetriever(
+            final int rid, final String url, boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread thr = new LooperThread(new Runnable() {
             @Override
@@ -1646,7 +1794,7 @@
 
     @SecurityTest(minPatchLevel = "2017-05")
     public void testBug36895511() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_36895511, "video/hevc", 320, 240);
+        doStagefrightTestRawBlob(R.raw.bug_36895511, "video/hevc", 320, 240, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-11")
@@ -1676,7 +1824,7 @@
 
     @SecurityTest(minPatchLevel = "2018-04")
     public void testBug_70897394() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_70897394_avc, "video/avc", 320, 240);
+        doStagefrightTestRawBlob(R.raw.bug_70897394_avc, "video/avc", 320, 240, false);
     }
 
     private int[] getFrameSizes(int rid) throws IOException {
@@ -1716,9 +1864,16 @@
         }, 5000);
     }
 
-    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight) throws Exception {
+    private void doStagefrightTestRawBlob(
+            int rid, String mime, int initWidth, int initHeight) throws Exception {
+        // check crash address by default
+        doStagefrightTestRawBlob(rid, mime, initWidth, initHeight, true);
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
+            boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
         final Context context = getInstrumentation().getContext();
         final Resources resources =  context.getResources();
 
@@ -1831,9 +1986,15 @@
     }
 
     private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
-        int frameSizes[]) throws Exception {
+            int frameSizes[]) throws Exception {
+        // check crash address by default
+        doStagefrightTestRawBlob(rid, mime, initWidth, initHeight, frameSizes, true);
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
+            int frameSizes[], boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
         final Context context = getInstrumentation().getContext();
         final Resources resources =  context.getResources();
 
@@ -1967,11 +2128,16 @@
     }
 
     private void doStagefrightTestMediaPlayerANR(final int rid, final String uri) throws Exception {
+        doStagefrightTestMediaPlayerANR(rid, uri, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayerANR(final int rid, final String uri,
+            boolean checkMinCrashAddress) throws Exception {
         String name = uri != null ? uri :
             getInstrumentation().getContext().getResources().getResourceEntryName(rid);
         Log.i(TAG, "start mediaplayerANR test for: " + name);
 
-        final MediaPlayerCrashListener mpl = new MediaPlayerCrashListener();
+        final MediaPlayerCrashListener mpl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread t = new LooperThread(new Runnable() {
             @Override
@@ -2015,7 +2181,12 @@
     }
 
     private void doStagefrightTestExtractorSeek(final int rid, final long offset) throws Exception {
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        doStagefrightTestExtractorSeek(rid, offset, true); // check crash address by default
+    }
+
+    private void doStagefrightTestExtractorSeek(final int rid, final long offset,
+            boolean checkMinCrashAddress) throws Exception {
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
         LooperThread thr = new LooperThread(new Runnable() {
             @Override
             public void run() {
diff --git a/tests/tests/slice/Android.bp b/tests/tests/slice/Android.bp
index bc25d6c..d3b8083 100644
--- a/tests/tests/slice/Android.bp
+++ b/tests/tests/slice/Android.bp
@@ -18,6 +18,7 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
+        "sts",
         "vts",
         "general-tests",
     ],
diff --git a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java
new file mode 100644
index 0000000..2a2e8e4
--- /dev/null
+++ b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2019 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.slice.cts;
+
+import android.app.slice.Slice;
+import android.app.slice.SliceSpec;
+import android.content.ContentResolver;
+import android.net.Uri;
+import android.os.Bundle;
+
+import androidx.test.rule.ActivityTestRule;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.android.collect.Lists;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class SliceProviderTest {
+
+    private static final String VALID_AUTHORITY = "android.slice.cts";
+    private static final String SUSPICIOUS_AUTHORITY = "com.suspicious.www";
+    private static final String ACTION_BLUETOOTH = "/action/bluetooth";
+    private static final String VALID_BASE_URI_STRING = "content://" + VALID_AUTHORITY;
+    private static final String VALID_ACTION_URI_STRING =
+            "content://" + VALID_AUTHORITY + ACTION_BLUETOOTH;
+    private static final String SHADY_ACTION_URI_STRING =
+            "content://" + SUSPICIOUS_AUTHORITY + ACTION_BLUETOOTH;
+
+    @Rule
+    public ActivityTestRule<Launcher> mLauncherActivityTestRule = new ActivityTestRule<>(Launcher.class);
+
+    private Uri validBaseUri = Uri.parse(VALID_BASE_URI_STRING);
+    private Uri validActionUri = Uri.parse(VALID_ACTION_URI_STRING);
+    private Uri shadyActionUri = Uri.parse(SHADY_ACTION_URI_STRING);
+
+    private ContentResolver mContentResolver;
+
+    @Before
+    public void setUp() {
+        mContentResolver = mLauncherActivityTestRule.getActivity().getContentResolver();
+    }
+
+    @Test
+    public void testCallSliceUri_ValidAuthority() {
+        doQuery(validActionUri);
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testCallSliceUri_ShadyAuthority() {
+        doQuery(shadyActionUri);
+    }
+
+    private Slice doQuery(Uri actionUri) {
+        Bundle extras = new Bundle();
+        extras.putParcelable("slice_uri", actionUri);
+        extras.putParcelableArrayList("supported_specs", Lists.newArrayList(
+                    new SliceSpec("androidx.slice.LIST", 1),
+                    new SliceSpec("androidx.app.slice.BASIC", 1),
+                    new SliceSpec("androidx.slice.BASIC", 1),
+                    new SliceSpec("androidx.app.slice.LIST", 1)
+            ));
+        Bundle result = mContentResolver.call(
+                validBaseUri,
+                SliceProvider.METHOD_SLICE,
+                null,
+                extras
+        );
+        return result.getParcelable(SliceProvider.EXTRA_SLICE);
+    }
+
+}
diff --git a/tests/tests/systemui/Android.bp b/tests/tests/systemui/Android.bp
index 51d1af4..b9ab2ac 100644
--- a/tests/tests/systemui/Android.bp
+++ b/tests/tests/systemui/Android.bp
@@ -19,7 +19,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     libs: ["android.test.runner.stubs"],
     static_libs: [
diff --git a/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java b/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java
index 7ca476c..3a70017 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java
@@ -22,10 +22,12 @@
 import static org.junit.Assert.assertThat;
 
 import android.content.Context;
+import android.database.Cursor;
 import android.graphics.drawable.Icon;
 import android.media.AudioManager;
 import android.os.Bundle;
 import android.net.Uri;
+import android.provider.CallLog;
 import android.telecom.Call;
 import android.telecom.Connection;
 import android.telecom.ConnectionRequest;
@@ -38,6 +40,8 @@
 
 import java.util.Arrays;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Suites of tests that verifies the various Call details.
@@ -72,6 +76,7 @@
     public static final int TEST_EXTRA_VALUE = 10;
     public static final String TEST_EVENT = "com.test.event.TEST";
     public static final Uri TEST_DEFLECT_URI = Uri.fromParts("tel", "+16505551212", null);
+    private static final int ASYNC_TIMEOUT = 10000;
     private StatusHints mStatusHints;
     private Bundle mExtras = new Bundle();
 
@@ -752,4 +757,29 @@
                 "Call should have extras key " + expectedKey
         );
     }
+
+    /**
+     * Tests whether the CallLogManager logs the features of a call(HD call and Wifi call)
+     * correctly.
+     */
+    public void testLogHdAndWifi() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
+        // Register content observer on call log and get latch
+        CountDownLatch callLogEntryLatch = getCallLogEntryLatch();
+        mCall.disconnect();
+
+        // Wait on the call log latch.
+        callLogEntryLatch.await(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+
+        // Verify the contents of the call log
+        Cursor callsCursor = mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null,
+                "features", null, null);
+        int features = callsCursor.getColumnIndex(CallLog.Calls.FEATURES);
+        assertEquals(CallLog.Calls.FEATURES_HD_CALL,
+                features & CallLog.Calls.FEATURES_HD_CALL);
+        assertEquals(CallLog.Calls.FEATURES_WIFI, features & CallLog.Calls.FEATURES_WIFI);
+    }
 }
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 340841e..febb89d 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -548,10 +548,6 @@
             changeAndVerifySubscriptionEnabledValue(mSubId, !enabled);
             // Reset it back to original
             changeAndVerifySubscriptionEnabledValue(mSubId, enabled);
-        } else {
-            boolean changeSuccessfully = executeWithShellPermissionAndDefault(false, mSm,
-                    (sm) -> sm.setSubscriptionEnabled(mSubId, !enabled));
-            assertFalse(changeSuccessfully);
         }
     }
 
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
index c0e08f1..6134d47 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
@@ -730,11 +730,19 @@
 
     @Test
     public void testGetNetworkCountryIso() {
-        String countryCode = mTelephonyManager.getNetworkCountryIso();
         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            String countryCode = mTelephonyManager.getNetworkCountryIso();
             assertTrue("Country code '" + countryCode + "' did not match "
                     + ISO_COUNTRY_CODE_PATTERN,
                     Pattern.matches(ISO_COUNTRY_CODE_PATTERN, countryCode));
+
+            for (int i = 0; i < mTelephonyManager.getPhoneCount(); i++) {
+                countryCode = mTelephonyManager.getNetworkCountryIso(i);
+
+                assertTrue("Country code '" + countryCode + "' did not match "
+                                + ISO_COUNTRY_CODE_PATTERN + " for slot " + i,
+                        Pattern.matches(ISO_COUNTRY_CODE_PATTERN, countryCode));
+            }
         } else {
             // Non-telephony may still have the property defined if it has a SIM.
         }
@@ -1003,7 +1011,7 @@
         synchronized (mLock) {
             t.start();
             if (!mServiceStateChangedCalled) {
-                mLock.wait(10000);
+                mLock.wait(60000);
             }
         }
         assertThat(mTelephonyManager.getServiceState().getState()).isEqualTo(
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java
new file mode 100644
index 0000000..a6a2c4f
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java
@@ -0,0 +1,35 @@
+package android.telephony.cts;
+
+import static org.junit.Assert.fail;
+
+import android.content.Context;
+import android.os.telephony.TelephonyRegistryManager;
+import androidx.test.InstrumentationRegistry;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Test TelephonyRegistryManagerTest APIs.
+ */
+public class TelephonyRegistryManagerTest {
+    private TelephonyRegistryManager mTelephonyRegistryMgr;
+
+    @Before
+    public void setUp() throws Exception {
+        mTelephonyRegistryMgr = (TelephonyRegistryManager) InstrumentationRegistry.getContext()
+            .getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
+    }
+
+    /**
+     * expect security exception as there is no carrier privilege permission.
+     */
+    @Test
+    public void testNotifyCarrierNetworkChange() {
+        try {
+            mTelephonyRegistryMgr.notifyCarrierNetworkChange(true);
+            fail("Expected SecurityException for notifyCarrierNetworkChange");
+        } catch (SecurityException ex) {
+            /* Expected */
+        }
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/telephonyprovider/Android.mk b/tests/tests/telephonyprovider/Android.mk
index 8422431..45d041f 100755
--- a/tests/tests/telephonyprovider/Android.mk
+++ b/tests/tests/telephonyprovider/Android.mk
@@ -36,7 +36,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsTelephonyProviderTestCases
 
diff --git a/tests/tests/text/Android.bp b/tests/tests/text/Android.bp
index cadb6b8..f3d34bf 100644
--- a/tests/tests/text/Android.bp
+++ b/tests/tests/text/Android.bp
@@ -48,7 +48,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
         "mts",
     ],
 }
diff --git a/tests/tests/text/src/android/text/cts/BoringLayoutTest.java b/tests/tests/text/src/android/text/cts/BoringLayoutTest.java
index 5f17b32..cb62639 100644
--- a/tests/tests/text/src/android/text/cts/BoringLayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/BoringLayoutTest.java
@@ -20,6 +20,7 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
@@ -264,6 +265,17 @@
     }
 
     @Test
+    public void testIsBoringForEmptyString() {
+        Metrics metrics = new Metrics();
+        assertNotNull(BoringLayout.isBoring("", new TextPaint(), metrics));
+
+        // The default font Roboto has non-zero ascent/descent values. If metrics returns zeros, it
+        // means failed to retrieve the font metrics.
+        assertNotEquals(0, metrics.ascent);
+        assertNotEquals(0, metrics.descent);
+    }
+
+    @Test
     public void testIsBoring_resetsFontMetrics() {
         int someInt = 100;
         String text = "some text";
diff --git a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
index 56a6c85..00856cd 100644
--- a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
@@ -1681,4 +1681,32 @@
         end = LOREM_IPSUM.length();
         testLineBackgroundSpanInRange(LOREM_IPSUM, start, end);
     }
+
+    // This is for b/140755449
+    @Test
+    public void testBidiVisibleEnd() {
+        TextPaint paint = new TextPaint();
+        // The default text size is too small and not useful for handling line breaks.
+        // Make it bigger.
+        paint.setTextSize(32);
+
+        final String input = "\u05D0aaaaaa\u3000 aaaaaa";
+        // To make line break happen, pass slightly shorter width from the full text width.
+        final int lineBreakWidth = (int) (paint.measureText(input) * 0.8);
+        final StaticLayout layout = StaticLayout.Builder.obtain(
+                input, 0, input.length(), paint, lineBreakWidth).build();
+
+        // Make sure getLineMax won't cause crashes.
+        // getLineMax eventually calls TextLine.measure which was the problematic method.
+        layout.getLineMax(0);
+
+        final Bitmap bmp = Bitmap.createBitmap(
+                layout.getWidth(),
+                layout.getHeight(),
+                Bitmap.Config.RGB_565);
+        final Canvas c = new Canvas(bmp);
+        // Make sure draw won't cause crashes.
+        // draw eventualy calls TextLine.draw which was the problematic method.
+        layout.draw(c);
+    }
 }
diff --git a/tests/tests/toast/Android.bp b/tests/tests/toast/Android.bp
index 72c785f..69dcf15 100644
--- a/tests/tests/toast/Android.bp
+++ b/tests/tests/toast/Android.bp
@@ -21,7 +21,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     static_libs: [
         "androidx.test.rules",
diff --git a/tests/tests/tools/processors/view_inspector/Android.bp b/tests/tests/tools/processors/view_inspector/Android.bp
index 342eecd..65c78cc 100644
--- a/tests/tests/tools/processors/view_inspector/Android.bp
+++ b/tests/tests/tools/processors/view_inspector/Android.bp
@@ -30,6 +30,5 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ]
 }
diff --git a/tests/tests/uiautomation/Android.bp b/tests/tests/uiautomation/Android.bp
index 67f3ed7..6a0ba7c 100644
--- a/tests/tests/uiautomation/Android.bp
+++ b/tests/tests/uiautomation/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     static_libs: [
         "CtsAccessibilityCommon",
diff --git a/tests/tests/uiautomation/AndroidManifest.xml b/tests/tests/uiautomation/AndroidManifest.xml
index b1e5821..75eab20 100644
--- a/tests/tests/uiautomation/AndroidManifest.xml
+++ b/tests/tests/uiautomation/AndroidManifest.xml
@@ -23,7 +23,7 @@
   <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
-  <uses-permission android:name="android.permission.RECORD_AUDIO" />
+  <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
 
   <application android:theme="@android:style/Theme.Holo.NoActionBar"
           android:requestLegacyExternalStorage="true">
diff --git a/tests/tests/uiautomation/AndroidTest.xml b/tests/tests/uiautomation/AndroidTest.xml
index 05bfc9c..e05dc4b 100644
--- a/tests/tests/uiautomation/AndroidTest.xml
+++ b/tests/tests/uiautomation/AndroidTest.xml
@@ -23,7 +23,7 @@
         <option name="test-file-name" value="CtsUiAutomationTestCases.apk" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="pm revoke android.app.uiautomation.cts android.permission.RECORD_AUDIO" />
+        <option name="run-command" value="pm revoke android.app.uiautomation.cts android.permission.ANSWER_PHONE_CALLS" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.app.uiautomation.cts" />
diff --git a/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java b/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java
index f5df2c0..9135e56 100755
--- a/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java
+++ b/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java
@@ -99,7 +99,7 @@
         }
         try {
             packageManager.grantRuntimePermission(context.getPackageName(),
-                    Manifest.permission.RECORD_AUDIO, Process.myUserHandle());
+                    Manifest.permission.ANSWER_PHONE_CALLS, Process.myUserHandle());
             fail("Should not be able to access APIs protected by a permission apps cannot get");
         } catch (SecurityException e) {
             /* expected */
@@ -113,17 +113,17 @@
             activityManager.getPackageImportance("foo.bar.baz");
 
             // Grant ourselves a runtime permission (was granted at install)
-            assertSame(packageManager.checkPermission(Manifest.permission.RECORD_AUDIO,
+            assertSame(packageManager.checkPermission(Manifest.permission.ANSWER_PHONE_CALLS,
                     context.getPackageName()), PackageManager.PERMISSION_DENIED);
             packageManager.grantRuntimePermission(context.getPackageName(),
-                    Manifest.permission.RECORD_AUDIO, Process.myUserHandle());
+                    Manifest.permission.ANSWER_PHONE_CALLS, Process.myUserHandle());
         } catch (SecurityException e) {
             fail("Should be able to access APIs protected by a permission apps cannot get");
         } finally {
             getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
         }
         // Make sure the grant worked
-        assertSame(packageManager.checkPermission(Manifest.permission.RECORD_AUDIO,
+        assertSame(packageManager.checkPermission(Manifest.permission.ANSWER_PHONE_CALLS,
                 context.getPackageName()), PackageManager.PERMISSION_GRANTED);
 
 
@@ -136,7 +136,7 @@
         }
         try {
             packageManager.revokeRuntimePermission(context.getPackageName(),
-                    Manifest.permission.RECORD_AUDIO, Process.myUserHandle());
+                    Manifest.permission.ANSWER_PHONE_CALLS, Process.myUserHandle());
             fail("Should not be able to access APIs protected by a permission apps cannot get");
         } catch (SecurityException e) {
             /* expected */
diff --git a/tests/tests/uidisolation/Android.bp b/tests/tests/uidisolation/Android.bp
index 80059bc..f202038 100644
--- a/tests/tests/uidisolation/Android.bp
+++ b/tests/tests/uidisolation/Android.bp
@@ -20,7 +20,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
     static_libs: [
         "ctstestrunner-axt",
diff --git a/tests/tests/uirendering/res/layout/viewpropertyanimator_test_layout.xml b/tests/tests/uirendering/res/layout/viewpropertyanimator_test_layout.xml
new file mode 100644
index 0000000..b6f67d8
--- /dev/null
+++ b/tests/tests/uirendering/res/layout/viewpropertyanimator_test_layout.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+             android:background="#FFFFFF"
+             android:layout_width="match_parent"
+             android:layout_height="match_parent">
+    <FrameLayout
+        android:id="@+id/viewalpha_test_container"
+        android:background="#0000FF"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent">
+            <android.uirendering.cts.testclasses.view.AlphaTestView
+                android:id="@+id/alpha_test_view"
+                android:layout_width="100px"
+                android:layout_height="100px"
+            />
+    </FrameLayout>
+</FrameLayout>
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
index db37463..f42b004 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
@@ -562,8 +562,10 @@
                     // Adjust Y to match the same gradient percentage, regardless of vertical
                     // fading edge length.
                     int verticalFadingEdgeLength = webview.getVerticalFadingEdgeLength();
-                    testPoints[2].y = TEST_HEIGHT - verticalFadingEdgeLength * 10 / 42;
-                    testPoints[3].y = TEST_HEIGHT - verticalFadingEdgeLength * 5 / 42;
+                    testPoints[2].y = TEST_HEIGHT
+                        - (int) Math.round(verticalFadingEdgeLength * 10.0 / 42);
+                    testPoints[3].y = TEST_HEIGHT
+                        - (int) Math.round(verticalFadingEdgeLength * 5.0 / 42);
                 }, true, hwFence)
                 .runWithVerifier(new SamplePointVerifier(
                         testPoints,
@@ -603,8 +605,10 @@
                     // Adjust Y to match the same gradient percentage, regardless of vertical
                     // fading edge length.
                     int verticalFadingEdgeLength = webview.getVerticalFadingEdgeLength();
-                    testPoints[3].y = TEST_HEIGHT - verticalFadingEdgeLength * 10 / 42;
-                    testPoints[4].y = TEST_HEIGHT - verticalFadingEdgeLength * 5 / 42;
+                    testPoints[3].y = TEST_HEIGHT
+                        - (int) Math.round(verticalFadingEdgeLength * 10.0 / 42);
+                    testPoints[4].y = TEST_HEIGHT
+                        - (int) Math.round(verticalFadingEdgeLength * 5.0 / 42);
                 }, true, hwFence)
                 .runWithVerifier(new SamplePointVerifier(
                         testPoints,
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ViewPropertyAnimatorTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ViewPropertyAnimatorTests.java
new file mode 100644
index 0000000..0f749d9
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ViewPropertyAnimatorTests.java
@@ -0,0 +1,542 @@
+/*
+ * Copyright (C) 2019 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.uirendering.cts.testclasses;
+
+import static junit.framework.Assert.assertEquals;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.graphics.Color;
+import android.uirendering.cts.R;
+import android.uirendering.cts.bitmapverifiers.ColorVerifier;
+import android.uirendering.cts.testclasses.view.AlphaTestView;
+import android.uirendering.cts.testinfrastructure.ActivityTestBase;
+import android.uirendering.cts.testinfrastructure.ViewInitializer;
+import android.view.View;
+import android.view.ViewPropertyAnimator;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.CountDownLatch;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class ViewPropertyAnimatorTests extends ActivityTestBase {
+
+    @Test
+    public void testViewCustomAlpha() {
+        createViewPropertyAnimatorTest(new ViewPropertyAnimatorTestDelegate<AlphaTestView>() {
+            @Override
+            public void configureView(AlphaTestView target) {
+                target.setStartColor(Color.RED);
+                target.setEndColor(Color.BLUE);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.alpha(0.0f);
+            }
+
+            @Override
+            public void verifyViewState(AlphaTestView target) {
+                assertEquals(Color.BLUE, target.getBlendedColor());
+            }
+
+        }).runWithVerifier(new ColorVerifier(Color.BLUE));
+    }
+
+    @Test
+    public void testViewNonCustomAlpha() {
+        final CountDownLatch latch = new CountDownLatch(1);
+        createTest().addLayout(R.layout.viewpropertyanimator_test_layout,
+                (ViewInitializer) view -> {
+                    View testContent = view.findViewById(R.id.viewalpha_test_container);
+                    testContent.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() {
+                        @Override
+                        public void onAnimationEnd(Animator animation) {
+                            latch.countDown();
+                        }
+                    }).setDuration(16).start();
+                }, true, latch).runWithVerifier(new ColorVerifier(Color.WHITE));
+    }
+
+    @Test
+    public void testViewCustomAlphaBy() {
+        createViewPropertyAnimatorTest(new ViewPropertyAnimatorTestDelegate<AlphaTestView>() {
+            @Override
+            public void configureView(AlphaTestView target) {
+                target.setStartColor(Color.RED);
+                target.setEndColor(Color.BLUE);
+                target.setAlpha(0.5f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.alphaBy(-0.5f);
+            }
+
+            @Override
+            public void verifyViewState(AlphaTestView target) {
+                assertEquals(Color.BLUE, target.getBlendedColor());
+            }
+
+        }).runWithVerifier(new ColorVerifier(Color.BLUE));
+    }
+
+    @Test
+    public void testViewTranslateX() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.translationX(100.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(100.0f, target.getTranslationX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewTranslateXBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setTranslationX(20.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.translationXBy(100.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(120.0f, target.getTranslationX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewTranslateY() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.translationY(60.0f);
+
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(60.0f, target.getTranslationY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewTranslateYBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setTranslationY(30.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.translationYBy(60.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(90.0f, target.getTranslationY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewTranslateZ() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.translationZ(30.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(30.0f, target.getTranslationZ());
+            }
+        });
+    }
+
+    @Test
+    public void testViewTranslateZBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setTranslationZ(40.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.translationZBy(30.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(70.0f, target.getTranslationZ());
+            }
+        });
+    }
+
+    @Test
+    public void testViewRotation() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.rotation(20.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(20.0f, target.getRotation());
+            }
+        });
+    }
+
+    @Test
+    public void testViewRotationBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setRotation(30.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.rotationBy(20.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(50.0f, target.getRotation());
+            }
+        });
+    }
+
+    @Test
+    public void testViewRotationX() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.rotationX(80.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(80.0f, target.getRotationX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewRotationXBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setRotationX(30.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.rotationXBy(80.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(110.0f, target.getRotationX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewRotationY() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.rotationY(25.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(25.0f, target.getRotationY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewRotationYBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setRotationY(10.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.rotationYBy(25.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(35.0f, target.getRotationY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewScaleX() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.scaleX(2.5f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(2.5f, target.getScaleX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewScaleXBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setScaleX(1.2f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.scaleXBy(2.5f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(3.7f, target.getScaleX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewScaleY() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.scaleY(3.2f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(3.2f, target.getScaleY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewScaleYBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setScaleY(1.2f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.scaleYBy(3.2f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(4.4f, target.getScaleY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewX() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.x(27.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(27.0f, target.getX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewXBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setX(140.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.xBy(27.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(167.0f, target.getX());
+            }
+        });
+    }
+
+    @Test
+    public void testViewY() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.y(77.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(77.0f, target.getY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewYBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setY(80.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.yBy(77.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(157.0f, target.getY());
+            }
+        });
+    }
+
+    @Test
+    public void testViewZ() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.z(17.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(17.0f, target.getZ());
+            }
+        });
+    }
+
+    @Test
+    public void testViewZBy() {
+        runViewPropertyAnimatorTestWithoutVerification(new ViewPropertyAnimatorTestDelegate() {
+
+            @Override
+            public void configureView(View target) {
+                target.setZ(38.0f);
+            }
+
+            @Override
+            public void configureAnimator(ViewPropertyAnimator animator) {
+                animator.zBy(17.0f);
+            }
+
+            @Override
+            public void verifyViewState(View target) {
+                assertEquals(55.0f, target.getZ());
+            }
+        });
+    }
+
+    private void runViewPropertyAnimatorTestWithoutVerification(
+            ViewPropertyAnimatorTestDelegate delegate) {
+        createViewPropertyAnimatorTest(delegate).runWithoutVerification();
+    }
+
+    private TestCaseBuilder createViewPropertyAnimatorTest(
+            final ViewPropertyAnimatorTestDelegate delegate) {
+        final CountDownLatch latch = new CountDownLatch(1);
+        return createTest().addLayout(R.layout.viewpropertyanimator_test_layout,
+                (ViewInitializer) view -> {
+                    AlphaTestView alphaView = view.findViewById(R.id.alpha_test_view);
+                    delegate.configureView(alphaView);
+                    alphaView.setStartColor(Color.RED);
+                    alphaView.setEndColor(Color.BLUE);
+                    ViewPropertyAnimator animator = alphaView.animate();
+                    delegate.configureAnimator(animator);
+                    animator.setListener(
+                            new AnimatorListenerAdapter() {
+
+                                @Override
+                                public void onAnimationEnd(Animator animator) {
+                                    delegate.verifyViewState(alphaView);
+                                    latch.countDown();
+                                }
+
+                            }).setDuration(16).start();
+                }, true, latch);
+    }
+
+    private interface ViewPropertyAnimatorTestDelegate<T extends View> {
+
+        default void configureView(T target) {
+            // NO-OP
+        }
+
+        void configureAnimator(ViewPropertyAnimator animator);
+
+        void verifyViewState(T target);
+    }
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
index 8ea5834..a7652df 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
@@ -148,7 +148,7 @@
                 .runWithVerifier(getVerifier(
                             new Point[] { new Point(0, 0), new Point(50, 50) },
                             new Color[] { greenP3, greenP3 },
-                            .001f));
+                            .002f));
     }
 
     private static Color plus(Color a, Color b) {
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/view/AlphaTestView.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/view/AlphaTestView.java
new file mode 100644
index 0000000..d475c8f
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/view/AlphaTestView.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2019 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.uirendering.cts.testclasses.view;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.util.AttributeSet;
+import android.view.View;
+
+/**
+ * Test View used to verify a View's custom alpha implementation logic
+ * in conjunction with {@link android.view.ViewPropertyAnimator}
+ */
+public class AlphaTestView extends View {
+
+    private Paint mPaint = new Paint();
+    private int mStartColor = Color.RED;
+    private int mEndColor = Color.BLUE;
+
+    public AlphaTestView(Context context) {
+        super(context);
+    }
+
+    public AlphaTestView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public AlphaTestView(Context context, AttributeSet attrs, int defStyleAttr) {
+        super(context, attrs, defStyleAttr);
+    }
+
+    public AlphaTestView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+    }
+
+    public void setStartColor(int startColor) {
+        mStartColor = startColor;
+        mPaint.setColor(mStartColor);
+    }
+
+    public void setEndColor(int endColor) {
+        mEndColor = endColor;
+    }
+
+    @Override
+    protected boolean onSetAlpha(int alpha) {
+        mPaint.setColor(blendColor(mStartColor, mEndColor, 1.0f - alpha / 255.0f));
+        return true;
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        canvas.drawRect(getLeft(), getTop(), getRight(), getBottom(), mPaint);
+    }
+
+    public int getBlendedColor() {
+        return mPaint.getColor();
+    }
+
+    private int blendColor(int color1, int color2, float ratio) {
+        float inverseRatio = 1 - ratio;
+        float a = (float) Color.alpha(color1) * inverseRatio + (float) Color.alpha(color2) * ratio;
+        float r = (float) Color.red(color1) * inverseRatio + (float) Color.red(color2) * ratio;
+        float g = (float) Color.green(color1) * inverseRatio + (float) Color.green(color2) * ratio;
+        float b = (float) Color.blue(color1) * inverseRatio + (float) Color.blue(color2) * ratio;
+        return Color.argb((int) a, (int) r, (int) g, (int) b);
+    }
+}
diff --git a/tests/tests/view/Android.mk b/tests/tests/view/Android.mk
index ee792d0..bb4a657 100644
--- a/tests/tests/view/Android.mk
+++ b/tests/tests/view/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MULTILIB := both
 
diff --git a/tests/tests/view/sdk28/Android.bp b/tests/tests/view/sdk28/Android.bp
index 1356ef7..1056390 100644
--- a/tests/tests/view/sdk28/Android.bp
+++ b/tests/tests/view/sdk28/Android.bp
@@ -21,7 +21,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
     compile_multilib: "both",
diff --git a/tests/tests/voicesettings/AndroidManifest.xml b/tests/tests/voicesettings/AndroidManifest.xml
index 5ea6a84..8be0b80 100644
--- a/tests/tests/voicesettings/AndroidManifest.xml
+++ b/tests/tests/voicesettings/AndroidManifest.xml
@@ -23,7 +23,7 @@
     <application>
         <uses-library android:name="android.test.runner" />
 
-        <activity android:name="com.android.compatibility.common.util.BroadcastTestStartActivity"
+        <activity android:name=".BroadcastTestStartActivity"
                   android:label="The Target Activity for VoiceSettings CTS Test">
             <intent-filter>
                 <action android:name="android.intent.action.TEST_START_ACTIVITY_ZEN_MODE" />
diff --git a/tests/tests/voicesettings/AndroidTest.xml b/tests/tests/voicesettings/AndroidTest.xml
index 6de903a..11e749e 100644
--- a/tests/tests/voicesettings/AndroidTest.xml
+++ b/tests/tests/voicesettings/AndroidTest.xml
@@ -25,7 +25,6 @@
         <option name="test-file-name" value="CtsVoiceSettingsTestCases.apk" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="settings put secure voice_interaction_service android.voicesettings.service/.MainInteractionService" />
 
         <!-- Close the "turn on battery saver?" dialog, and wait for the broadcast queue to drain. -->
         <option name="teardown-command" value="am broadcast --receiver-foreground -a android.intent.action.CLOSE_SYSTEM_DIALOGS" />
diff --git a/tests/tests/voicesettings/src/android/voicesettings/cts/AirplaneModeTest.java b/tests/tests/voicesettings/src/android/voicesettings/cts/AirplaneModeTest.java
index 2ef1999..2992c5b 100644
--- a/tests/tests/voicesettings/src/android/voicesettings/cts/AirplaneModeTest.java
+++ b/tests/tests/voicesettings/src/android/voicesettings/cts/AirplaneModeTest.java
@@ -18,13 +18,15 @@
 
 import static android.provider.Settings.ACTION_VOICE_CONTROL_AIRPLANE_MODE;
 
-import com.android.compatibility.common.util.BroadcastTestBase;
-import com.android.compatibility.common.util.BroadcastUtils;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.provider.Settings;
-import android.provider.Settings.Global;
 import android.util.Log;
 
+import com.android.compatibility.common.util.BroadcastUtils;
+
+import org.junit.Test;
+
 public class AirplaneModeTest extends BroadcastTestBase {
     static final String TAG = "AirplaneModeTest";
     private static final String VOICE_SETTINGS_PACKAGE = "android.voicesettings.service";
@@ -36,17 +38,12 @@
     private static final int AIRPLANE_MODE_IS_ON = 1;
 
     @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mContext = getInstrumentation().getTargetContext();
+    protected void customSetup() throws Exception {
         mHasFeature = mContext.getPackageManager().hasSystemFeature(FEATURE_VOICE_RECOGNIZERS);
         Log.v(TAG, "setUp(): mHasFeature=" + mHasFeature);
     }
 
-    public AirplaneModeTest() {
-        super();
-    }
-
+    @Test
     public void testAll() throws Exception {
         if (!mHasFeature) {
             Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
@@ -96,7 +93,7 @@
         // verify the test results
         int mode = getMode();
         Log.i(TAG, "After testing, AIRPLANE_MODE is set to: " + mode);
-        assertEquals(expectedMode, mode);
+        assertThat(mode).isEqualTo(expectedMode);
         Log.i(TAG, "Successfully Tested: " + test);
         return true;
     }
diff --git a/tests/tests/voicesettings/src/android/voicesettings/cts/BatterySaverModeTest.java b/tests/tests/voicesettings/src/android/voicesettings/cts/BatterySaverModeTest.java
index 759d82e..181c4ba 100644
--- a/tests/tests/voicesettings/src/android/voicesettings/cts/BatterySaverModeTest.java
+++ b/tests/tests/voicesettings/src/android/voicesettings/cts/BatterySaverModeTest.java
@@ -18,13 +18,14 @@
 
 import static android.provider.Settings.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE;
 
-import com.android.compatibility.common.util.BroadcastTestBase;
-import com.android.compatibility.common.util.BroadcastUtils;
-
 import android.content.Context;
 import android.os.PowerManager;
 import android.util.Log;
 
+import com.android.compatibility.common.util.BroadcastUtils;
+
+import org.junit.Test;
+
 public class BatterySaverModeTest extends BroadcastTestBase {
     static final String TAG = "BatterySaverModeTest";
     private static final String VOICE_SETTINGS_PACKAGE = "android.voicesettings.service";
@@ -32,17 +33,12 @@
         "android.voicesettings.service.VoiceInteractionMain";
     protected static final String FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers";
 
-    public BatterySaverModeTest() {
-        super();
-    }
-
     @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mContext = getInstrumentation().getTargetContext();
+    protected void customSetup() throws Exception {
         mHasFeature = mContext.getPackageManager().hasSystemFeature(FEATURE_VOICE_RECOGNIZERS);
     }
 
+    @Test
     public void testAll() throws Exception {
         if (!mHasFeature) {
             Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/BroadcastTestBase.java b/tests/tests/voicesettings/src/android/voicesettings/cts/BroadcastTestBase.java
similarity index 66%
rename from common/device-side/util-axt/src/com/android/compatibility/common/util/BroadcastTestBase.java
rename to tests/tests/voicesettings/src/android/voicesettings/cts/BroadcastTestBase.java
index 7500050..95e9433 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/BroadcastTestBase.java
+++ b/tests/tests/voicesettings/src/android/voicesettings/cts/BroadcastTestBase.java
@@ -14,7 +14,13 @@
  * limitations under the License.
  */
 
-package com.android.compatibility.common.util;
+package android.voicesettings.cts;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.fail;
 
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
@@ -23,18 +29,31 @@
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.os.Bundle;
-import android.test.ActivityInstrumentationTestCase2;
+import android.provider.Settings;
 import android.util.Log;
 
+import androidx.test.rule.ActivityTestRule;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.compatibility.common.util.BroadcastUtils;
+import com.android.compatibility.common.util.SettingsStateChangerRule;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
-public class BroadcastTestBase extends ActivityInstrumentationTestCase2<
-                                       BroadcastTestStartActivity> {
+@RunWith(AndroidJUnit4.class)
+public abstract class BroadcastTestBase {
+
     static final String TAG = "BroadcastTestBase";
     protected static final int TIMEOUT_MS = 20 * 1000;
 
-    protected Context mContext;
+    protected final Context mContext = getInstrumentation().getTargetContext();
     protected Bundle mResultExtras;
     private CountDownLatch mLatch;
     protected ActivityDoneReceiver mActivityDoneReceiver = null;
@@ -42,20 +61,29 @@
     private BroadcastUtils.TestcaseType mTestCaseType;
     protected boolean mHasFeature;
 
-    public BroadcastTestBase() {
-        super(BroadcastTestStartActivity.class);
-    }
+    private final SettingsStateChangerRule mServiceSetterRule = new SettingsStateChangerRule(
+            mContext, Settings.Secure.VOICE_INTERACTION_SERVICE,
+            "android.voicesettings.service/.MainInteractionService");
+    private final ActivityTestRule<BroadcastTestStartActivity> mActivityTestRule =
+            new ActivityTestRule<>(BroadcastTestStartActivity.class, false, false);
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
+    @Rule
+    public final RuleChain mgRules = RuleChain
+            .outerRule(mServiceSetterRule)
+            .around(mActivityTestRule);
+
+    @Before
+    public void setUp() throws Exception {
         mHasFeature = false;
+
+        customSetup();
     }
 
-    @Override
-    protected void tearDown() throws Exception {
+    @After
+    public final void tearDown() throws Exception {
         Log.v(TAG, getClass().getSimpleName() + ".tearDown(): hasFeature=" + mHasFeature
                 + " receiver=" + mActivityDoneReceiver);
+
         if (mHasFeature && mActivityDoneReceiver != null) {
             try {
                 mContext.unregisterReceiver(mActivityDoneReceiver);
@@ -66,13 +94,18 @@
             }
             mActivityDoneReceiver = null;
         }
-        super.tearDown();
+    }
+
+    /**
+     * Test-specific setup - doesn't need to call {@code super} neither use <code>@Before</code>.
+     */
+    protected void customSetup() throws Exception {
     }
 
     protected boolean isIntentSupported(String intentStr) {
         Intent intent = new Intent(intentStr);
         final PackageManager manager = mContext.getPackageManager();
-        assertNotNull(manager);
+        assertThat(manager).isNotNull();
         if (manager.resolveActivity(intent, 0) == null) {
             Log.i(TAG, "No Activity found for the intent: " + intentStr);
             return false;
@@ -83,13 +116,12 @@
     protected void startTestActivity(String intentSuffix) {
         Intent intent = new Intent();
         intent.setAction("android.intent.action.TEST_START_ACTIVITY_" + intentSuffix);
-        intent.setComponent(new ComponentName(getInstrumentation().getContext(),
-                BroadcastTestStartActivity.class));
-        setActivityIntent(intent);
-        mActivity = getActivity();
+        intent.setComponent(new ComponentName(mContext, BroadcastTestStartActivity.class));
+        mActivity = mActivityTestRule.launchActivity(intent);
     }
 
-    protected void registerBroadcastReceiver(BroadcastUtils.TestcaseType testCaseType) throws Exception {
+    protected void registerBroadcastReceiver(BroadcastUtils.TestcaseType testCaseType)
+            throws Exception {
         mTestCaseType = testCaseType;
         mLatch = new CountDownLatch(1);
         mActivityDoneReceiver = new ActivityDoneReceiver();
@@ -98,7 +130,7 @@
     }
 
     protected boolean startTestAndWaitForBroadcast(BroadcastUtils.TestcaseType testCaseType,
-                                                   String pkg, String cls) throws Exception {
+            String pkg, String cls) throws Exception {
         Log.i(TAG, "Begin Testing: " + testCaseType);
         registerBroadcastReceiver(testCaseType);
         mActivity.startTest(testCaseType.toString(), pkg, cls);
@@ -114,7 +146,7 @@
         public void onReceive(Context context, Intent intent) {
             if (intent.getAction().equals(
                     BroadcastUtils.BROADCAST_INTENT +
-                        BroadcastTestBase.this.mTestCaseType.toString())) {
+                            BroadcastTestBase.this.mTestCaseType.toString())) {
                 Bundle extras = intent.getExtras();
                 Log.i(TAG, "received_broadcast for " + BroadcastUtils.toBundleString(extras));
                 BroadcastTestBase.this.mResultExtras = extras;
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/BroadcastTestStartActivity.java b/tests/tests/voicesettings/src/android/voicesettings/cts/BroadcastTestStartActivity.java
similarity index 95%
rename from common/device-side/util-axt/src/com/android/compatibility/common/util/BroadcastTestStartActivity.java
rename to tests/tests/voicesettings/src/android/voicesettings/cts/BroadcastTestStartActivity.java
index 4b3e85d..163c2e4 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/BroadcastTestStartActivity.java
+++ b/tests/tests/voicesettings/src/android/voicesettings/cts/BroadcastTestStartActivity.java
@@ -14,14 +14,16 @@
  * limitations under the License.
  */
 
-package com.android.compatibility.common.util;
+package android.voicesettings.cts;
 
 import android.app.Activity;
-import android.content.Intent;
 import android.content.ComponentName;
+import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 
+import com.android.compatibility.common.util.BroadcastUtils;
+
 public class BroadcastTestStartActivity extends Activity {
     static final String TAG = "BroadcastTestStartActivity";
 
diff --git a/tests/tests/voicesettings/src/android/voicesettings/cts/ZenModeTest.java b/tests/tests/voicesettings/src/android/voicesettings/cts/ZenModeTest.java
index e01f3b9..5bb2f8c 100644
--- a/tests/tests/voicesettings/src/android/voicesettings/cts/ZenModeTest.java
+++ b/tests/tests/voicesettings/src/android/voicesettings/cts/ZenModeTest.java
@@ -20,13 +20,15 @@
 import static android.provider.Settings.EXTRA_DO_NOT_DISTURB_MODE_ENABLED;
 import static android.provider.Settings.EXTRA_DO_NOT_DISTURB_MODE_MINUTES;
 
-import com.android.compatibility.common.util.BroadcastTestBase;
-import com.android.compatibility.common.util.BroadcastUtils;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.provider.Settings;
-import android.provider.Settings.Global;
 import android.util.Log;
 
+import com.android.compatibility.common.util.BroadcastUtils;
+
+import org.junit.Test;
+
 public class ZenModeTest extends BroadcastTestBase {
     static final String TAG = "ZenModeTest";
     private static final String VOICE_SETTINGS_PACKAGE = "android.voicesettings.service";
@@ -35,9 +37,7 @@
     protected static final String FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers";
 
     @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mContext = getInstrumentation().getTargetContext();
+    protected void customSetup() throws Exception {
         mHasFeature = mContext.getPackageManager().hasSystemFeature(FEATURE_VOICE_RECOGNIZERS);
     }
 
@@ -47,10 +47,7 @@
     private static final int ZEN_MODE_IS_OFF = 0;
     private static final int ZEN_MODE_IS_ALARMS = 3;
 
-    public ZenModeTest() {
-        super();
-    }
-
+    @Test
     public void testAll() throws Exception {
         if (!mHasFeature) {
             Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
@@ -99,15 +96,15 @@
         // verify the test results
         int mode = getMode();
         Log.i(TAG, "After testing, zen-mode is set to: " + mode);
-        assertEquals(expectedMode, mode);
+        assertThat(mode).isEqualTo(expectedMode);
         Log.i(TAG, "results_received: " + BroadcastUtils.toBundleString(mResultExtras));
-        assertNotNull(mResultExtras);
+        assertThat(mResultExtras).isNotNull();
         if (expectedMode == ZEN_MODE_IS_ALARMS) {
-            assertTrue(mResultExtras.getBoolean(EXTRA_DO_NOT_DISTURB_MODE_ENABLED));
-            assertEquals(BroadcastUtils.NUM_MINUTES_FOR_ZENMODE,
-                    mResultExtras.getInt(EXTRA_DO_NOT_DISTURB_MODE_MINUTES));
+            assertThat(mResultExtras.getBoolean(EXTRA_DO_NOT_DISTURB_MODE_ENABLED)).isTrue();
+            assertThat(mResultExtras.getInt(EXTRA_DO_NOT_DISTURB_MODE_MINUTES)).isEqualTo(
+                    BroadcastUtils.NUM_MINUTES_FOR_ZENMODE);
         } else {
-            assertFalse(mResultExtras.getBoolean(EXTRA_DO_NOT_DISTURB_MODE_ENABLED));
+            assertThat(mResultExtras.getBoolean(EXTRA_DO_NOT_DISTURB_MODE_ENABLED)).isFalse();
         }
         Log.i(TAG, "Successfully Tested: " + test);
         return true;
diff --git a/tests/tests/widget/Android.bp b/tests/tests/widget/Android.bp
index e8ce4c5..30d6516 100644
--- a/tests/tests/widget/Android.bp
+++ b/tests/tests/widget/Android.bp
@@ -42,7 +42,6 @@
         "cts",
         "vts",
         "general-tests",
-        "cts_instant",
     ],
 
 }
diff --git a/tests/tests/widget/AndroidTest.xml b/tests/tests/widget/AndroidTest.xml
index fd9afe8..8cd40dc 100644
--- a/tests/tests/widget/AndroidTest.xml
+++ b/tests/tests/widget/AndroidTest.xml
@@ -26,5 +26,6 @@
         <option name="package" value="android.widget.cts" />
         <option name="runtime-hint" value="11m55s" />
         <option name="hidden-api-checks" value="false" />
+        <option name="instrumentation-arg" key="thisisignored" value="thisisignored --no-window-animation" />
     </test>
 </configuration>