Merge "Snap for 5130802 from da93ef70d1fd4a1ba8eeac1ef0785395c3c2357d to pie-cts-release" into pie-cts-release
diff --git a/apps/CameraITS/pymodules/its/cv2image.py b/apps/CameraITS/pymodules/its/cv2image.py
index 21804e9..2004846 100644
--- a/apps/CameraITS/pymodules/its/cv2image.py
+++ b/apps/CameraITS/pymodules/its/cv2image.py
@@ -51,7 +51,7 @@
     """
 
     def __init__(self, chart_file, height, distance, scale_start, scale_stop,
-                 scale_step):
+                 scale_step, camera_id=None):
         """Initial constructor for class.
 
         Args:
@@ -61,6 +61,7 @@
             scale_start:    float; start value for scaling for chart search
             scale_stop:     float; stop value for scaling for chart search
             scale_step:     float; step value for scaling for chart search
+            camera_id:      int; camera used for extractor
         """
         self._file = chart_file
         self._height = height
@@ -70,7 +71,7 @@
         self._scale_step = scale_step
         self.xnorm, self.ynorm, self.wnorm, self.hnorm, self.scale = its.image.chart_located_per_argv()
         if not self.xnorm:
-            with its.device.ItsSession() as cam:
+            with its.device.ItsSession(camera_id) as cam:
                 props = cam.get_camera_properties()
                 if its.caps.read_3a(props):
                     self.locate(cam, props)
diff --git a/apps/CameraITS/pymodules/its/device.py b/apps/CameraITS/pymodules/its/device.py
index 1c3c2c1..8b02230 100644
--- a/apps/CameraITS/pymodules/its/device.py
+++ b/apps/CameraITS/pymodules/its/device.py
@@ -216,6 +216,9 @@
                 break
         proc.kill()
 
+    def __init__(self, camera_id=None):
+        self._camera_id = camera_id
+
     def __enter__(self):
         # Initialize device id and adb command.
         self.device_id = get_device_id()
@@ -225,7 +228,7 @@
         self.__init_socket_port()
 
         self.__close_camera()
-        self.__open_camera()
+        self.__open_camera(self._camera_id)
         return self
 
     def __exit__(self, type, value, traceback):
@@ -258,12 +261,17 @@
             buf = numpy.frombuffer(buf, dtype=numpy.uint8)
         return jobj, buf
 
-    def __open_camera(self):
-        # Get the camera ID to open as an argument.
-        camera_id = 0
-        for s in sys.argv[1:]:
-            if s[:7] == "camera=" and len(s) > 7:
-                camera_id = int(s[7:])
+    def __open_camera(self, camera_id):
+        # Get the camera ID to open if it is an argument as a single camera.
+        # This allows passing camera=# to individual tests at command line
+        # and camera=#,#,# or an no camera argv with tools/run_all_tests.py.
+        if not camera_id:
+            camera_id = 0
+            for s in sys.argv[1:]:
+                if s[:7] == "camera=" and len(s) > 7:
+                    camera_ids = s[7:].split(",")
+                    if len(camera_ids) == 1:
+                        camera_id = camera_ids[0]
         cmd = {"cmdName":"open", "cameraId":camera_id}
         self.sock.send(json.dumps(cmd) + "\n")
         data,_ = self.__read_response_from_socket()
diff --git a/apps/CameraITS/tests/scene0/test_gyro_bias.py b/apps/CameraITS/tests/scene0/test_gyro_bias.py
index 86445fe..44be95f 100644
--- a/apps/CameraITS/tests/scene0/test_gyro_bias.py
+++ b/apps/CameraITS/tests/scene0/test_gyro_bias.py
@@ -39,7 +39,8 @@
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
         # Only run test if the appropriate caps are claimed.
-        its.caps.skip_unless(its.caps.sensor_fusion(props))
+        its.caps.skip_unless(its.caps.sensor_fusion(props) and
+            cam.get_sensors().get("gyro"))
 
         print "Collecting gyro events"
         cam.start_sensor_events()
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index bc00d5f..265fc33 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -430,7 +430,8 @@
         props = cam.get_camera_properties()
         its.caps.skip_unless(its.caps.sensor_fusion(props) and
                              its.caps.manual_sensor(props) and
-                             props["android.lens.facing"] != FACING_EXTERNAL)
+                             props["android.lens.facing"] != FACING_EXTERNAL and
+                             cam.get_sensors().get("gyro"))
 
         print "Starting sensor event collection"
         cam.start_sensor_events()
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index a6e0402..4cc0151 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -73,9 +73,9 @@
 }
 
 
-def calc_camera_fov():
+def calc_camera_fov(camera_id):
     """Determine the camera field of view from internal params."""
-    with ItsSession() as cam:
+    with ItsSession(camera_id) as cam:
         props = cam.get_camera_properties()
     try:
         focal_l = props['android.lens.info.availableFocalLengths'][0]
@@ -101,11 +101,11 @@
     return socket_fail
 
 
-def skip_sensor_fusion():
+def skip_sensor_fusion(camera_id):
     """Determine if sensor fusion test is skipped for this camera."""
 
     skip_code = SKIP_RET_CODE
-    with ItsSession() as cam:
+    with ItsSession(camera_id) as cam:
         props = cam.get_camera_properties()
         if (its.caps.sensor_fusion(props) and its.caps.manual_sensor(props) and
                 props['android.lens.facing'] is not FACING_EXTERNAL):
@@ -174,7 +174,6 @@
     tmp_dir = None
     skip_scene_validation = False
     chart_distance = CHART_DISTANCE
-    chart_height = CHART_HEIGHT
 
     for s in sys.argv[1:]:
         if s[:7] == "camera=" and len(s) > 7:
@@ -277,7 +276,7 @@
             assert wake_code == 0
 
     for camera_id in camera_ids:
-        camera_fov = calc_camera_fov()
+        camera_fov = calc_camera_fov(camera_id)
         # Loop capturing images until user confirm test scene is correct
         camera_id_arg = "camera=" + camera_id
         print "Preparing to run ITS on camera", camera_id
@@ -303,7 +302,7 @@
                 out_path = os.path.join(topdir, camera_id, scene+".jpg")
                 out_arg = "out=" + out_path
                 if scene == 'sensor_fusion':
-                    skip_code = skip_sensor_fusion()
+                    skip_code = skip_sensor_fusion(camera_id)
                     if rot_rig_id or skip_code == SKIP_RET_CODE:
                         validate_switch = False
                 if skip_scene_validation:
@@ -335,13 +334,15 @@
             print "Start running ITS on camera %s, %s" % (camera_id, scene)
             # Extract chart from scene for scene3 once up front
             chart_loc_arg = ''
+            chart_height = CHART_HEIGHT
             if scene == 'scene3':
                 if float(camera_fov) < 90 and np.isclose(chart_distance, 22,
                                                          rtol=0.1):
                     chart_height *= 0.67
                 chart = its.cv2image.Chart(SCENE3_FILE, chart_height,
                                            chart_distance, CHART_SCALE_START,
-                                           CHART_SCALE_STOP, CHART_SCALE_STEP)
+                                           CHART_SCALE_STOP, CHART_SCALE_STEP,
+                                           camera_id)
                 chart_loc_arg = 'chart_loc=%.2f,%.2f,%.2f,%.2f,%.3f' % (
                         chart.xnorm, chart.ynorm, chart.wnorm, chart.hnorm,
                         chart.scale)
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 933fdab..20b4a40 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.cts.verifier"
       android:versionCode="5"
-      android:versionName="9.0_r4">
+      android:versionName="9.0_r5">
 
     <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28"/>
 
@@ -2006,7 +2006,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_notifications" />
             <meta-data android:name="test_excluded_features"
-                android:value="android.hardware.type.watch:android.software.leanback" />
+                android:value="android.hardware.type.watch:android.software.leanback:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".vr.VrListenerVerifierActivity"
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
index e5b73e8..fdb57fc 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
@@ -118,7 +118,8 @@
         tests.add(new TestVibrateNotificationDndOn());
         tests.add(new TestVibrateRingerDndOn());
         tests.add(new TestSetRingerModePolicyAccessDndOn());
-        tests.add(new TestVolumeDndAffectedStreamDndOn());
+        // TODO: Add a @TestApi method to query the VolumPolicy
+        //tests.add(new TestVolumeDndAffectedStreamDndOn());
         tests.add(new TestAdjustVolumeInPriorityOnlyAllowAlarmsMediaMode());
 
         tests.add(new SetModeAllTest());
@@ -126,7 +127,8 @@
         tests.add(new TestVibrateNotification());
         tests.add(new TestVibrateRinger());
         tests.add(new TestSetRingerModePolicyAccess());
-        tests.add(new TestVolumeDndAffectedStream());
+        // TODO: Add a @TestApi method to query the VolumPolicy
+        //tests.add(new TestVolumeDndAffectedStream());
         tests.add(new TestVolume());
         tests.add(new TestMuteStreams());
         tests.add(new EnableSoundEffects());
@@ -632,17 +634,12 @@
                 return;
             }
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
             if (mHasVibrator) {
+                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
                 if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
                     setFailed();
                     return;
                 }
-            } else {
-                if (RINGER_MODE_NORMAL != mAudioManager.getRingerMode()) {
-                    setFailed();
-                    return;
-                }
             }
             status = PASS;
         }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
index e8cf2ef..fc2374e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
@@ -1728,6 +1728,14 @@
                                               .left;
                             int aay = ItsUtils.getActiveArrayCropRegion(mCameraCharacteristics)
                                               .top;
+
+                            if (w == aaw) {
+                                aax = 0;
+                            }
+                            if (h == aah) {
+                                aay = 0;
+                            }
+
                             int gw = mCaptureStatsGridWidth;
                             int gh = mCaptureStatsGridHeight;
                             float[] stats = StatsImage.computeStatsImage(
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java
index 49b34fd..d753d6a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java
@@ -465,6 +465,10 @@
                 int viewHeight = mFormatView.getHeight();
                 int newWidth, newHeight;
 
+                if (viewWidth == 0 || viewHeight == 0){
+                    return;
+                }
+
                 if (mPreviewOrientations.get(mNextPreviewOrientation) == 0
                     || mPreviewOrientations.get(mNextPreviewOrientation) == 180) {
                     // make preview width same as output image width,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
index 5f90b66..67f82d0 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -647,12 +647,14 @@
                     .show();
         }
 
-        mWidgetTest = TestListItem.newTest(this,
-                R.string.provisioning_byod_work_profile_widget,
-                WorkProfileWidgetActivity.class.getName(),
-                new Intent(WorkProfileWidgetActivity.ACTION_TEST_WORK_PROFILE_WIDGET),
-                new String[] {PackageManager.FEATURE_APP_WIDGETS});
-        adapter.add(mWidgetTest);
+        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)) {
+            mWidgetTest = TestListItem.newTest(this,
+                    R.string.provisioning_byod_work_profile_widget,
+                    WorkProfileWidgetActivity.class.getName(),
+                    new Intent(WorkProfileWidgetActivity.ACTION_TEST_WORK_PROFILE_WIDGET),
+                    new String[]{PackageManager.FEATURE_APP_WIDGETS});
+            adapter.add(mWidgetTest);
+        }
 
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java
index b04ec47..82612f7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java
@@ -36,6 +36,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
 import android.database.DataSetObserver;
 import android.os.AsyncTask;
 import android.os.Bundle;
@@ -125,47 +126,57 @@
     }
 
     private void addTestsToAdapter(final ArrayTestListAdapter adapter) {
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_DEFAULT,
-                LOCK_TASK_FEATURE_NONE,
-                R.string.device_owner_lock_task_ui_default_test,
-                R.string.device_owner_lock_task_ui_default_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_DEFAULT,
+                    LOCK_TASK_FEATURE_NONE,
+                    R.string.device_owner_lock_task_ui_default_test,
+                    R.string.device_owner_lock_task_ui_default_test_info));
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_SYSTEM_INFO,
-                LOCK_TASK_FEATURE_SYSTEM_INFO,
-                R.string.device_owner_lock_task_ui_system_info_test,
-                R.string.device_owner_lock_task_ui_system_info_test_info));
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_SYSTEM_INFO,
+                    LOCK_TASK_FEATURE_SYSTEM_INFO,
+                    R.string.device_owner_lock_task_ui_system_info_test,
+                    R.string.device_owner_lock_task_ui_system_info_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_NOTIFICATIONS,
-                LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_NOTIFICATIONS,
-                R.string.device_owner_lock_task_ui_notifications_test,
-                R.string.device_owner_lock_task_ui_notifications_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_NOTIFICATIONS,
+                    LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_NOTIFICATIONS,
+                    R.string.device_owner_lock_task_ui_notifications_test,
+                    R.string.device_owner_lock_task_ui_notifications_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_HOME,
-                LOCK_TASK_FEATURE_HOME,
-                R.string.device_owner_lock_task_ui_home_test,
-                R.string.device_owner_lock_task_ui_home_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_HOME,
+                    LOCK_TASK_FEATURE_HOME,
+                    R.string.device_owner_lock_task_ui_home_test,
+                    R.string.device_owner_lock_task_ui_home_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_RECENTS,
-                LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_OVERVIEW,
-                R.string.device_owner_lock_task_ui_recents_test,
-                R.string.device_owner_lock_task_ui_recents_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_RECENTS,
+                    LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_OVERVIEW,
+                    R.string.device_owner_lock_task_ui_recents_test,
+                    R.string.device_owner_lock_task_ui_recents_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_GLOBAL_ACTIONS,
-                LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
-                R.string.device_owner_lock_task_ui_global_actions_test,
-                R.string.device_owner_lock_task_ui_global_actions_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_GLOBAL_ACTIONS,
+                    LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
+                    R.string.device_owner_lock_task_ui_global_actions_test,
+                    R.string.device_owner_lock_task_ui_global_actions_test_info));
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_KEYGUARD,
-                LOCK_TASK_FEATURE_KEYGUARD,
-                R.string.device_owner_lock_task_ui_keyguard_test,
-                R.string.device_owner_lock_task_ui_keyguard_test_info));
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_KEYGUARD,
+                    LOCK_TASK_FEATURE_KEYGUARD,
+                    R.string.device_owner_lock_task_ui_keyguard_test,
+                    R.string.device_owner_lock_task_ui_keyguard_test_info));
+        }
 
         final Intent stopLockTaskIntent = new Intent(this, LockTaskUiTestActivity.class);
         stopLockTaskIntent.setAction(ACTION_STOP_LOCK_TASK);
diff --git a/apps/VpnApp/notalwayson/AndroidManifest.xml b/apps/VpnApp/notalwayson/AndroidManifest.xml
index 58d2bf9..b356369 100644
--- a/apps/VpnApp/notalwayson/AndroidManifest.xml
+++ b/apps/VpnApp/notalwayson/AndroidManifest.xml
@@ -19,6 +19,7 @@
 
     <uses-sdk android:minSdkVersion="22"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
 
     <application android:label="@string/app">
         <activity android:name=".VpnClient">
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
index a49e949..943ebc7 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
@@ -46,7 +46,7 @@
     }
 
     public static boolean isAtLeast(String version) {
-        return Build.VERSION.SDK_INT > resolveVersionString(version);
+        return Build.VERSION.SDK_INT >= resolveVersionString(version);
     }
 
     public static boolean isAtMost(int version) {
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java b/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java
index a1adc02..eb94b60 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java
@@ -59,7 +59,8 @@
     public static boolean isAppStandbyEnabledAtRuntime() {
         final String result =
                 SystemUtil.runShellCommand("settings get global app_standby_enabled").trim();
-        final boolean boolResult = result.equals("1");
+        // framework considers null value as enabled.
+        final boolean boolResult = result.equals("1") || result.equals("null");
         Log.d(TAG, "AppStandby is " + (boolResult ? "enabled" : "disabled") + " at runtime.");
         return boolResult;
     }
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
index 130bf69..7d7aaf0 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
@@ -17,6 +17,7 @@
 package com.android.compatibility.common.util;
 
 import android.content.Context;
+import android.text.TextUtils;
 import android.util.Log;
 
 import java.lang.reflect.Method;
@@ -56,6 +57,22 @@
      * {@inheritDoc}
      */
     @Override
+    public void logDebug(String format, Object... args) {
+        Log.d(LOG_TAG, String.format(format, args));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected String formatExecutionString(String method, String... args) {
+        return String.format("%s(%s)", method, TextUtils.join(", ", args));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
     protected ResolvedMethod getResolvedMethod(Class cls, String methodName, String... args)
             throws ClassNotFoundException {
         List<Method> nameMatches = getMethodsWithName(cls, methodName);
diff --git a/hostsidetests/api/Android.mk b/hostsidetests/api/Android.mk
deleted file mode 100644
index ec9a337..0000000
--- a/hostsidetests/api/Android.mk
+++ /dev/null
@@ -1,48 +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 := CtsUnofficialApisUsageTestCases
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_SDK_VERSION := current
-LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
-LOCAL_STATIC_JAVA_LIBRARIES := dexlib2 doclava jsilver guavalib antlr-runtime host-jdk-tools-prebuilt \
-    compatibility-host-util
-
-# These are list of api txt files that are considered as approved APIs
-LOCAL_JAVA_RESOURCE_FILES := $(addprefix frameworks/base/,\
-api/current.txt \
-api/system-current.txt \
-test-base/api/android-test-base-current.txt \
-test-runner/api/android-test-runner-current.txt \
-test-mock/api/android-test-mock-current.txt)
-
-# API 27 is added since some support libraries are using old APIs
-LOCAL_JAVA_RESOURCE_FILES += prebuilts/sdk/api/27.txt
-
-# org.apache.http.legacy is considered as approved APIs
-LOCAL_JAVA_RESOURCE_FILES += external/apache-http/api/apache-http-legacy-current.txt
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE_TAGS := optional
-LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := host-jdk-tools-prebuilt:../../../$(HOST_JDK_TOOLS_JAR)
-include $(BUILD_HOST_PREBUILT)
diff --git a/hostsidetests/api/AndroidTest.xml b/hostsidetests/api/AndroidTest.xml
deleted file mode 100644
index df163b0..0000000
--- a/hostsidetests/api/AndroidTest.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?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.
--->
-<configuration description="Config for CTS unofficial APIs usage test cases">
-    <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="systems" />
-    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
-      <option name="jar" value="CtsUnofficialApisUsageTestCases.jar" />
-      <option name="runtime-hint" value="30s" />
-    </test>
-</configuration>
diff --git a/hostsidetests/api/src/com/android/cts/api/ApprovedApis.java b/hostsidetests/api/src/com/android/cts/api/ApprovedApis.java
deleted file mode 100644
index c68fe91..0000000
--- a/hostsidetests/api/src/com/android/cts/api/ApprovedApis.java
+++ /dev/null
@@ -1,225 +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.cts.api;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringJoiner;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import com.google.doclava.ClassInfo;
-import com.google.doclava.FieldInfo;
-import com.google.doclava.MethodInfo;
-import com.google.doclava.ParameterInfo;
-import com.google.doclava.TypeInfo;
-import com.google.doclava.apicheck.ApiFile;
-import com.google.doclava.apicheck.ApiInfo;
-import com.google.doclava.apicheck.ApiParseException;
-
-/**
- * Parses API text files (e.g. current.txt) into classes, methods, and fields.
- */
-public class ApprovedApis {
-    private final Map<String, DefinedClass> definedApiClasses = new HashMap<>();
-    private final Map<String, DefinedMethod> definedApiMethods = new HashMap<>();
-    private final Map<String, DefinedField> definedApiFields = new HashMap<>();
-
-    public ApprovedApis(Stream<File> apiFiles) {
-        apiFiles.forEach(file -> parse(file));
-
-        // build the maps for methods and fields
-        definedApiMethods.putAll(definedApiClasses.values().stream()
-                .flatMap(c -> c.getMethods().stream()) // all methods from all classes
-                .collect(Collectors.toMap(DefinedMethod::getFullSignature,
-                        Function.identity()))); // map by their full signatures
-
-        definedApiFields.putAll(definedApiClasses.values().stream()
-                .flatMap(c -> c.getFields().stream()) // all fields from all classes
-                .collect(Collectors.toMap(DefinedField::getFullSignature,
-                        Function.identity()))); // map by their full signatures
-
-        if (UnofficialApisUsageTest.DEBUG) {
-            System.err.println("-------------------API------------------");
-
-            definedApiClasses.values().stream().sorted()
-                    .forEach(def -> System.err.println(" Defined class: " + def.getName()));
-
-            definedApiMethods.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined method: " + def.getFullSignature()));
-
-            definedApiFields.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined field: " + def.getFullSignature()));
-        }
-    }
-
-    public Map<String, DefinedClass> getDefinedClasses() {
-        return definedApiClasses;
-    }
-
-    public Map<String, DefinedMethod> getDefinedMethods() {
-        return definedApiMethods;
-    }
-
-    public Map<String, DefinedField> getDefinedFields() {
-        return definedApiFields;
-    }
-
-    private void parse(File apiFile) {
-        try {
-            InputStream is = null;
-            try {
-                is = this.getClass().getResourceAsStream(apiFile.toString());
-                ApiInfo apiInfo = ApiFile.parseApi(apiFile.toString(), is);
-                apiInfo.getPackages().values().stream()
-                        .flatMap(packageInfo -> packageInfo.allClasses().values().stream())
-                        .forEach(classInfo -> {
-                            DefinedClass c = definedApiClasses.get(classInfo.qualifiedName());
-                            if (c != null) {
-                                // if the same class has already been defined by other api file,
-                                // then update it
-                                DefinedClass newClass = definedClassFrom(classInfo);
-                                c.addNewMembers(newClass.getMethods(), newClass.getFields());
-                            } else {
-                                c = definedClassFrom(classInfo);
-                                definedApiClasses.put(c.getName(), c);
-                            }
-                        });
-
-            } finally {
-                if (is != null) {
-                    is.close();
-                }
-            }
-        } catch (ApiParseException | IOException e) {
-            throw new RuntimeException("Failed to parse " + apiFile, e);
-        }
-    }
-
-    private static DefinedClass definedClassFrom(ClassInfo def) {
-        String name = def.qualifiedName();
-        String superClassName = def.superclassName();
-        Collection<String> interfaces = def.interfaces().stream().map(ClassInfo::qualifiedName)
-                .collect(Collectors.toList());
-
-        Collection<DefinedMethod> methods = new ArrayList<>(
-                def.allConstructors().size() + def.selfMethods().size());
-        Collection<DefinedField> fields = new ArrayList<>(
-                def.enumConstants().size() + def.selfFields().size());
-
-        methods = Stream.concat(
-                def.allConstructors().stream().map(ApprovedApis::definedMethodFromConstructor),
-                def.selfMethods().stream().map(ApprovedApis::definedMethodFromMethod))
-                .collect(Collectors.toSet());
-
-        fields = Stream.concat(def.enumConstants().stream(), def.selfFields().stream())
-                .map(ApprovedApis::definedFieldFrom).collect(Collectors.toSet());
-
-        return new DefinedClass(name, superClassName, interfaces, methods, fields);
-    }
-
-    private static DefinedMethod definedMethodFromConstructor(MethodInfo def) {
-        return definedMethodFrom(def, true);
-    }
-
-    private static DefinedMethod definedMethodFromMethod(MethodInfo def) {
-        return definedMethodFrom(def, false);
-    }
-
-    private static DefinedMethod definedMethodFrom(MethodInfo def, boolean isCtor) {
-        StringBuffer sb = new StringBuffer();
-        if (isCtor) {
-            sb.append("<init>");
-        } else {
-            sb.append(def.name());
-        }
-        sb.append('(');
-        StringJoiner joiner = new StringJoiner(",");
-        for (int i = 0; i < def.parameters().size(); i++) {
-            ParameterInfo param = def.parameters().get(i);
-            TypeInfo type = param.type();
-            TypeInfo typeParameterType = def.getTypeParameter(type.qualifiedTypeName());
-            String typeName;
-            if (typeParameterType != null) {
-                List<TypeInfo> bounds = typeParameterType.extendsBounds();
-                if (bounds == null || bounds.size() == 0) {
-                    typeName = "java.lang.Object" + type.dimension();
-                } else {
-                    typeName = bounds.get(0).qualifiedTypeName() + type.dimension();
-                }
-            } else {
-                typeName = type.qualifiedTypeName() + type.dimension();
-            }
-            if (i == def.parameters().size() - 1 && def.isVarArgs()) {
-                typeName += "[]";
-            }
-            joiner.add(typeName);
-        }
-        sb.append(joiner.toString());
-        sb.append(')');
-        if (!isCtor) {
-            TypeInfo type = def.returnType();
-            TypeInfo typeParameterType = def.getTypeParameter(type.qualifiedTypeName());
-            if (typeParameterType != null) {
-                List<TypeInfo> bounds = typeParameterType.extendsBounds();
-                if (bounds == null || bounds.size() != 1) {
-                    sb.append("java.lang.Object" + type.dimension());
-                } else {
-                    sb.append(bounds.get(0).qualifiedTypeName() + type.dimension());
-                }
-            } else {
-                sb.append(type.qualifiedTypeName() + type.dimension());
-            }
-        }
-
-        String signature = sb.toString();
-        String containingClass = def.containingClass().qualifiedName();
-        return new DefinedMethod(signature, containingClass);
-    }
-
-    private static DefinedField definedFieldFrom(FieldInfo def) {
-        StringBuffer sb = new StringBuffer(def.name());
-        sb.append(":");
-
-        TypeInfo type = def.type();
-        TypeInfo typeParameterType = def.containingClass()
-                .getTypeParameter(type.qualifiedTypeName());
-        if (typeParameterType != null) {
-            List<TypeInfo> bounds = typeParameterType.extendsBounds();
-            if (bounds == null || bounds.size() != 1) {
-                sb.append("java.lang.Object" + type.dimension());
-            } else {
-                sb.append(bounds.get(0).qualifiedTypeName() + type.dimension());
-            }
-        } else {
-            sb.append(type.qualifiedTypeName() + type.dimension());
-        }
-
-        String signature = sb.toString();
-        String containingClass = def.containingClass().qualifiedName();
-        return new DefinedField(signature, containingClass);
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DefinedClass.java b/hostsidetests/api/src/com/android/cts/api/DefinedClass.java
deleted file mode 100644
index e4adc71..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DefinedClass.java
+++ /dev/null
@@ -1,111 +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.cts.api;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.stream.Collectors;
-
-/**
- * A class defined in a DEX or in an API file
- */
-public final class DefinedClass implements Comparable<DefinedClass> {
-    private final String name;
-    private final String superClassName;
-    private final Collection<String> interfaceNames;
-    private final Collection<DefinedMethod> methods;
-    private final Collection<DefinedField> fields;
-    private final Collection<String> methodSignatures;
-    private final Collection<String> fieldSignatures;
-
-    DefinedClass(String name, String superClassName, Collection<String> interfaceNames,
-            Collection<DefinedMethod> methods, Collection<DefinedField> fields) {
-        this.name = name;
-        this.superClassName = superClassName;
-        this.interfaceNames = interfaceNames;
-        // these are Set instead of List to eliminate duplication from multiple api files
-        this.methods = new HashSet<>();
-        this.fields = new HashSet<>();
-
-        // signatures is okay to be list because they are always re-generated
-        // in addMembersFrom
-        this.methodSignatures = new ArrayList<>();
-        this.fieldSignatures = new ArrayList<>();
-
-        addNewMembers(methods, fields);
-    }
-
-    void addNewMembers(Collection<DefinedMethod> newMethods, Collection<DefinedField> newFields) {
-        methods.addAll(newMethods);
-        fields.addAll(newFields);
-
-        // re-generate the signatures list
-        methodSignatures.clear();
-        methodSignatures.addAll(methods.stream()
-                .map(DefinedMethod::getSignature)
-                .collect(Collectors.toList()));
-
-        fieldSignatures.clear();
-        fieldSignatures.addAll(fields.stream()
-                .map(DefinedField::getSignature)
-                .collect(Collectors.toList()));
-    }
-
-    /**
-     * Returns canonical name of a class
-     */
-    public String getName() {
-        return name;
-    }
-
-    String getSuperClass() {
-        return superClassName;
-    }
-
-    Collection<String> getInterfaces() {
-        return interfaceNames;
-    }
-
-    Collection<DefinedMethod> getMethods() {
-        return methods;
-    }
-
-    Collection<DefinedField> getFields() {
-        return fields;
-    }
-
-    Collection<String> getMethodSignatures() {
-        return methodSignatures;
-    }
-
-    Collection<String> getFieldSignatures() {
-        return fieldSignatures;
-    }
-
-    boolean isEnum() {
-        return getSuperClass().equals("java.lang.Enum");
-    }
-
-    @Override
-    public int compareTo(DefinedClass o) {
-        if (o != null) {
-            return getName().compareTo(o.getName());
-        }
-        return 0;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DefinedField.java b/hostsidetests/api/src/com/android/cts/api/DefinedField.java
deleted file mode 100644
index 0fe1796..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DefinedField.java
+++ /dev/null
@@ -1,73 +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.cts.api;
-
-/**
- * A field or enum constant defined in a DEX or in an API file
- */
-public final class DefinedField implements Comparable<DefinedField> {
-    private final String signature;
-    private final String definingClass;
-
-    DefinedField(String signature, String definingClass) {
-        this.signature = signature;
-        this.definingClass = definingClass;
-    }
-
-    /**
-     * Returns name:type
-     */
-    String getSignature() {
-        return signature;
-    }
-
-    /**
-     * Returns class.name:type
-     */
-    public String getFullSignature() {
-        return getDefiningClass() + "." + getSignature();
-    }
-
-    String getDefiningClass() {
-        return definingClass;
-    }
-
-    @Override
-    public int compareTo(DefinedField o) {
-        if (o != null) {
-            return getFullSignature().compareTo(o.getFullSignature());
-        }
-        return 0;
-    }
-
-    @Override
-    public int hashCode() {
-        return getFullSignature().hashCode();
-    }
-
-    /**
-     * Fields are fully identified by their full signature. Two fields with same signature are
-     * considered to be the same.
-     */
-    @Override
-    public boolean equals(Object o) {
-        if (o != null && o instanceof DefinedField) {
-            return getFullSignature().equals(((DefinedField) o).getFullSignature());
-        }
-        return false;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DefinedMethod.java b/hostsidetests/api/src/com/android/cts/api/DefinedMethod.java
deleted file mode 100644
index 9d78157..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DefinedMethod.java
+++ /dev/null
@@ -1,73 +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.cts.api;
-
-/**
- * A method or constructor defined in a DEX or in an API file
- */
-public final class DefinedMethod implements Comparable<DefinedMethod> {
-    private final String signature;
-    private final String definingClass;
-
-    DefinedMethod(String signature, String definingClass) {
-        this.signature = signature;
-        this.definingClass = definingClass;
-    }
-
-    /**
-     * Returns name(arg1,arg2,...)type. For constructor, name is <init> and type is empty.
-     */
-    String getSignature() {
-        return signature;
-    }
-
-    /**
-     * Returns class.name(arg1,arg2,...)type. For constructor, name is <init> and type is empty.
-     */
-    public String getFullSignature() {
-        return getDefiningClass() + "." + getSignature();
-    }
-
-    String getDefiningClass() {
-        return definingClass;
-    }
-
-    @Override
-    public int compareTo(DefinedMethod o) {
-        if (o != null) {
-            return getFullSignature().compareTo(o.getFullSignature());
-        }
-        return 0;
-    }
-
-    @Override
-    public int hashCode() {
-        return getFullSignature().hashCode();
-    }
-
-    /**
-     * Methods are fully identified by their full signature. Two methods with same signature are
-     * considered to be the same.
-     */
-    @Override
-    public boolean equals(Object o) {
-        if (o != null && o instanceof DefinedMethod) {
-            return getFullSignature().equals(((DefinedMethod) o).getFullSignature());
-        }
-        return false;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DexAnalyzer.java b/hostsidetests/api/src/com/android/cts/api/DexAnalyzer.java
deleted file mode 100644
index d2d9ade..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DexAnalyzer.java
+++ /dev/null
@@ -1,560 +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.cts.api;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringJoiner;
-import java.util.function.Function;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
-
-import org.jf.dexlib2.DexFileFactory;
-import org.jf.dexlib2.DexFileFactory.DexFileNotFoundException;
-import org.jf.dexlib2.Opcodes;
-import org.jf.dexlib2.ReferenceType;
-import org.jf.dexlib2.dexbacked.DexBackedClassDef;
-import org.jf.dexlib2.dexbacked.DexBackedDexFile;
-import org.jf.dexlib2.dexbacked.DexBackedField;
-import org.jf.dexlib2.dexbacked.DexBackedMethod;
-import org.jf.dexlib2.dexbacked.reference.DexBackedFieldReference;
-import org.jf.dexlib2.dexbacked.reference.DexBackedMethodReference;
-import org.jf.dexlib2.dexbacked.reference.DexBackedTypeReference;
-
-public class DexAnalyzer {
-    private static Map<Character, String> primitiveTypes = new HashMap<>();
-    static {
-        primitiveTypes.put('Z', "boolean");
-        primitiveTypes.put('B', "byte");
-        primitiveTypes.put('C', "char");
-        primitiveTypes.put('S', "short");
-        primitiveTypes.put('I', "int");
-        primitiveTypes.put('J', "long");
-        primitiveTypes.put('F', "float");
-        primitiveTypes.put('D', "double");
-        primitiveTypes.put('V', "void");
-    }
-
-    // [[Lcom/foo/bar/MyClass$Inner; becomes
-    // com.foo.bar.MyClass.Inner[][]
-    // and [[I becomes int[][]
-    private static String toCanonicalName(String name) {
-        int arrayDepth = 0;
-        for (int i = 0; i < name.length(); i++) {
-            if (name.charAt(i) == '[') {
-                arrayDepth++;
-            } else {
-                break;
-            }
-        }
-
-        // test the first character.
-        final char firstChar = name.charAt(arrayDepth);
-        if (primitiveTypes.containsKey(firstChar)) {
-            name = primitiveTypes.get(firstChar);
-        } else if (firstChar == 'L') {
-            // omit the leading 'L' and the trailing ';'
-            name = name.substring(arrayDepth + 1, name.length() - 1);
-
-            // replace '/' and '$' to '.'
-            name = name.replace('/', '.').replace('$', '.');
-        } else {
-            throw new RuntimeException("Invalid type name " + name);
-        }
-
-        // add []'s, if any
-        if (arrayDepth > 0) {
-            for (int i = 0; i < arrayDepth; i++) {
-                name += "[]";
-            }
-        }
-        return name;
-    }
-
-    public static abstract class Ref {
-        private final List<String> fromList; // list of files that this reference was found
-
-        protected Ref(String from) {
-            fromList = new ArrayList<>();
-            fromList.add(from);
-        }
-
-        void merge(Ref other) {
-            this.fromList.addAll(other.fromList);
-        }
-
-        String printReferencedFrom() {
-            StringJoiner joiner = new StringJoiner(", ");
-            fromList.stream().forEach(name -> joiner.add(name));
-            return joiner.toString();
-        }
-    }
-
-    public static class TypeRef extends Ref implements Comparable<TypeRef> {
-        private final DexBackedTypeReference ref;
-        private final String name;
-
-        TypeRef(DexBackedTypeReference ref, String from) {
-            super(from);
-            this.ref = ref;
-            name = toCanonicalName(ref.getType());
-        }
-
-        String getName() {
-            return name;
-        }
-
-        boolean isArray() {
-            return ref.getType().charAt(0) == '[';
-        }
-
-        boolean isPrimitiveType() {
-            String name = ref.getType();
-            if (name.length() == 1) {
-                return primitiveTypes.containsKey(name.charAt(0));
-            } else if (name.charAt(0) == '[') {
-                return primitiveTypes.containsKey(name.replaceAll("\\[+", "").charAt(0));
-            }
-            return false;
-        }
-
-        @Override
-        public int compareTo(TypeRef o) {
-            if (o != null) {
-                return getName().compareTo(o.getName());
-            }
-            return 0;
-        }
-    }
-
-    // common parent class for MethodRef and FieldRef
-    public static abstract class MemberRef extends Ref implements Comparable<MemberRef> {
-        private final String signature;
-        private String definingClass;
-
-        protected MemberRef(String signature, String initialDefiningClass, String from) {
-            super(from);
-            this.signature = signature;
-            // This might be incorrect since DexBacked[Method|Field]Reference.getDefiningClass()
-            // only returns the type name of the target object. For example,
-            //
-            // class Super { void foo() {...} }
-            // class Child extends Super { }
-            // Child obj = new Child();
-            // obj.foo();
-            //
-            // then method reference for `obj.foo()` is `Child.foo()` since obj is declared as type
-            // Child. The true defining class is somewhere in the type hierarchy, which is Super
-            // in this case.
-            definingClass = initialDefiningClass;
-        }
-
-        String getSignature() {
-            return signature;
-        }
-
-        String getDefiningClass() {
-            return definingClass;
-        }
-
-        void setDefiningClass(String name) {
-            definingClass = name;
-        }
-
-        String getFullSignature() {
-            return getDefiningClass() + "." + getSignature();
-        }
-
-        @Override
-        public int compareTo(MemberRef o) {
-            if (o != null) {
-                return getFullSignature().compareTo(o.getFullSignature());
-            }
-            return 0;
-        }
-    }
-
-    public static class MethodRef extends MemberRef {
-        private final boolean isConstructor;
-
-        MethodRef(DexBackedMethodReference ref, String from) {
-            super(makeSignature(ref), toCanonicalName(ref.getDefiningClass()), from);
-            isConstructor = ref.getName().equals("<init>");
-        }
-
-        private static String makeSignature(DexBackedMethodReference ref) {
-            StringBuffer sb = new StringBuffer();
-            sb.append(ref.getName());
-            sb.append('(');
-            StringJoiner joiner = new StringJoiner(",");
-            for (String param : ref.getParameterTypes()) {
-                joiner.add(toCanonicalName(param));
-            }
-            sb.append(joiner.toString());
-            sb.append(')');
-            if (!ref.getName().equals("<init>")) {
-                sb.append(toCanonicalName(ref.getReturnType()));
-            }
-            return sb.toString();
-        }
-
-        boolean isConstructor() {
-            return isConstructor;
-        }
-    }
-
-    public static class FieldRef extends MemberRef {
-        FieldRef(DexBackedFieldReference ref, String from) {
-            super(makeSignature(ref), toCanonicalName(ref.getDefiningClass()), from);
-        }
-
-        private static String makeSignature(DexBackedFieldReference ref) {
-            return ref.getName() + ":" + toCanonicalName(ref.getType());
-        }
-    }
-
-    private final Map<String, DefinedClass> definedClassesInDex = new HashMap<>();
-    private final Map<String, DefinedMethod> definedMethodsInDex = new HashMap<>();
-    private final Map<String, DefinedField> definedFieldsInDex = new HashMap<>();
-
-    private final Map<String, TypeRef> typeReferences = new HashMap<>();
-    private final Map<String, MethodRef> methodReferences = new HashMap<>();
-    private final Map<String, FieldRef> fieldReferences = new HashMap<>();
-
-    private final ApprovedApis approvedApis;
-
-    public DexAnalyzer(Stream<PulledFile> files, ApprovedApis approvedApis) {
-        this.approvedApis = approvedApis;
-
-        files.forEach(file -> parse(file));
-
-        // Maps for methods and fields are constructed AFTER all files are parsed.
-        // This is because different dex files can have the same class with different sets of
-        // members - if they are statically linking to the same class which are built
-        // with source code at different times. In that case, members of the classes are
-        // merged together.
-        definedMethodsInDex.putAll(definedClassesInDex.values().stream()
-                .map(DefinedClass::getMethods)
-                .flatMap(methods -> methods.stream())
-                .collect(Collectors.toMap(DefinedMethod::getFullSignature,
-                        Function.identity())));
-
-        definedFieldsInDex.putAll(definedClassesInDex.values().stream()
-                .map(DefinedClass::getFields)
-                .flatMap(fields -> fields.stream())
-                .collect(
-                        Collectors.toMap(DefinedField::getFullSignature, Function.identity())));
-
-        if (UnofficialApisUsageTest.DEBUG) {
-            definedClassesInDex.values().stream().sorted()
-                    .forEach(def -> System.err.println(" Defined class: " + def.getName()));
-
-            definedMethodsInDex.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined method: " + def.getFullSignature()));
-
-            definedFieldsInDex.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined field: " + def.getFullSignature()));
-
-            typeReferences.values().stream().sorted().forEach(
-                    ref -> System.err.println(" type ref: " + ref.getName()));
-            methodReferences.values().stream().sorted().forEach(
-                    ref -> System.err.println(" method ref: " + ref.getFullSignature()));
-            fieldReferences.values().stream().sorted().forEach(
-                    ref -> System.err.println(" field ref: " + ref.getFullSignature()));
-        }
-
-        updateDefiningClassInReferences();
-    }
-
-    /**
-     * Parse a dex file to extract symbols defined in the file and symbols referenced from the file
-     */
-    private void parse(PulledFile file) {
-        if (UnofficialApisUsageTest.DEBUG) {
-            System.err.println("Analyzing file: " + file.pathInDevice);
-        }
-
-        try {
-            parseInner(file, "classes.dex");
-        } catch (DexFileNotFoundException e) {
-            // classes.dex must exist
-            throw new RuntimeException("classes.dex" + " not found in " + file, e);
-        }
-
-        int i = 2;
-        while (true) {
-            try {
-                parseInner(file, String.format("classes%d.dex", i++));
-            } catch (DexFileNotFoundException e) {
-                // failing to find additional dex files is okay. we just stop trying.
-                break;
-            }
-        }
-    }
-
-    private void parseInner(PulledFile file, String dexEntry) throws DexFileNotFoundException {
-        try {
-            DexBackedDexFile dexFile = DexFileFactory.loadDexEntry(file.fileInHost, dexEntry, true,
-                    Opcodes.getDefault());
-
-            // 1. extract defined symbols and add them to the maps
-            dexFile.getClasses().stream().forEach(classDef -> {
-                // If the same class is found (defined from one of the previous files), then
-                // merge the members of this class to the old class.
-                DefinedClass c = definedClassFrom(classDef);
-                if (definedClassesInDex.containsKey(c.getName())) {
-                    definedClassesInDex.get(c.getName()).addNewMembers(c.getMethods(),
-                            c.getFields());
-                } else {
-                    definedClassesInDex.put(c.getName(), c);
-                }
-            });
-
-            // 2. extract referenced symbols and add then to the sets
-            // Note that these *Ref classes are identified by their names or full signatures.
-            // This is required since a same reference can be created by different dex files.
-
-            // array types and primitive types are filtered-out
-            dexFile.getReferences(ReferenceType.TYPE).stream()
-                    .map(t -> new TypeRef((DexBackedTypeReference) t, file.pathInDevice))
-                    .filter(((Predicate<TypeRef>) TypeRef::isArray).negate())
-                    .filter(((Predicate<TypeRef>) TypeRef::isPrimitiveType).negate())
-                    .forEach(ref -> {
-                        if (typeReferences.containsKey(ref.getName())) {
-                            typeReferences.get(ref.getName()).merge(ref);
-                        } else {
-                            typeReferences.put(ref.getName(), ref);
-                        }
-                    });
-
-            dexFile.getReferences(ReferenceType.METHOD).stream()
-                    .map(m -> new MethodRef((DexBackedMethodReference) m, file.pathInDevice))
-                    .forEach(ref -> {
-                        if (methodReferences.containsKey(ref.getFullSignature())) {
-                            methodReferences.get(ref.getFullSignature()).merge(ref);
-                        } else {
-                            methodReferences.put(ref.getFullSignature(), ref);
-                        }
-                    });
-
-            dexFile.getReferences(ReferenceType.FIELD).stream()
-                    .map(f -> new FieldRef((DexBackedFieldReference) f, file.pathInDevice))
-                    .forEach(ref -> {
-                        if (fieldReferences.containsKey(ref.getFullSignature())) {
-                            fieldReferences.get(ref.getFullSignature()).merge(ref);
-                        } else {
-                            fieldReferences.put(ref.getFullSignature(), ref);
-                        }
-                    });
-
-        } catch (IOException e) {
-            throw new RuntimeException("Cannot parse dex file in " + file, e);
-        }
-    }
-
-    /**
-     * For For each method/field reference, try to find a class defining it. If found, update the
-     * reference in the set since its full signature has changed.
-     */
-    private void updateDefiningClassInReferences() {
-        Stream.concat(methodReferences.values().stream(), fieldReferences.values().stream())
-                .forEach(ref -> {
-                    DefinedClass c = findDefiningClass(ref);
-                    if (c != null && !ref.getDefiningClass().equals(c.getName())) {
-                        ref.setDefiningClass(c.getName());
-                    }
-                });
-    }
-
-    /**
-     * Try to find a true class defining the given member.
-     */
-    private DefinedClass findDefiningClass(MemberRef ref) {
-        return findMemberInner(ref, ref.getDefiningClass());
-    }
-
-    /**
-     * Try to find a class defining a member by from the given class up to the parent classes
-     */
-    private DefinedClass findMemberInner(MemberRef ref, String className) {
-        final Function<DefinedClass, Collection<String>> getMethods = (DefinedClass c) -> c
-                .getMethodSignatures();
-        final Function<DefinedClass, Collection<String>> getFields = (DefinedClass c) -> c
-                .getFieldSignatures();
-
-        Function<DefinedClass, Collection<String>> getMembers = ref instanceof MethodRef
-                ? getMethods
-                : getFields;
-
-        final boolean classFoundInDex = definedClassesInDex.containsKey(className);
-        final boolean classFoundInApi = approvedApis.getDefinedClasses().containsKey(className);
-        if (!classFoundInDex && !classFoundInApi) {
-            // unknown class.
-            return null;
-        }
-
-        if (classFoundInDex) {
-            DefinedClass c = definedClassesInDex.get(className);
-            if (getMembers.apply(c).contains(ref.getSignature())) {
-                // method was found in the class
-                return c;
-            }
-        }
-
-        if (classFoundInApi) {
-            DefinedClass c = approvedApis.getDefinedClasses().get(className);
-            if (getMembers.apply(c).contains(ref.getSignature())) {
-                // method was found in the class
-                return c;
-            }
-        }
-
-        // member was not found in the class. try finding in parent classes.
-        // first gather the name of parent classes both from dex and api
-        Set<String> parentClasses = new HashSet<>();
-        if (classFoundInDex) {
-            DefinedClass c = definedClassesInDex.get(className);
-            parentClasses.add(c.getSuperClass());
-            parentClasses.addAll(c.getInterfaces());
-        }
-        if (classFoundInApi) {
-            DefinedClass c = approvedApis.getDefinedClasses().get(className);
-            parentClasses.add(c.getSuperClass());
-            parentClasses.addAll(c.getInterfaces());
-        }
-        // null can be in parentClasses, because null might have been added as getSuperClass() is
-        // null for java.lang.Object
-        parentClasses.remove(null);
-
-        for (String pc : parentClasses) {
-            DefinedClass foundClass = findMemberInner(ref, pc);
-            if (foundClass != null) {
-                return foundClass;
-            }
-        }
-        return null;
-    }
-
-    private static class SkipIfNeeded implements Predicate<Ref> {
-        @Override
-        public boolean test(Ref ref) {
-            String className = (ref instanceof TypeRef) ?
-                    ((TypeRef)ref).getName() : ((MemberRef)ref).getDefiningClass();
-            if (className.endsWith("[]")) {
-                // Reference to array type is skipped
-                return true;
-            }
-            if (className.startsWith("dalvik.annotation.")
-                    || className.startsWith("javax.annotation.")) {
-                // These annotation classes are not part of API but they are not explicitly used.
-                return true;
-            }
-            if (className.startsWith("java.lang.")) {
-                // core java libraries are exempted.
-                return true;
-            }
-            if (ref instanceof MemberRef) {
-                MemberRef memberRef = (MemberRef)ref;
-                if (memberRef.getFullSignature().equals(
-                        "android.os.SystemProperties.set(java.lang.String,java.lang.String)void")) {
-                    // SystemProperties.set is exceptionally allowed.
-                    // TODO(b/73750660): remove this when sysprops are publicized via IDs.
-                    return true;
-                }
-            }
-            return false;
-        }
-    }
-
-    // for each type, method and field references, find the ones that are found neither in dex
-    // nor in api
-    public Stream<TypeRef> collectUndefinedTypeReferences() {
-        return typeReferences.values().stream()
-                .filter(ref -> !definedClassesInDex.containsKey(ref.getName())
-                        && !approvedApis.getDefinedClasses().containsKey(ref.getName()))
-                .filter((new SkipIfNeeded()).negate());
-    }
-
-    public Stream<MethodRef> collectUndefinedMethodReferences() {
-        return methodReferences.values().stream()
-                .filter(ref -> !definedMethodsInDex.containsKey(ref.getFullSignature())
-                        && !approvedApis.getDefinedMethods().containsKey(ref.getFullSignature()))
-                .filter((new SkipIfNeeded()).negate());
-    }
-
-    public Stream<FieldRef> collectUndefinedFieldReferences() {
-        return fieldReferences.values().stream()
-                .filter(ref -> !definedFieldsInDex.containsKey(ref.getFullSignature())
-                        && !approvedApis.getDefinedFields().containsKey(ref.getFullSignature()))
-                .filter((new SkipIfNeeded()).negate());
-    }
-
-    private static DefinedClass definedClassFrom(DexBackedClassDef def) {
-        String name = toCanonicalName(def.getType());
-        String superClassName = toCanonicalName(def.getSuperclass());
-        Collection<String> interfaceNames = def.getInterfaces().stream()
-                .map(n -> toCanonicalName(n))
-                .collect(Collectors.toList());
-
-        Collection<DefinedMethod> methods = StreamSupport
-                .stream(def.getMethods().spliterator(), false /* parallel */)
-                .map(DexAnalyzer::definedMethodFrom).collect(Collectors.toList());
-
-        Collection<DefinedField> fields = StreamSupport
-                .stream(def.getFields().spliterator(), false /* parallel */)
-                .map(DexAnalyzer::definedFieldFrom).collect(Collectors.toList());
-
-        return new DefinedClass(name, superClassName, interfaceNames, methods, fields);
-    }
-
-    private static DefinedMethod definedMethodFrom(DexBackedMethod def) {
-        StringBuffer sb = new StringBuffer();
-        sb.append(def.getName());
-        sb.append('(');
-        StringJoiner joiner = new StringJoiner(",");
-        for (String param : def.getParameterTypes()) {
-            joiner.add(toCanonicalName(param));
-        }
-        sb.append(joiner.toString());
-        sb.append(')');
-        final boolean isConstructor = def.getName().equals("<init>");
-        if (!isConstructor) {
-            sb.append(toCanonicalName(def.getReturnType()));
-        }
-
-        String signature = sb.toString();
-        String definingClass = toCanonicalName(def.getDefiningClass());
-        return new DefinedMethod(signature, definingClass);
-    }
-
-    private static DefinedField definedFieldFrom(DexBackedField def) {
-        String signature = def.getName() + ":" + toCanonicalName(def.getType());
-        String definingClass = toCanonicalName(def.getDefiningClass());
-        return new DefinedField(signature, definingClass);
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/FilePuller.java b/hostsidetests/api/src/com/android/cts/api/FilePuller.java
deleted file mode 100644
index 5e3b7cb..0000000
--- a/hostsidetests/api/src/com/android/cts/api/FilePuller.java
+++ /dev/null
@@ -1,94 +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.cts.api;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-import com.android.ddmlib.IShellOutputReceiver;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-
-/**
- * Pulls files from a non-rooted device
- */
-class FilePuller {
-    private final ITestDevice device;
-    private final Path hostDir;
-
-    FilePuller(ITestDevice device) {
-        this.device = device;
-        try {
-            hostDir = Files.createTempDirectory("pulled_files");
-            hostDir.toFile().deleteOnExit();
-        } catch (IOException e) {
-            throw new RuntimeException("Cannot create directory for pulled files", e);
-        }
-    }
-
-    void clean() {
-        hostDir.toFile().delete();
-    }
-
-    PulledFile pullFromDevice(String path, String name) {
-        try {
-            File outputFile = new File(hostDir.toFile(), name);
-            FileOutputStream outputStream = new FileOutputStream(outputFile);
-
-            // For files on vendor partition, `adb shell pull` does not work on non-rooted device,
-            // due to the permission. Thus using `cat` to copy file content to outside of the
-            // device, which might a little bit slower than adb pull, but should be acceptable for
-            // testing.
-            device.executeShellCommand(String.format("cat %s", path),
-                    new IShellOutputReceiver() {
-
-                        @Override
-                        public void addOutput(byte[] data, int offset, int len) {
-                            try {
-                                outputStream.write(data, offset, len);
-                            } catch (IOException e) {
-                                throw new RuntimeException("Error pulling file " + path, e);
-                            }
-                        }
-
-                        @Override
-                        public void flush() {
-                            try {
-                                outputStream.close();
-                            } catch (IOException e) {
-                                throw new RuntimeException("Error saving file " + path,
-                                        e);
-                            }
-                        }
-
-                        @Override
-                        public boolean isCancelled() {
-                            // don't cancel at any time.
-                            return false;
-                        }
-                    });
-            return new PulledFile(outputFile, path);
-        } catch (DeviceNotAvailableException e) {
-            throw new RuntimeException("Cannot connect to the device", e);
-        } catch (IOException e) {
-            throw new RuntimeException("Failed to pull file " + path, e);
-        }
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/PulledFile.java b/hostsidetests/api/src/com/android/cts/api/PulledFile.java
deleted file mode 100644
index 4742d52..0000000
--- a/hostsidetests/api/src/com/android/cts/api/PulledFile.java
+++ /dev/null
@@ -1,29 +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.cts.api;
-
-import java.io.File;
-
-class PulledFile {
-    final File fileInHost;
-    final String pathInDevice;
-
-    PulledFile(File fileInHost, String pathInDevice) {
-        this.fileInHost = fileInHost;
-        this.pathInDevice = pathInDevice;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java b/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
deleted file mode 100644
index ba36549..0000000
--- a/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
+++ /dev/null
@@ -1,251 +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.cts.api;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Stream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.android.compatibility.common.util.PropertyUtil;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.DeviceTestCase;
-
-/**
- * Ensures that java modules in vendor partition on the device are not using any non-approved APIs
- */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public class UnofficialApisUsageTest extends DeviceTestCase {
-    public final static boolean DEBUG = true;
-    private ITestDevice device;
-    private FilePuller filePuller;
-
-    @Override
-    protected void setUp() throws Exception {
-        device = getDevice();
-        filePuller = new FilePuller(device);
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        filePuller.clean();
-    }
-
-    private static class JavaModule {
-        enum Type {
-            JAR, APK,
-        }
-
-        public final String name;
-        public final String path;
-        public final Type type;
-
-        private JavaModule(String name, String path, Type type) {
-            this.name = name;
-            this.path = path;
-            this.type = type;
-        }
-
-        public static JavaModule newPackageFromLine(String line) {
-            // package:/path/to/apk=com.foo.bar
-            line = line.split(":")[1]; // filter-out "package:" prefix
-            int separatorPos = line.lastIndexOf('=');
-            String path = line.substring(0, separatorPos);
-            String name = line.substring(separatorPos + 1);
-            return new JavaModule(name, path, Type.APK);
-        }
-
-        public static JavaModule newLibraryFromLine(String line) {
-            // com.foo.bar -> (jar) /path/to/jar
-            String[] tokens = line.trim().split(" ");
-            String name = tokens[0];
-            String type = tokens[3];
-            String path = tokens[4];
-            return new JavaModule(name, path, type.equals("(jar)") ? Type.JAR : Type.APK);
-        }
-    }
-
-    private Stream<JavaModule> getPackages() throws DeviceNotAvailableException {
-        return Arrays.stream(device.executeShellCommand("cmd package list packages -f").split("\n"))
-                .map(line -> JavaModule.newPackageFromLine(line));
-    }
-
-    private Stream<JavaModule> getLibraries() throws DeviceNotAvailableException {
-        // cmd package list libraries only shows the name of the libraries, but not their paths.
-        // Until it shows the paths as well, let's use the old dumpsys package.
-        return Arrays.stream(device.executeShellCommand("dumpsys package libraries").split("\n"))
-                .skip(1) // for "Libraries:" header
-                .map(line -> JavaModule.newLibraryFromLine(line))
-                .filter(module -> module.type == JavaModule.Type.JAR); // only jars
-    }
-
-    private String getRealPath(String path) {
-        try {
-            return device.executeShellCommand(String.format("realpath %s", path));
-        } catch (DeviceNotAvailableException e) {
-            throw new RuntimeException("Cannot connect to device", e);
-        }
-    }
-
-    /**
-     * Tests whether the downloaded file has code or not, by examining the existence of classes.dex
-     * in it
-     */
-    private boolean hasCode(File file) {
-        try {
-            ZipFile zipFile = null;
-            try {
-                zipFile = new ZipFile(file);
-                Enumeration<? extends ZipEntry> entries = zipFile.entries();
-                while (entries.hasMoreElements()) {
-                    ZipEntry e = entries.nextElement();
-                    if (e.getName().equals("classes.dex")) {
-                        return true;
-                    }
-                }
-            } finally {
-                if (zipFile != null) {
-                    zipFile.close();
-                }
-            }
-            return false;
-        } catch (IOException e) {
-            throw new RuntimeException("Error while examining whether code is in " + file, e);
-        }
-    }
-
-    /**
-     * These tests are required only for the Treble-ized devices launching with P or later.
-     *
-     * @throws DeviceNotAvailableException
-     */
-    private boolean isTestRequired() throws DeviceNotAvailableException {
-        return PropertyUtil.propertyEquals(device, "ro.treble.enabled", "true")
-                && PropertyUtil.getFirstApiLevel(device) > 27 /* O_MR1 */;
-    }
-
-    /**
-     * The main test. If there is any type/method/field reference to unknown type/method/field, then
-     * it indicates that vendors are using non-approved APIs.
-     */
-    @Test
-    public void testNonApiReferences() throws Exception {
-        if (!isTestRequired()) {
-            return;
-        }
-        Stream<PulledFile> pulledFiles;
-        Stream<File> apiFiles;
-        ApprovedApis approvedApis;
-        DexAnalyzer extractedApis;
-
-        try {
-            // pulls packages and libraries which are in vendor partition and have code.
-            pulledFiles = Stream.concat(getPackages(), getLibraries())
-                    .filter(module -> getRealPath(module.path).startsWith("/vendor"))
-                    .map(module -> filePuller.pullFromDevice(module.path, module.name))
-                    .filter(file -> hasCode(file.fileInHost));
-
-        } catch (DeviceNotAvailableException e) {
-            throw new RuntimeException("Cannot connect to device", e);
-        }
-
-        apiFiles = Arrays.stream(new String[] {
-            "/current.txt",
-            "/system-current.txt",
-            "/android-test-base-current.txt",
-            "/android-test-runner-current.txt",
-            "/android-test-mock-current.txt",
-            "/27.txt",
-            "/apache-http-legacy-current"
-        }).map(name -> new File(name));
-
-        approvedApis = new ApprovedApis(apiFiles);
-        extractedApis = new DexAnalyzer(pulledFiles, approvedApis);
-
-        StringBuilder sb = new StringBuilder(10000);
-        extractedApis.collectUndefinedTypeReferences().sorted().forEach(
-                ref -> sb.append("Undefined type ref: " + ref.getName() + " from: "
-                        + ref.printReferencedFrom() + "\n"));
-        extractedApis.collectUndefinedMethodReferences().sorted().forEach(
-                ref -> sb.append("Undefined method ref: " + ref.getFullSignature() + " from: "
-                        + ref.printReferencedFrom() + "\n"));
-        extractedApis.collectUndefinedFieldReferences().sorted().forEach(
-                ref -> sb.append("Undefined field ref: " + ref.getFullSignature() + " from: "
-                        + ref.printReferencedFrom() + "\n"));
-        if (sb.length() != 0) {
-            fail(sb.toString());
-        }
-    }
-
-    /**
-     * Ensures that vendor apps are not targeting pre-P SDK.
-     */
-    @Test
-    public void testTargetSdk() throws Exception {
-        if (!isTestRequired()) {
-            return;
-        }
-        StringBuilder output = new StringBuilder();
-        Pattern p = Pattern.compile(".*targetSdk=(.*)\n");
-        getPackages()
-                .filter(module -> getRealPath(module.path).startsWith("/vendor"))
-                .forEach(module -> {
-                    try {
-                        // This is very dependent on how the information is shown in the dump.
-                        // Sould be checked for amendment whenever the format changes in
-                        // dumpPackagesLPr in Settings.java
-                        // 1. targetSdk version is shown as 'targetSdk=<number>'.
-                        // 2: tail -1 is for the case when an apk is updated in the data partition.
-                        // In that case, we get dumps for two packages (first for the updated one,
-                        // and then for the original one). Among these two, we use targetSdk for
-                        // the original one (the last dump), because the updated one can be
-                        // uninstalled or wiped out at any time.
-                        String result = device.executeShellCommand(
-                                "dumpsys package " + module.name + " | grep targetSdk= | tail -1");
-                        Matcher m = p.matcher(result);
-                        if (m.matches() && m.groupCount() == 1) {
-                            String versionString = m.group(1);
-                            int versionInt = Integer.parseInt(versionString);
-                            if (versionInt <= 27) {
-                                output.append("Vendor package " + module.name
-                                        + " is targeting old SDK: " + versionString + "\n");
-                            }
-                        } else {
-                            output.append(
-                                    "Failed to get targetSDK for vendor package " + module.name
-                                            + "\n");
-                        }
-                    } catch (DeviceNotAvailableException e) {
-                        output.append("Failed to get info for vendor package " + module.name
-                                + ". Cause: " + e.getMessage() + "\n");
-                    }
-                });
-        if (output.length() != 0) {
-            fail(output.toString());
-        }
-    }
-}
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
index 1d0f83e..38cdb3c 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
@@ -19,6 +19,7 @@
 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
 
+import android.app.KeyguardManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -56,6 +57,7 @@
     private Context mCe;
     private Context mDe;
     private PackageManager mPm;
+    private KeyguardManager mKm;
 
     private UiDevice mDevice;
     private AwareActivity mActivity;
@@ -67,6 +69,7 @@
         mCe = getInstrumentation().getContext();
         mDe = mCe.createDeviceProtectedStorageContext();
         mPm = mCe.getPackageManager();
+        mKm = (KeyguardManager) mCe.getSystemService(Context.KEYGUARD_SERVICE);
 
         mDevice = UiDevice.getInstance(getInstrumentation());
         assertNotNull(mDevice);
@@ -100,7 +103,9 @@
 
     public void testTearDown() throws Exception {
         // Just in case, always try tearing down keyguard
-        dismissKeyguard();
+        if (mKm.isKeyguardLocked()) {
+            dismissKeyguard();
+        }
 
         mActivity = launchActivity(getInstrumentation().getTargetContext().getPackageName(),
                 AwareActivity.class, null);
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java
index 2265dec..48a1b5d 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java
@@ -441,6 +441,10 @@
         final int originalSetting = Secure.getInt(contentResolver, Secure.INSTANT_APPS_ENABLED, 1);
         Secure.putInt(contentResolver, Secure.INSTANT_APPS_ENABLED, 0);
         try {
+            Thread.sleep(1000);
+        } catch (Exception e) {
+        }
+        try {
             // start the ephemeral activity; using VIEW/BROWSABLE with setting disabled
             try {
                 final Intent startViewIntent = new Intent(Intent.ACTION_VIEW)
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/raw/ringer.mp3 b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/raw/ringer.mp3
new file mode 100644
index 0000000..aa052e7
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/raw/ringer.mp3
Binary files differ
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
index d44b782..e66d041 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
@@ -20,6 +20,7 @@
 import android.content.pm.PackageManager;
 import android.media.AudioManager;
 import android.media.MediaPlayer;
+import android.net.Uri;
 import android.provider.Settings;
 import android.os.SystemClock;
 import android.os.UserManager;
@@ -84,8 +85,9 @@
             return;
         }
 
+        Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.ringer);
         MediaPlayer mediaPlayer = new MediaPlayer();
-        mediaPlayer.setDataSource(mContext, Settings.System.DEFAULT_RINGTONE_URI);
+        mediaPlayer.setDataSource(mContext, uri);
         mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
         mediaPlayer.prepare();
         mediaPlayer.setLooping(true);
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java
index 0fbbee1..3030e35 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java
@@ -19,6 +19,7 @@
 import android.os.UserHandle;
 import android.provider.Settings;
 
+import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
 /**
  * Test {@link DevicePolicyManager#setSystemSetting}.
  */
@@ -36,8 +37,23 @@
   }
 
   public void testSetBrightness() {
-    testSetBrightnessWithValue(TEST_BRIGHTNESS_1);
-    testSetBrightnessWithValue(TEST_BRIGHTNESS_2);
+    final int mode = Settings.System.getInt(mContext.getContentResolver(),
+        Settings.System.SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
+    if(mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
+
+        mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT,
+          Settings.System.SCREEN_BRIGHTNESS_MODE, "0");
+
+        testSetBrightnessWithValue(TEST_BRIGHTNESS_1);
+        testSetBrightnessWithValue(TEST_BRIGHTNESS_2);
+        mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT,
+            Settings.System.SCREEN_BRIGHTNESS_MODE,
+              mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC? "1" : "0");
+    }
+    else {
+       testSetBrightnessWithValue(TEST_BRIGHTNESS_1);
+       testSetBrightnessWithValue(TEST_BRIGHTNESS_2);
+    }
   }
 
   public void testSetSystemSettingsFailsForNonWhitelistedSettings() throws Exception {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
index 7b568af..eca6953 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
@@ -43,9 +43,6 @@
     protected static final String ACCOUNT_MANAGEMENT_APK
             = "CtsAccountManagementDevicePolicyApp.apk";
 
-    // Dequeue time of PACKAGE_ADDED intent for two test packages.
-    private static final int BROADCAST_WAIT_TIME_MILLIS = 10000; // 10 seconds
-
     @Override
     public void tearDown() throws Exception {
         if (mHasFeature) {
@@ -75,8 +72,9 @@
             assertTrue(setDeviceOwner(DEVICE_OWNER_ADMIN_COMPONENT, mPrimaryUserId,
                     /*expectFailure*/ false));
 
-            // Waiting for the broadcast idle state.
-            Thread.sleep(BROADCAST_WAIT_TIME_MILLIS);
+            // Wait broadcast idle to ensure the owner changed broadcast has been sent.
+            waitForBroadcastIdle();
+
             runDeviceTestsAsUser(INTENT_RECEIVER_PKG, testClass,
                     "testOwnerChangedBroadcastReceived", mPrimaryUserId);
         } finally {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java
index 0b17b17..a5fcf4e 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java
@@ -30,7 +30,15 @@
     public UserActivityEmulator(ITestDevice device) throws DeviceNotAvailableException {
         // Figure out screen size. Output is something like "Physical size: 1440x2880".
         mDevice = device;
-        final String output = mDevice.executeShellCommand("wm size");
+        String outputString = mDevice.executeShellCommand  ("wm size");
+
+        // In case that "Override size" follows by separator like 
+        // "Physical size: 1440x2960\nOverride size: 1080x2220"
+        if (outputString.contains("Override")) {
+            outputString = outputString.split(System.getProperty("line.separator"))[1];
+        }
+
+        final String output = outputString;
         final String[] sizes = output.split(" ")[2].split("x");
         mWidth = Integer.valueOf(sizes[0].trim());
         mHeight = Integer.valueOf(sizes[1].trim());
diff --git a/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java b/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
index 7a13e79..6c22f37 100644
--- a/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
+++ b/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
@@ -22,16 +22,12 @@
 import art.Main;
 
 /**
- * Check tagging-related functionality.
+ * Check tracking-related functionality.
  */
 public class JvmtiTrackingTest extends JvmtiTestBase {
 
     @Before
     public void setUp() throws Exception {
-        // Bind our native methods.
-        Main.bindAgentJNI("android/jvmti/cts/JvmtiTrackingTest",
-                getClass().getClassLoader());
-
         prefetchClassNames();
     }
 
diff --git a/hostsidetests/jvmti/base/jni/cts_agent.cpp b/hostsidetests/jvmti/base/jni/cts_agent.cpp
index 665a47e..3f3a836 100644
--- a/hostsidetests/jvmti/base/jni/cts_agent.cpp
+++ b/hostsidetests/jvmti/base/jni/cts_agent.cpp
@@ -25,12 +25,26 @@
 
 namespace art {
 
+extern void register_art_Main(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiRedefineClassesTest(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiTaggingTest(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv*, JNIEnv*);
+
 static void InformMainAttach(jvmtiEnv* jenv,
                              JNIEnv* env,
                              const char* class_name,
                              const char* method_name) {
+  // Register native methods from available classes
+  // The agent is used with each test class, but we don't know which class is currently available.
+  // For that reason, we try to register the native methods in each one. Each function returns
+  // without throwing an error if the specified class can't be found.
+  register_art_Main(jenv, env);
+  register_android_jvmti_cts_JvmtiRedefineClassesTest(jenv, env);
+  register_android_jvmti_cts_JvmtiTaggingTest(jenv, env);
+  register_android_jvmti_cts_JvmtiTrackingTest(jenv, env);
+
   // Use JNI to load the class.
-  ScopedLocalRef<jclass> klass(env, FindClass(jenv, env, class_name, nullptr));
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env, class_name, nullptr));
   CHECK(klass.get() != nullptr) << class_name;
 
   jmethodID method = env->GetStaticMethodID(klass.get(), method_name, "()V");
diff --git a/hostsidetests/jvmti/base/jni/redefine.cpp b/hostsidetests/jvmti/base/jni/redefine.cpp
index f96108c..1a044ca 100644
--- a/hostsidetests/jvmti/base/jni/redefine.cpp
+++ b/hostsidetests/jvmti/base/jni/redefine.cpp
@@ -23,6 +23,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "jni_binder.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
@@ -172,5 +173,40 @@
   env->ReleaseByteArrayElements(dex_bytes, redef_bytes, 0);
 }
 
+static JNINativeMethod gMethods[] = {
+  { "redefineClass", "(Ljava/lang/Class;[B)I",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_redefineClass },
+
+  { "retransformClass", "(Ljava/lang/Class;)I",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_retransformClass },
+
+  { "setTransformationEvent", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_setTransformationEvent },
+
+  { "clearTransformations", "()V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_clearTransformations },
+
+  { "setPopTransformations", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_setPopTransformations },
+
+  { "pushTransformationResult", "(Ljava/lang/String;[B)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_pushTransformationResult },
+};
+
+void register_android_jvmti_cts_JvmtiRedefineClassesTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiRedefineClassesTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiRedefineClassesTest class";
+  }
+}
+
 }  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tagging.cpp b/hostsidetests/jvmti/base/jni/tagging.cpp
index 372805b..35d83d7 100644
--- a/hostsidetests/jvmti/base/jni/tagging.cpp
+++ b/hostsidetests/jvmti/base/jni/tagging.cpp
@@ -18,6 +18,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "jni_binder.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
@@ -127,5 +128,48 @@
   return CreateObjectArray(env, 3, "java/lang/Object", callback);
 }
 
+static JNINativeMethod gMethodsForMain[] = {
+  { "setTag", "(Ljava/lang/Object;J)V",
+          (void*)Java_android_jvmti_cts_JniBindings_setTag },
+
+  { "getTag", "(Ljava/lang/Object;)J",
+          (void*)Java_android_jvmti_cts_JniBindings_getTag },
+};
+
+void register_art_Main(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env, "art/Main", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethodsForMain,
+          sizeof(gMethodsForMain) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for Main class";
+  }
+}
+
+static JNINativeMethod gMethods[] = {
+  { "getTaggedObjects", "([JZZ)[Ljava/lang/Object;",
+          (void*)Java_android_jvmti_cts_JvmtiTaggingTest_getTaggedObjects },
+};
+
+void register_android_jvmti_cts_JvmtiTaggingTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiTaggingTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiTaggingTest class";
+  }
+}
+
 }  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tracking.cpp b/hostsidetests/jvmti/base/jni/tracking.cpp
index a07d653..425fd63 100644
--- a/hostsidetests/jvmti/base/jni/tracking.cpp
+++ b/hostsidetests/jvmti/base/jni/tracking.cpp
@@ -21,6 +21,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/stringprintf.h"
+#include "jni_binder.h"
 #include "jvmti_helper.h"
 #include "scoped_local_ref.h"
 #include "scoped_utf_chars.h"
@@ -93,4 +94,30 @@
   return env->NewStringUTF(result.c_str());
 }
 
+static JNINativeMethod gMethods[] = {
+  { "setupObjectAllocCallback", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_setupObjectAllocCallback },
+
+  { "enableAllocationTracking", "(Ljava/lang/Thread;Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking },
+
+  { "getAndResetAllocationTrackingString", "()Ljava/lang/String;",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_getAndResetAllocationTrackingString },
+};
+
+void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiTrackingTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiTrackingTest class";
+  }
+}
+
 }  // namespace art
diff --git a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
index 00962d0..49c266d 100644
--- a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
+++ b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
@@ -108,7 +108,7 @@
      *
      * @throws Exception
      */
-    @CddTest(requirement="9.7")
+    @CddTest(requirement="9.7/C-0-7")
     public void testConfigStackProtectorStrong() throws Exception {
         assertTrue("Linux kernel must have Stack Protector enabled: " +
                 "CONFIG_CC_STACKPROTECTOR_STRONG=y",
@@ -121,7 +121,7 @@
      *
      * @throws Exception
      */
-    @CddTest(requirement="9.7")
+    @CddTest(requirement="9.7/C-0-8")
     public void testConfigROData() throws Exception {
         assertTrue("Linux kernel must have RO data enabled: " +
                 "CONFIG_DEBUG_RODATA=y or CONFIG_STRICT_KERNEL_RWX=y",
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
index 5641aee..158071d 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
@@ -22,76 +22,6 @@
 public class Poc16_10 extends SecurityTestCase {
 
     /**
-     *  b/30904789
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6730() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6730", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30906023
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6731() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6731", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30906599
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6732() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6732", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30906694
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6733() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6733", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30907120
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6734() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6734", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30907701
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6735() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6735", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30953284
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6736() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6736", getDevice(), 60);
-        }
-    }
-
-    /**
      *  b/30741779
      */
     @SecurityTest
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
new file mode 100644
index 0000000..da8da31
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
@@ -0,0 +1,93 @@
+/**
+ * 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+
+@SecurityTest
+public class Poc16_11 extends SecurityTestCase {
+
+    /**
+     *  b/30904789
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6730() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6730", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30906023
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6731() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6731", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30906599
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6732() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6732", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30906694
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6733() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6733", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30907120
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6734() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6734", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30907701
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6735() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6735", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30953284
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6736() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6736", getDevice(), 60);
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java
deleted file mode 100644
index 5e1b2fc..0000000
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java
+++ /dev/null
@@ -1,137 +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.security.cts;
-
-import android.platform.test.annotations.SecurityTest;
-
-@SecurityTest
-public class Poc16_12 extends SecurityTestCase {
-
-    //Criticals
-    /**
-     *  b/31797770
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8425() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
-            AdbUtils.runPoc("CVE-2016-8425", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31799206
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8426() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-gpu")) {
-            AdbUtils.runPoc("CVE-2016-8426", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31799885
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8427() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-gpu") ||
-              containsDriver(getDevice(), "/dev/nvhost-dbg-gpu")) {
-            AdbUtils.runPoc("CVE-2016-8427", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31993456
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8428() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8428", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32160775
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8429() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8429", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32225180
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8430() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
-            AdbUtils.runPoc("CVE-2016-8430", getDevice(), 60);
-        }
-    }
-
-   /**
-     *  b/32402179
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8431() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-8431", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32447738
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8432() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-8432", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32125137
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8434() throws Exception {
-        if(containsDriver(getDevice(), "/dev/kgsl-3d0")) {
-            // This poc is very verbose so we ignore the output to avoid using a lot of memory.
-            AdbUtils.runPocNoOutput("CVE-2016-8434", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31668540
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8460() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            String result = AdbUtils.runPoc("CVE-2016-8460", getDevice(), 60);
-            assertTrue(!result.equals("Vulnerable"));
-        }
-    }
-
-    /**
-     *  b/32659848
-     */
-    @SecurityTest
-    public void testPoc32659848() throws Exception {
-        String command =
-            "echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb";
-        AdbUtils.runCommandLine(command, getDevice());
-    }
-}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
index 4fd98b7..3446507 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
@@ -21,13 +21,117 @@
 @SecurityTest
 public class Poc17_01 extends SecurityTestCase {
 
+    //Criticals
     /**
-     *  b/31799863
+     *  b/31797770
      */
     @SecurityTest
-    public void testPocCVE_2016_8482() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8482", getDevice(), 60);
+    public void testPocCVE_2016_8425() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
+            AdbUtils.runPoc("CVE-2016-8425", getDevice(), 60);
         }
     }
+
+    /**
+     *  b/31799206
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8426() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-gpu")) {
+            AdbUtils.runPoc("CVE-2016-8426", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/31799885
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8427() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-gpu") ||
+              containsDriver(getDevice(), "/dev/nvhost-dbg-gpu")) {
+            AdbUtils.runPoc("CVE-2016-8427", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/31993456
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8428() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            AdbUtils.runPoc("CVE-2016-8428", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32160775
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8429() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            AdbUtils.runPoc("CVE-2016-8429", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32225180
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8430() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
+            AdbUtils.runPoc("CVE-2016-8430", getDevice(), 60);
+        }
+    }
+
+   /**
+     *  b/32402179
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8431() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-8431", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32447738
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8432() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-8432", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32125137
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8434() throws Exception {
+        if(containsDriver(getDevice(), "/dev/kgsl-3d0")) {
+            // This poc is very verbose so we ignore the output to avoid using a lot of memory.
+            AdbUtils.runPocNoOutput("CVE-2016-8434", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/31668540
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8460() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            String result = AdbUtils.runPoc("CVE-2016-8460", getDevice(), 60);
+            assertTrue(!result.equals("Vulnerable"));
+        }
+    }
+
+    /**
+     *  b/32659848
+     */
+    @SecurityTest
+    public void testPoc32659848() throws Exception {
+        String command =
+            "echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb";
+        AdbUtils.runCommandLine(command, getDevice());
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
index 44f7d27..fc68707 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
@@ -29,4 +29,14 @@
       String logcatOut = AdbUtils.runCommandLine("logcat -d", getDevice());
       assertNotMatches("[\\s\\n\\S]*Bugreports file in wrong path[\\s\\n\\S]*", logcatOut);
   }
+
+    /**
+     *  b/31799863
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8482() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            AdbUtils.runPoc("CVE-2016-8482", getDevice(), 60);
+        }
+    }
 }
diff --git a/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java b/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java
index ab377d9..f38348c 100644
--- a/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java
+++ b/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java
@@ -26,6 +26,7 @@
 import android.view.ContextMenu;
 import android.view.View;
 import android.view.ContextMenu.ContextMenuInfo;
+import android.support.test.InstrumentationRegistry;
 import android.widget.ExpandableListAdapter;
 import android.widget.ExpandableListView;
 import android.widget.SimpleExpandableListAdapter;
@@ -114,23 +115,29 @@
         return RESULT_OK;
     }
 
-    private int testSelecte() {
+    private int testSelect() {
         final ExpandableListView v = getExpandableListView();
-        for (int i = 0; i < 20; i++) {
-            v.expandGroup(i);
-            setSelectedGroup(i);
-            for (int k = 0; k < 15; k++) {
-                setSelectedChild(i, k, false);
-                if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
-                    return RESULT_CANCELED;
-            }
+        try {
+            // Make sure the touch mode is disabled since selection doesn't work in touch mode.
+            InstrumentationRegistry.getInstrumentation().setInTouchMode(false);
+            for (int i = 0; i < 20; i++) {
+                v.expandGroup(i);
+                setSelectedGroup(i);
+                for (int k = 0; k < 15; k++) {
+                    setSelectedChild(i, k, false);
+                    if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
+                        return RESULT_CANCELED;
+                }
 
-            for (int k = 0; k < 15; k++) {
-                setSelectedChild(i, k, true);
-                if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
-                    return RESULT_CANCELED;
+                for (int k = 0; k < 15; k++) {
+                    setSelectedChild(i, k, true);
+                    if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
+                        return RESULT_CANCELED;
+                }
+                v.collapseGroup(i);
             }
-            v.collapseGroup(i);
+        } finally {
+            InstrumentationRegistry.getInstrumentation().setInTouchMode(true);
         }
         return RESULT_OK;
     }
@@ -140,7 +147,7 @@
         super.onResume();
         final String action = getIntent().getAction();
         if (LaunchpadActivity.EXPANDLIST_SELECT.equals(action)) {
-            setResult(testSelecte());
+            setResult(testSelect());
         } else if (LaunchpadActivity.EXPANDLIST_VIEW.equals(action)) {
             setResult(testView());
         } else if (LaunchpadActivity.EXPANDLIST_CALLBACK.equals(action)) {
diff --git a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
index b6a031a..ae58e43 100644
--- a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
@@ -1009,7 +1009,8 @@
             uidWatcher.waitFor(WatchUidRunner.CMD_ACTIVE, null);
             uidWatcher.waitFor(WatchUidRunner.CMD_UNCACHED, null);
             uidWatcher.waitFor(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_FG_SERVICE);
-
+            // Remove tempwhitelist avoid temp white list block idle command and app crash occur.
+            executeShellCmd("cmd deviceidle tempwhitelist -r " + SIMPLE_PACKAGE_NAME);
             // Good, now stop the service and wait for it to go away.
             mContext.stopService(mServiceStartForegroundIntent);
             conn.waitForDisconnect();
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 98fa7af..f72fcd7 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -1097,7 +1097,7 @@
             }
 
             for (int inFormat : inputFormats) {
-                int outputFormats [] = config.getValidOutputFormatsForInput(inputFormat);
+                int outputFormats [] = config.getValidOutputFormatsForInput(inFormat);
                 for (int outFormat : outputFormats) {
                     if (inFormat == outFormat) {
                         inputFormat = inFormat;
diff --git a/tests/framework/base/activitymanager/AndroidManifest.xml b/tests/framework/base/activitymanager/AndroidManifest.xml
old mode 100644
new mode 100755
index 5b9672b..f442cdb6
--- a/tests/framework/base/activitymanager/AndroidManifest.xml
+++ b/tests/framework/base/activitymanager/AndroidManifest.xml
@@ -23,6 +23,7 @@
     <uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS" />
     <uses-permission android:name="android.permission.ACTIVITY_EMBEDDING" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
+    <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
 
     <application android:label="CtsActivityManagerDeviceTestCases">
         <uses-library android:name="android.test.runner" />
diff --git a/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java b/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
index b772ce2..30f7a85 100644
--- a/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
+++ b/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
@@ -29,10 +29,14 @@
 
     private boolean mReady;
 
+    private boolean mStarted;
+    private Bundle mExtras;
+
     @Override
     public void onReady() {
         super.onReady();
         mReady = true;
+        showSessionIfReady();
     }
 
     @Override
@@ -43,13 +47,18 @@
             stopSelf();
             return START_NOT_STICKY;
         }
-        if (mReady) {
-            Bundle extras = intent.getExtras() != null ? intent.getExtras() : new Bundle();
-            showSession(extras, 0);
-        }
+        mExtras = intent.getExtras() != null ? intent.getExtras() : new Bundle();
+        mStarted = true;
+        showSessionIfReady();
         return START_NOT_STICKY;
     }
 
+    private void showSessionIfReady() {
+        if (mReady && mStarted) {
+            showSession(mExtras, 0);
+        }
+    };
+
     /**
      * Starts the assistant voice interaction service, which initiates a new session that starts
      * the assistant activity.
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java
index 7f431c8..f625fdd 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java
@@ -334,8 +334,13 @@
                 slibNames, deviceConfig.sharedLibraries);
 
         FeatureInfo[] features = mPm.getSystemAvailableFeatures();
-        Arrays.sort(features, (o1, o2) ->
-                (o1.name == o2.name ? 0 : (o1.name == null ? -1 : o1.name.compareTo(o2.name))));
+        Arrays.sort(features, (o1, o2) -> {
+            if (o1.name == o2.name) return 0;
+            if (o1.name == null) return -1;
+            if (o2.name == null) return 1;
+            return o1.name.compareTo(o2.name);
+        });
+
         int size = 0;
         for (int i = 0; i < features.length; i++) {
             if (features[i].name != null) {
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
index b866101..dbc93b4 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
@@ -565,7 +565,7 @@
 
         // Launch first PIP activity
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
-        waitForEnterPip(PIP_ACTIVITY);
+        waitForEnterPipAnimationComplete(PIP_ACTIVITY);
 
         // Launch second PIP activity
         launchActivity(PIP_ACTIVITY2, EXTRA_ENTER_PIP, "true");
diff --git a/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java b/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java
old mode 100644
new mode 100755
index a53993b..bf3d1ea
--- a/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java
@@ -327,6 +327,7 @@
             pressBackButton();
             mAmWmState.waitForKeyguardShowingAndNotOccluded();
             mAmWmState.waitForDisplayUnfrozen();
+            mAmWmState.waitForAppTransitionIdle();
             mAmWmState.assertSanity();
             mAmWmState.assertHomeActivityVisible(false);
             mAmWmState.assertKeyguardShowingAndNotOccluded();
diff --git a/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java b/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java
index 9903653..153a4cc 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java
@@ -150,12 +150,14 @@
                 occludedActivityState(translucentActivity, topOpaqueActivity),
                 state(topOpaqueActivity, ON_RESUME));
 
-        getLifecycleLog().clear();
         try (final RotationSession rotationSession = new RotationSession()) {
             if (!supportsLockedUserRotation(
                     rotationSession, translucentActivity.getDisplay().getDisplayId())) {
                 return;
             }
+
+            getLifecycleLog().clear();
+
             final int current = rotationSession.get();
             // Set new rotation to cause a configuration change.
             switch (current) {
diff --git a/tests/leanbackjank/app/res/layout/icon_header_item.xml b/tests/leanbackjank/app/res/layout/icon_header_item.xml
index 56c8488..ce4942d 100644
--- a/tests/leanbackjank/app/res/layout/icon_header_item.xml
+++ b/tests/leanbackjank/app/res/layout/icon_header_item.xml
@@ -17,6 +17,8 @@
 <androidx.leanback.widget.NonOverlappingLinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="horizontal"
+    android:focusable="true"
+    android:focusableInTouchMode="true"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
 
diff --git a/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java b/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java
index ded9ea1..0c19395 100644
--- a/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java
+++ b/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java
@@ -32,7 +32,7 @@
     private static final long WAIT_TIMEOUT = 5 * MILLIS_PER_SECOND;
     private static final int SCROLL_COUNT = 100;
     private static final int SCROLL_INTERVAL_MILLIS = 200;
-    private static final int PRE_SCROLL_DELAY_MILLIS = 0;
+    private static final int PRE_SCROLL_DELAY_MILLIS = 500;
     private static final int PRE_SCROLL_IDLE_TIME = 2 * MILLIS_PER_SECOND;
     private static final int SAMPLING_DURATION_SECONDS = 2;
     private static final int SAMPLING_DURATION_MILLIS =
diff --git a/tests/libcore/wycheproof-bc/AndroidTest.xml b/tests/libcore/wycheproof-bc/AndroidTest.xml
index 2e92706..8e455bf 100644
--- a/tests/libcore/wycheproof-bc/AndroidTest.xml
+++ b/tests/libcore/wycheproof-bc/AndroidTest.xml
@@ -30,7 +30,7 @@
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="runtime-hint" value="10m"/>
-        <option name="test-timeout" value="600000" />
+        <option name="runtime-hint" value="16m"/>
+        <option name="test-timeout" value="3600000" />
     </test>
 </configuration>
diff --git a/tests/sensor/src/android/hardware/cts/SensorSupportTest.java b/tests/sensor/src/android/hardware/cts/SensorSupportTest.java
index 9d2b454..7988ef3 100644
--- a/tests/sensor/src/android/hardware/cts/SensorSupportTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorSupportTest.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.content.res.Configuration;
 import android.hardware.Sensor;
 import android.hardware.SensorDirectChannel;
 import android.hardware.SensorManager;
@@ -41,6 +42,7 @@
     private SensorManager mSensorManager;
     private boolean mAreHifiSensorsSupported;
     private boolean mVrHighPerformanceModeSupported;
+    private boolean mIsVrHeadset;
 
     @Override
     public void setUp() {
@@ -48,6 +50,8 @@
         // Tests will only run if either HIFI_SENSORS or VR high performance mode is supported.
         mAreHifiSensorsSupported = pm.hasSystemFeature(PackageManager.FEATURE_HIFI_SENSORS);
         mVrHighPerformanceModeSupported = pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
+        mIsVrHeadset = (getContext().getResources().getConfiguration().uiMode
+            & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET;
         if (mAreHifiSensorsSupported || mVrHighPerformanceModeSupported) {
             mSensorManager =
                     (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
@@ -128,7 +132,7 @@
         if (mAreHifiSensorsSupported || isVrSensor) {
             Sensor sensor = mSensorManager.getDefaultSensor(sensorType);
             assertTrue(sensor != null);
-            if (isVrSensor) {
+            if (isVrSensor && mIsVrHeadset) {
                 assertTrue(sensor.isDirectChannelTypeSupported(SensorDirectChannel.TYPE_HARDWARE_BUFFER));
             }
         }
diff --git a/tests/signature/dex-checker/dex-checker.cpp b/tests/signature/dex-checker/dex-checker.cpp
index 4a80e02..61d9e32 100644
--- a/tests/signature/dex-checker/dex-checker.cpp
+++ b/tests/signature/dex-checker/dex-checker.cpp
@@ -49,7 +49,8 @@
   ScopedUtfChars utf_type(env, type);
   jfieldID fid = env->GetFieldID(klass, utf_name.c_str(), utf_type.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetFieldID could have thrown either NoSuchFieldError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedField(klass, fid, /* static */ false);
@@ -62,7 +63,8 @@
   ScopedUtfChars utf_type(env, type);
   jfieldID fid = env->GetStaticFieldID(klass, utf_name.c_str(), utf_type.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetStaticFieldID could have thrown either NoSuchFieldError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedField(klass, fid, /* static */ true);
@@ -75,7 +77,8 @@
   ScopedUtfChars utf_signature(env, signature);
   jmethodID mid = env->GetMethodID(klass, utf_name.c_str(), utf_signature.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetMethodID could have thrown either NoSuchMethodError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedMethod(klass, mid, /* static */ false);
@@ -88,7 +91,8 @@
   ScopedUtfChars utf_signature(env, signature);
   jmethodID mid = env->GetStaticMethodID(klass, utf_name.c_str(), utf_signature.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetStaticMethodID could have thrown either NoSuchMethodError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedMethod(klass, mid, /* static */ true);
diff --git a/tests/signature/intent-check/DynamicConfig.xml b/tests/signature/intent-check/DynamicConfig.xml
index 934d60a..10b4834 100644
--- a/tests/signature/intent-check/DynamicConfig.xml
+++ b/tests/signature/intent-check/DynamicConfig.xml
@@ -25,6 +25,11 @@
     Bug: 78574873 android.intent.action.EPHEMERAL_RESOLVER_SETTINGS
     Bug: 115799975 android.intent.action.ACTION_AIRPLANE_MODE_CHANGED
          Will be removed after v17 of CS.apk is released.
+    Bug: 117590943 android.intent.action.View
+         Fixed in GMSCore v14.7.68.
+    Bug: 67109014 android.intent.action.BADGE_COUNT_UPDATE // Samsung is sending
+    //new corrected intent and the old intent in P.
+    //Target date for fix is under disucssion for BADGE_COUNT_UPDATE
 -->
 <dynamicConfig>
     <entry key ="intent_whitelist">
@@ -37,5 +42,7 @@
       <value>android.intent.action.RESOLVE_EPHEMERAL_PACKAGE</value>
       <value>android.intent.action.EPHEMERAL_RESOLVER_SETTINGS</value>
       <value>android.intent.action.ACTION_AIRPLANE_MODE_CHANGED</value>
+      <value>android.intent.action.View</value>
+      <value>android.intent.action.BADGE_COUNT_UPDATE</value>
     </entry>
 </dynamicConfig>
diff --git a/tests/signature/src/android/signature/cts/DexMemberChecker.java b/tests/signature/src/android/signature/cts/DexMemberChecker.java
index 528e868..1efdbad 100644
--- a/tests/signature/src/android/signature/cts/DexMemberChecker.java
+++ b/tests/signature/src/android/signature/cts/DexMemberChecker.java
@@ -16,6 +16,7 @@
 
 package android.signature.cts;
 
+import android.util.Log;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Executable;
 import java.lang.reflect.Field;
@@ -24,6 +25,7 @@
 import java.util.List;
 
 public class DexMemberChecker {
+    public static final String TAG = "DexMemberChecker";
 
     public interface Observer {
         void classAccessible(boolean accessible, DexMember member);
@@ -85,17 +87,39 @@
             observer.fieldAccessibleViaReflection(
                     hasMatchingField_Reflection(klass, field),
                     field);
-            observer.fieldAccessibleViaJni(
-                    hasMatchingField_JNI(klass, field),
-                    field);
+            try {
+                observer.fieldAccessibleViaJni(
+                        hasMatchingField_JNI(klass, field),
+                        field);
+            } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
+                if ((e instanceof NoClassDefFoundError)
+                        && !(e.getCause() instanceof ExceptionInInitializerError)
+                        && !(e.getCause() instanceof UnsatisfiedLinkError)) {
+                    throw e;
+                }
+
+                // Could not initialize the class. Skip JNI test.
+                Log.w(TAG, "JNI failed for " + dexMember.toString(), e);
+            }
         } else if (dexMember instanceof DexMethod) {
             DexMethod method = (DexMethod) dexMember;
             observer.methodAccessibleViaReflection(
                     hasMatchingMethod_Reflection(klass, method),
                     method);
-            observer.methodAccessibleViaJni(
-                    hasMatchingMethod_JNI(klass, method),
-                    method);
+            try {
+                observer.methodAccessibleViaJni(
+                        hasMatchingMethod_JNI(klass, method),
+                        method);
+            } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
+                if ((e instanceof NoClassDefFoundError)
+                        && !(e.getCause() instanceof ExceptionInInitializerError)
+                        && !(e.getCause() instanceof UnsatisfiedLinkError)) {
+                    throw e;
+                }
+
+                // Could not initialize the class. Skip JNI test.
+                Log.w(TAG, "JNI failed for " + dexMember.toString(), e);
+            }
         } else {
             throw new IllegalStateException("Unexpected type of dex member");
         }
@@ -134,10 +158,25 @@
     }
 
     private static boolean hasMatchingField_JNI(Class<?> klass, DexField dexField) {
-        Field ifield = getField_JNI(klass, dexField.getName(), dexField.getDexType());
-        Field sfield = getStaticField_JNI(klass, dexField.getName(), dexField.getDexType());
-        return (ifield != null && ifield.getDeclaringClass() == klass) ||
-               (sfield != null && sfield.getDeclaringClass() == klass);
+        try {
+            Field ifield = getField_JNI(klass, dexField.getName(), dexField.getDexType());
+            if (ifield.getDeclaringClass() == klass) {
+              return true;
+            }
+        } catch (NoSuchFieldError e) {
+            // Not found.
+        }
+
+        try {
+            Field sfield = getStaticField_JNI(klass, dexField.getName(), dexField.getDexType());
+            if (sfield.getDeclaringClass() == klass) {
+              return true;
+            }
+        } catch (NoSuchFieldError e) {
+            // Not found.
+        }
+
+        return false;
     }
 
     private static boolean hasMatchingMethod_Reflection(Class<?> klass, DexMethod dexMethod) {
@@ -163,11 +202,29 @@
     }
 
     private static boolean hasMatchingMethod_JNI(Class<?> klass, DexMethod dexMethod) {
-        Executable imethod = getMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
-        Executable smethod = dexMethod.isConstructor() ? null :
-             getStaticMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
-        return (imethod != null && imethod.getDeclaringClass() == klass) ||
-               (smethod != null && smethod.getDeclaringClass() == klass);
+        try {
+            Executable imethod = getMethod_JNI(
+                klass, dexMethod.getName(), dexMethod.getDexSignature());
+            if (imethod.getDeclaringClass() == klass) {
+                return true;
+            }
+        } catch (NoSuchMethodError e) {
+            // Not found.
+        }
+
+        if (!dexMethod.isConstructor()) {
+            try {
+                Executable smethod =
+                    getStaticMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
+                if (smethod.getDeclaringClass() == klass) {
+                    return true;
+                }
+            } catch (NoSuchMethodError e) {
+                // Not found.
+            }
+        }
+
+        return false;
     }
 
     private static native Field getField_JNI(Class<?> klass, String name, String type);
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
index 7019ea4..beaa315 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
@@ -246,7 +246,7 @@
     }
 }
 
-int32_t SwapchainInfo::init(bool setPreTransform) {
+int32_t SwapchainInfo::init(bool setPreTransform, int* outPreTransformHint) {
     VkSurfaceCapabilitiesKHR surfaceCapabilities;
     VK_CALL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(mDeviceInfo->gpu(), mDeviceInfo->surface(),
                                                       &surfaceCapabilities));
@@ -297,6 +297,10 @@
         std::swap(mDisplaySize.width, mDisplaySize.height);
     }
 
+    if (outPreTransformHint) {
+        *outPreTransformHint = preTransform;
+    }
+
     const uint32_t queueFamilyIndex = mDeviceInfo->queueFamilyIndex();
     const VkSwapchainCreateInfoKHR swapchainCreateInfo = {
             .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
index f876aad..21174b4 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
@@ -54,7 +54,7 @@
 public:
     SwapchainInfo(const DeviceInfo* const deviceInfo);
     ~SwapchainInfo();
-    int32_t init(bool setPreTransform);
+    int32_t init(bool setPreTransform, int* outPreTransformHint);
     VkFormat format() const { return mFormat; }
     VkExtent2D displaySize() const { return mDisplaySize; }
     VkSwapchainKHR swapchain() const { return mSwapchain; }
diff --git a/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp
index f96e39c..24721c3 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp
@@ -33,16 +33,6 @@
     AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
 static constexpr uint32_t kTestImageCount = 3;
 
-// Checks if a vector has more than 10 unique values, in which case we consider
-// it noisy.
-bool isNoisy(const std::vector<uint32_t> &data) {
-  std::set<uint32_t> values_seen;
-  for (uint32_t value : data) {
-    values_seen.insert(value);
-  }
-  return values_seen.size() > 10;
-}
-
 } // namespace
 
 // A basic test which does the following:
@@ -94,8 +84,7 @@
              vkImage.semaphore(), vkImage.isSamplerImmutable(), &imageData),
          "Could not render/read-back Vulkan pixels.");
 
-  // Ensure that we see noise.
-  ASSERT(isNoisy(imageData), "Camera data should be noisy.");
+  // TODO(b/110025779): We should find a way to validate pixels.
 }
 
 static JNINativeMethod gMethods[] = {
diff --git a/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp b/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
index 2a347b2..16fc851 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
@@ -33,14 +33,14 @@
 
 namespace {
 
-jboolean validatePixelValues(JNIEnv* env, jboolean setPreTransform) {
+jboolean validatePixelValues(JNIEnv* env, jboolean setPreTransform, jint preTransformHint) {
     jclass clazz = env->FindClass("android/graphics/cts/VulkanPreTransformTest");
-    jmethodID mid = env->GetStaticMethodID(clazz, "validatePixelValuesAfterRotation", "(Z)Z");
+    jmethodID mid = env->GetStaticMethodID(clazz, "validatePixelValuesAfterRotation", "(ZI)Z");
     if (mid == 0) {
         ALOGE("Failed to find method ID");
         return false;
     }
-    return env->CallStaticBooleanMethod(clazz, mid, setPreTransform);
+    return env->CallStaticBooleanMethod(clazz, mid, setPreTransform, preTransformHint);
 }
 
 void createNativeTest(JNIEnv* env, jclass /*clazz*/, jobject jAssetManager, jobject jSurface,
@@ -50,6 +50,7 @@
     ASSERT(jSurface, "jSurface is NULL");
 
     DeviceInfo deviceInfo;
+    int preTransformHint;
     int ret = deviceInfo.init(env, jSurface);
     ASSERT(ret >= 0, "Failed to initialize Vulkan device");
     if (ret > 0) {
@@ -58,7 +59,7 @@
     }
 
     SwapchainInfo swapchainInfo(&deviceInfo);
-    ASSERT(!swapchainInfo.init(setPreTransform), "Failed to initialize Vulkan swapchain");
+    ASSERT(!swapchainInfo.init(setPreTransform, &preTransformHint), "Failed to initialize Vulkan swapchain");
 
     Renderer renderer(&deviceInfo, &swapchainInfo);
     ASSERT(!renderer.init(env, jAssetManager), "Failed to initialize Vulkan renderer");
@@ -67,7 +68,7 @@
         ASSERT(!renderer.drawFrame(), "Failed to draw frame");
     }
 
-    ASSERT(validatePixelValues(env, setPreTransform), "Not properly rotated");
+    ASSERT(validatePixelValues(env, setPreTransform, preTransformHint), "Not properly rotated");
 }
 
 const std::array<JNINativeMethod, 1> JNI_METHODS = {{
diff --git a/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java b/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java
index 5906c899..8598b84 100644
--- a/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java
@@ -24,6 +24,9 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import android.os.Build;
+import com.android.compatibility.common.util.PropertyUtil;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class CameraVulkanGpuTest {
@@ -40,6 +43,11 @@
             return;
         }
 
+        if(PropertyUtil.getFirstApiLevel() < Build.VERSION.SDK_INT){
+            // HAL3 is not required for P upgrade devices.
+            return;
+        }
+
         loadCameraAndVerifyFrameImport(InstrumentationRegistry.getContext().getAssets());
     }
 
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
index 7918d58..d368f0e 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
@@ -31,7 +31,6 @@
 import android.test.suitebuilder.annotation.LargeTest;
 import android.util.Log;
 import android.view.PixelCopy;
-import android.view.Surface;
 import android.view.SurfaceView;
 
 import com.android.compatibility.common.util.SynchronousPixelCopy;
@@ -167,28 +166,29 @@
                 + Math.abs(actualB - expectedB);
     }
 
-    private static boolean validatePixelValuesAfterRotation(boolean setPreTransform) {
+    private static boolean validatePixelValuesAfterRotation(
+            boolean setPreTransform, int preTransformHint) {
         Bitmap bitmap = takeScreenshot();
 
         int width = bitmap.getWidth();
         int height = bitmap.getHeight();
         int diff = 0;
-        if (!setPreTransform || sActivity.getRotation() == Surface.ROTATION_0) {
+        if (!setPreTransform || preTransformHint == 0x1 /*VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR*/) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 255, 0);
-        } else if (sActivity.getRotation() == Surface.ROTATION_90) {
+        } else if (preTransformHint == 0x2 /*VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR*/) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 0, 255);
-        } else if (sActivity.getRotation() == Surface.ROTATION_180) {
+        } else if (preTransformHint == 0x4 /*VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR*/) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 0, 0);
-        } else {
+        } else { /* 0x8 : VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR*/
             diff += pixelDiff(bitmap.getPixel(0, 0), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 255, 0);
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java
index a3f116e..3780124 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java
@@ -350,7 +350,12 @@
 
             drawable.start();
             assertTrue(drawable.isRunning());
+        });
 
+        cb.waitForStart();
+        cb.assertStarted(true);
+
+        mActivityRule.runOnUiThread(() -> {
             drawable.stop();
             assertFalse(drawable.isRunning());
         });
@@ -358,7 +363,6 @@
         // This duration may be overkill, but we need to wait for the message
         // to post. Increasing it should help with flakiness on bots.
         cb.waitForEnd(DURATION * 3);
-        cb.assertStarted(true);
         cb.assertEnded(true);
     }
 
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index cf6da3c..1bc5f8c 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -41,8 +41,6 @@
     private final static String SYSTEM_CONFIG_FILE = PUBLIC_CONFIG_DIR + "public.libraries.txt";
     private final static Pattern EXTENSION_CONFIG_FILE_PATTERN = Pattern.compile(
             "public\\.libraries-([A-Za-z0-9\\-_.]+)\\.txt");
-    private final static Pattern EXTENSION_LIBRARY_FILE_PATTERN = Pattern.compile(
-            "lib[^.]+\\.([A-Za-z0-9\\-_.]+)\\.so");
     private final static String VENDOR_CONFIG_FILE = "/vendor/etc/public.libraries.txt";
     private final static String[] PUBLIC_SYSTEM_LIBRARIES = {
         "libaaudio.so",
@@ -126,8 +124,12 @@
                 // libFoo.acme.so
                 List<String> libNames = readPublicLibrariesFile(configFile);
                 for (String lib : libNames) {
-                    Matcher libMatcher = EXTENSION_LIBRARY_FILE_PATTERN.matcher(lib);
-                    if (libMatcher.matches() && libMatcher.group(1).equals(companyName)) {
+                    int space = lib.lastIndexOf(' ');
+                    if (space != -1) {
+                      // Drop 64 or 32 from 'libFoo.so 64'
+                      lib = lib.substring(0, space);
+                    }
+                    if (lib.endsWith("." + companyName + ".so")) {
                         libs.add(lib);
                     } else {
                         return "Library \"" + lib + "\" in " + configFile.toString()
diff --git a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
index 7db0f61..4bd6965 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
@@ -1345,46 +1345,6 @@
         assertPrivateKeyEntryEquals(actual, "RSA", FAKE_RSA_KEY_1, FAKE_RSA_USER_1, FAKE_RSA_CA_1);
     }
 
-    public void testKeyStore_SetEntry_PrivateKeyEntry_Params_Unencrypted_Failure() throws Exception {
-        // The Android Keystore requires encrypted storage which is only decryptable with a key
-        // bound to a credential provided by the user. By default, the Keystore waits for the user
-        // to set a lock screen PIN or password and uses this credential to set up an encrypted
-        // storage space itself. In that implementation, the Keystore should not be initialized when
-        // no lock screen PIN or password has been set. This is what the test verifies.
-        //
-        // If your environment already provides encrypted storage which is only decryptable with a
-        // key bound to another credential provided by the user, you may initialize the Keystore
-        // immediately and get a waiver for this test.
-        KeyguardManager keyguardManager =
-                (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
-        assertNotNull(keyguardManager);
-        assertFalse("Secure lock screen must not be configured", keyguardManager.isDeviceSecure());
-
-        mKeyStore.load(null, null);
-
-        KeyFactory keyFact = KeyFactory.getInstance("RSA");
-        PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_RSA_KEY_1));
-
-        final CertificateFactory f = CertificateFactory.getInstance("X.509");
-
-        final Certificate[] expectedChain = new Certificate[2];
-        expectedChain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_USER_1));
-        expectedChain[1] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_CA_1));
-
-        PrivateKeyEntry entry = new PrivateKeyEntry(expectedKey, expectedChain);
-
-        try {
-            mKeyStore.setEntry(TEST_ALIAS_1, entry,
-                    new KeyStoreParameter.Builder(getContext())
-                    .setEncryptionRequired(true)
-                    .build());
-            fail("Shouldn't be able to insert encrypted entry when KeyStore uninitialized");
-        } catch (KeyStoreException expected) {
-        }
-
-        assertNull(mKeyStore.getEntry(TEST_ALIAS_1, null));
-    }
-
     public void testKeyStore_SetEntry_PrivateKeyEntry_Overwrites_PrivateKeyEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index e75a60f..3f9f758 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -279,7 +279,10 @@
 
         public void performDeviceLock() {
             mLockCredential.sleepDevice();
-            SystemClock.sleep(200);
+            KeyguardManager keyguardManager = (KeyguardManager)getContext().getSystemService(Context.KEYGUARD_SERVICE);
+            for (int i = 0; i < 25 && !keyguardManager.isDeviceLocked(); i++) {
+                SystemClock.sleep(200);
+            }
         }
 
         public void performDeviceUnlock() throws Exception {
diff --git a/tests/tests/location/src/android/location/cts/GnssTestCase.java b/tests/tests/location/src/android/location/cts/GnssTestCase.java
index e1c5e88..a128c95 100644
--- a/tests/tests/location/src/android/location/cts/GnssTestCase.java
+++ b/tests/tests/location/src/android/location/cts/GnssTestCase.java
@@ -16,11 +16,10 @@
 package android.location.cts;
 
 import android.os.Build;
+import android.os.SystemProperties;
 import android.test.AndroidTestCase;
 import android.util.Log;
 
-import com.android.compatibility.common.util.PropertyUtil;
-
 /**
  * Base Test Case class for all Gnss Tests.
  */
@@ -38,7 +37,7 @@
     // On devices using newer hardware, GNSS measurement support is required.
     protected boolean isMeasurementTestStrict() {
         // Enforce strict measurement test on devices with first API level at least P.
-        if (PropertyUtil.getFirstApiLevel() >= Build.VERSION_CODES.P) {
+        if (SystemProperties.getInt("ro.product.first_api_level", 0) >= Build.VERSION_CODES.P) {
             return true;
         }
 
@@ -53,4 +52,4 @@
     public boolean isCtsVerifierTest() {
         return mCtsVerifierTest;
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java b/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java
index 1d77473..926abd8 100644
--- a/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java
@@ -226,6 +226,11 @@
             session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS
                     | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
             session.setCallback(callback, handler);
+            PlaybackState state = new PlaybackState.Builder()
+                    .setState(PlaybackState.STATE_PLAYING, 0, 1.0f).build();
+            // Fake the media session service so this session can take the media key events.
+            session.setPlaybackState(state);
+            session.setActive(true);
 
             // A media playback is also needed to receive media key events.
             Utils.assertMediaPlaybackStarted(context);
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
index 36f1b8a..fd0d37b 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
@@ -502,29 +502,14 @@
     }
 )glsl";
 
-const char* kSsboVertexShaderEs31 = R"glsl(#version 310 es
-    in vec2 aPosition;
-    in float aDepth;
-    uniform mediump float uScale;
+const char* kSsboComputeShaderEs31 = R"glsl(#version 310 es
+    layout(local_size_x = 1) in;
     layout(std430, binding=0) buffer Output {
-        vec2 data[];
+        uint data[];
     } bOutput;
-    out mediump vec2 vTexCoords;
     void main() {
-        bOutput.data[gl_VertexID] = aPosition;
-        vTexCoords = (vec2(1.0) + aPosition) * 0.5;
-        gl_Position.xy = aPosition * uScale;
-        gl_Position.z = aDepth;
-        gl_Position.w = 1.0;
-    }
-)glsl";
-
-const char* kColorFragmentShaderEs3x = R"glsl(
-    precision mediump float;
-    uniform lowp vec4 uColor;
-    out mediump vec4 color;
-    void main() {
-        color = uColor;
+        bOutput.data[gl_GlobalInvocationID.x] =
+            gl_GlobalInvocationID.x * 3u;
     }
 )glsl";
 
@@ -998,6 +983,7 @@
                     internal_format = GL_DEPTH_STENCIL_OES;
                     format = GL_DEPTH_STENCIL;
                     type = GL_UNSIGNED_INT_24_8;
+                    break;
                 default:
                     FAIL() << "Unrecognized GL format"; break;
             }
@@ -1232,8 +1218,9 @@
               mGLVersion / 10, mGLVersion % 10);
         return;
     }
+    const int kBufferElements = 16;
     AHardwareBuffer_Desc desc = GetParam();
-    desc.width = sizeof kQuadPositions;
+    desc.width = kBufferElements * sizeof(int);
     desc.usage = AHARDWAREBUFFER_USAGE_CPU_READ_RARELY | AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;
     if (!SetUpBuffer(desc)) return;
 
@@ -1244,30 +1231,44 @@
     }
 
     // Clear the buffer to zero
-    std::vector<float> zero_data(desc.width / sizeof(float), 0.f);
-    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, desc.width, zero_data.data());
+    std::vector<unsigned int> expected_data(kBufferElements, 0U);
+    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, desc.width, expected_data.data());
     glFinish();
 
-    // Write into the buffer with a shader
-    SetUpFramebuffer(40, 40, 0, kRenderbuffer);
-    SetUpProgram(kSsboVertexShaderEs31, std::string("#version 310 es") + kColorFragmentShaderEs3x,
-                 kQuadPositions, 0.5f);
+    // Write into the buffer with a compute shader
+    GLint status = 0;
+    mProgram = glCreateProgram();
+    GLuint shader = glCreateShader(GL_COMPUTE_SHADER);
+    glShaderSource(shader, 1, &kSsboComputeShaderEs31, nullptr);
+    glCompileShader(shader);
+    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
+    ASSERT_EQ(GL_TRUE, status) << "Compute shader compilation failed";
+    glAttachShader(mProgram, shader);
+    glLinkProgram(mProgram);
+    glGetProgramiv(mProgram, GL_LINK_STATUS, &status);
+    ASSERT_EQ(GL_TRUE, status) << "Shader program linking failed";
+    glDetachShader(mProgram, shader);
+    glDeleteShader(shader);
+    glUseProgram(mProgram);
+    ASSERT_EQ(GLenum{GL_NO_ERROR}, glGetError());
     glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, mBufferObjects[mWhich]);
-    glDrawArrays(GL_TRIANGLES, 0, kQuadVertexCount);
+    glDispatchCompute(kBufferElements, 1, 1);
+    glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);
     glFinish();
     EXPECT_EQ(GLenum{GL_NO_ERROR}, glGetError());
 
     // Inspect the data written into the buffer using CPU access.
     MakeCurrent(0);
-    float* data = nullptr;
+    unsigned int* data = nullptr;
     int result = AHardwareBuffer_lock(mBuffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY,
                                       -1, nullptr, reinterpret_cast<void**>(&data));
     ASSERT_EQ(NO_ERROR, result);
     std::ostringstream s;
-    for (int i = 0; i < 12; ++i) {
+    for (int i = 0; i < kBufferElements; ++i) {
+		expected_data[i] = static_cast<unsigned int>(i * 3);
         s << data[i] << ", ";
     }
-    EXPECT_EQ(0, memcmp(kQuadPositions, data, desc.width)) << s.str();
+    EXPECT_EQ(0, memcmp(expected_data.data(), data, desc.width)) << s.str();
     AHardwareBuffer_unlock(mBuffer, nullptr);
 }
 
diff --git a/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java b/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java
index 24b8f1f..ff022fc 100644
--- a/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java
+++ b/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java
@@ -17,6 +17,7 @@
 package android.hardware.nativehardware.cts;
 
 import android.content.pm.PackageManager;
+import android.content.res.Configuration;
 import android.hardware.HardwareBuffer;
 import android.test.AndroidTestCase;
 
@@ -29,8 +30,13 @@
 
     @CddTest(requirement="7.9.2/C-1-10")
     public void testLayeredBuffersForVr() throws AssertionError {
+        boolean mIsVrHeadset = (getContext().getResources().getConfiguration().uiMode
+            & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET;
+
+        // Some phones upgrading from older Android versions have the high performance VR feature,
+        // but cannot meet this requirement. Only actually check it for standalone VR headsets.
         PackageManager pm = getContext().getPackageManager();
-        if (!pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
+        if (!pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE) || !mIsVrHeadset) {
             return;
         }
         final long flags = HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE | HardwareBuffer.USAGE_GPU_COLOR_OUTPUT;
diff --git a/tests/tests/os/src/android/os/cts/ParcelTest.java b/tests/tests/os/src/android/os/cts/ParcelTest.java
index c65c61b..987ab00 100644
--- a/tests/tests/os/src/android/os/cts/ParcelTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelTest.java
@@ -19,7 +19,11 @@
 import java.io.FileDescriptor;
 import java.io.Serializable;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
 
 import android.content.pm.Signature;
 import android.os.BadParcelableException;
@@ -3225,4 +3229,58 @@
         assertEquals(42, list.get(0).getValue());
         assertEquals(56, list.get(1).getValue());
     }
+
+    public void testMaliciousMapWrite() {
+        class MaliciousMap<K, V> extends HashMap<K, V> {
+            public int fakeSize = 0;
+            public boolean armed = false;
+
+            class FakeEntrySet extends HashSet<Entry<K, V>> {
+                public FakeEntrySet(Collection<? extends Entry<K, V>> c) {
+                    super(c);
+                }
+
+                @Override
+                public int size() {
+                    if (armed) {
+                        // Only return fake size on next call, to mitigate unexpected behavior.
+                        armed = false;
+                        return fakeSize;
+                    } else {
+                        return super.size();
+                    }
+                }
+            }
+
+            @Override
+            public Set<Map.Entry<K, V>> entrySet() {
+                return new FakeEntrySet(super.entrySet());
+            }
+        }
+
+        Parcel parcel = Parcel.obtain();
+
+        // Fake having more Map entries than there really are
+        MaliciousMap map = new MaliciousMap<String, String>();
+        map.fakeSize = 1;
+        map.armed = true;
+        try {
+            parcel.writeMap(map);
+            fail("Should have thrown a BadParcelableException");
+        } catch (BadParcelableException bpe) {
+            // good
+        }
+
+        // Fake having fewer Map entries than there really are
+        map = new MaliciousMap<String, String>();
+        map.put("key", "value");
+        map.fakeSize = 0;
+        map.armed = true;
+        try {
+            parcel.writeMap(map);
+            fail("Should have thrown a BadParcelableException");
+        } catch (BadParcelableException bpe) {
+            // good
+        }
+    }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/CalendarTest.java b/tests/tests/provider/src/android/provider/cts/CalendarTest.java
index 8db5e45..fcd873a 100644
--- a/tests/tests/provider/src/android/provider/cts/CalendarTest.java
+++ b/tests/tests/provider/src/android/provider/cts/CalendarTest.java
@@ -2516,8 +2516,8 @@
         // instances, and it's stored as minutes since midnight in the device's time zone.
         // Things won't be consistent if the event and the device have different ideas about DST.
         String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
-        String testStart = "1999-04-18T00:00:00";
-        String testEnd = "1999-05-16T23:59:59";
+        String testStart = "1999-07-02T00:00:00";
+        String testEnd = "1999-08-04T23:59:59";
         String[] projection = { Instances.BEGIN, Instances.START_MINUTE, Instances.END_MINUTE };
 
         Cursor instances = getInstances(timeZone, testStart, testEnd, projection,
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java
index 18006b2..3a2f670 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java
@@ -29,7 +29,6 @@
     private static final String[] NOT_ALLOWED_FILES = {
             "not_allowed.txt",
             "../A-contacts-db.zip",   // ".." is not allowed.
-            "/A-contacts-db.zip",     // "/" is not allowed
             "-contacts-db.zip",       // no name prefix
             "asdf-contacts-db.zip"};
 
@@ -88,7 +87,7 @@
             return;
         }
 
-        fail("IllegalArgumentException expected but not thrown.");
+        fail("IllegalArgumentException expected but not thrown: " + uri);
     }
 
     private void assertOpenFileDescriptorThrowsError(Uri uri) {
@@ -101,6 +100,6 @@
 
         }
 
-        fail("IllegalArgumentException expected but not thrown.");
+        fail("IllegalArgumentException expected but not thrown: " + uri);
     }
 }
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java b/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java
old mode 100644
new mode 100755
index 45dd3f0..4ea5b59
--- a/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java
@@ -39,7 +39,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class AccessControlTest {
@@ -163,6 +163,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java b/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java
old mode 100644
new mode 100755
index 4a7b7e6..5998cea
--- a/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java
@@ -39,7 +39,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class AccessControlTest {
@@ -162,6 +162,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java b/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java
old mode 100644
new mode 100755
index 3a8971c..cdf8893
--- a/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java
@@ -39,7 +39,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class AccessControlTest {
@@ -172,6 +172,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
old mode 100644
new mode 100755
index 438857d..c9d21bb
--- a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
+++ b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
@@ -42,7 +42,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class OmapiTest {
@@ -159,6 +159,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/security/res/raw/bug_63522067_1_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_1_hevc.mp4
deleted file mode 100644
index 261e173..0000000
--- a/tests/tests/security/res/raw/bug_63522067_1_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_2_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_2_hevc.mp4
deleted file mode 100644
index e8f1c41..0000000
--- a/tests/tests/security/res/raw/bug_63522067_2_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_3_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_3_hevc.mp4
deleted file mode 100644
index ecc10cb..0000000
--- a/tests/tests/security/res/raw/bug_63522067_3_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_4_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_4_hevc.mp4
deleted file mode 100644
index 34851ad..0000000
--- a/tests/tests/security/res/raw/bug_63522067_4_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2016_3828.mp4 b/tests/tests/security/res/raw/cve_2016_3828.mp4
deleted file mode 100755
index 88109cb..0000000
--- a/tests/tests/security/res/raw/cve_2016_3828.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
old mode 100755
new mode 100644
index 1a1a136..a137e67
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -33,8 +33,6 @@
 import android.media.MediaCodec;
 import android.media.MediaCodecInfo;
 import android.media.MediaCodecList;
-import android.media.MediaDrm;
-import android.media.MediaDrm.MediaDrmStateException;
 import android.media.MediaExtractor;
 import android.media.MediaFormat;
 import android.media.MediaMetadataRetriever;
@@ -57,7 +55,6 @@
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.UUID;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -93,11 +90,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_cve_2016_3828() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3828);
-    }
-
-    @SecurityTest
     public void testStagefright_bug_64710074() throws Exception {
         doStagefrightTest(R.raw.bug_64710074);
     }
@@ -545,14 +537,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_bug_63522067() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_63522067_1_hevc, "video/hevc", 320, 420);
-        doStagefrightTestRawBlob(R.raw.bug_63522067_2_hevc, "video/hevc", 320, 420);
-        doStagefrightTestRawBlob(R.raw.bug_63522067_3_hevc, "video/hevc", 320, 420);
-        doStagefrightTestRawBlob(R.raw.bug_63522067_4_hevc, "video/hevc", 320, 420);
-    }
-
-    @SecurityTest
     public void testStagefright_bug_25765591() throws Exception {
         doStagefrightTest(R.raw.bug_25765591);
     }
@@ -618,39 +602,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_bug_37710346() throws Exception {
-        UUID CLEARKEY_SCHEME_UUID = new UUID(0x1077efecc0b24d02L, 0xace33c1e52e2fb4bL);
-
-        String drmInitString = "0000003470737368" +
-                               "01000000" +
-                               "1077efecc0b24d02" +
-                               "ace33c1e52e2fb4b" +
-                               "10000001" +
-                               "60061e017e477e87" +
-                               "7e57d00d1ed00d1e" +
-                               "00000000";
-        int len = drmInitString.length();
-        byte[] drmInitData = new byte[len / 2];
-        for (int i = 0; i < len; i += 2) {
-            drmInitData[i / 2] = (byte) ((Character.digit(drmInitString.charAt(i), 16) << 4) +
-                Character.digit(drmInitString.charAt(i + 1), 16));
-        }
-
-        try {
-            MediaDrm drm = new MediaDrm(CLEARKEY_SCHEME_UUID);
-            byte[] sessionId;
-            String initDataType = "video/mp4";
-
-            sessionId = drm.openSession();
-            MediaDrm.KeyRequest drmRequest = drm.getKeyRequest(sessionId, drmInitData,
-                initDataType, MediaDrm.KEY_TYPE_STREAMING, null);
-        } catch (Exception e) {
-            if (!(e instanceof MediaDrmStateException))
-                fail("media drm server died");
-        }
-    }
-
-    @SecurityTest
     public void testStagefright_cve_2015_3873_b_23248776() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_23248776);
     }
diff --git a/tests/tests/security/src/android/security/cts/VerifiedBootTest.java b/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
index a3209fc..8d388cc 100644
--- a/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
+++ b/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
@@ -21,6 +21,7 @@
 import android.platform.test.annotations.SecurityTest;
 import android.test.AndroidTestCase;
 import com.android.compatibility.common.util.PropertyUtil;
+import com.android.compatibility.common.util.CddTest;
 
 @SecurityTest
 public class VerifiedBootTest extends AndroidTestCase {
@@ -42,6 +43,7 @@
    * A device without the feature flag android.hardware.ram.normal is exempt if
    * it launched on a pre-P level.
    */
+  @CddTest(requirement="9.10/C-1-1,C-2-1")
   public void testVerifiedBootSupport() throws Exception {
     if (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.O_MR1) {
       return;
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
index dde2ce1..a56ab29 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
@@ -26,10 +26,11 @@
 import android.content.pm.PackageManager;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
+import android.graphics.Rect;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.rule.ActivityTestRule;
 import android.util.Log;
-import android.view.KeyEvent;
+import android.view.DisplayCutout;
 import android.view.WindowInsets;
 
 import java.io.File;
@@ -37,6 +38,8 @@
 import java.io.IOException;
 import java.nio.file.FileSystems;
 import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Locale;
 
 public class LightBarTestBase {
 
@@ -45,6 +48,8 @@
     public static final Path DUMP_PATH = FileSystems.getDefault()
             .getPath("/sdcard/LightBarTestBase/");
 
+    private ArrayList<Rect> mCutouts;
+
     protected Bitmap takeStatusBarScreenshot(LightBarBaseActivity activity) {
         Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
         return Bitmap.createBitmap(fullBitmap, 0, 0, activity.getWidth(), activity.getTop());
@@ -144,18 +149,30 @@
         int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
         bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
 
+        loadCutout(activity);
         int backgroundColorPixelCount = 0;
+        int shiftY = activity.getBottom();
         for (int i = 0; i < pixels.length; i++) {
-            if (pixels[i] == backgroundColor) {
+            int x = i % bitmap.getWidth();
+            int y = i / bitmap.getWidth();
+
+            if (pixels[i] == backgroundColor
+                    || isInsideCutout(x, shiftY + y)) {
                 backgroundColorPixelCount++;
             }
         }
         assumeNavigationBarChangesColor(backgroundColorPixelCount, pixels.length);
 
         for (int col = 0; col < bitmap.getWidth(); col++) {
+            if (isInsideCutout(col, shiftY)) {
+                continue;
+            }
+
             if (dividerColor != pixels[col]) {
                 dumpBitmap(bitmap, methodName);
-                fail("Invalid color exptected=" + dividerColor + " actual=" + pixels[col]);
+                fail(String.format(Locale.ENGLISH,
+                        "Invalid color expected= 0x%08x, actual= 0x%08x",
+                        dividerColor, pixels[col]));
             }
         }
     }
@@ -164,4 +181,25 @@
         assumeTrue("Not enough background pixels. The navigation bar may not be able to change "
                 + "color.", backgroundColorPixelCount > 0.3f * totalPixel);
     }
+
+    protected ArrayList loadCutout(LightBarBaseActivity activity) {
+        mCutouts = new ArrayList<>();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(()-> {
+            WindowInsets windowInsets = activity.getRootWindowInsets();
+            DisplayCutout displayCutout = windowInsets.getDisplayCutout();
+            if (displayCutout != null) {
+                mCutouts.addAll(displayCutout.getBoundingRects());
+            }
+        });
+        return mCutouts;
+    }
+
+    protected boolean isInsideCutout(int x, int y) {
+        for (Rect cutout : mCutouts) {
+            if (cutout.contains(x, y)) {
+                return true;
+            }
+        }
+        return false;
+    }
 }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
index 724bca0..5566a0d 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
@@ -20,13 +20,11 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.app.UiAutomation;
 import android.content.Context;
-import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.Color;
 import android.os.SystemClock;
@@ -96,7 +94,7 @@
         Thread.sleep(WAIT_TIME);
 
         Bitmap bitmap = takeStatusBarScreenshot(mActivityRule.getActivity());
-        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
+        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */, 0);
         assertLightStats(bitmap, s);
 
         mNm.cancelAll();
@@ -116,8 +114,9 @@
         injectCanceledTap(x, y);
         Thread.sleep(WAIT_TIME);
 
-        Bitmap bitmap = takeNavigationBarScreenshot(mActivityRule.getActivity());
-        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
+        LightBarActivity activity = mActivityRule.getActivity();
+        Bitmap bitmap = takeNavigationBarScreenshot(activity);
+        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */, activity.getBottom());
         assertLightStats(bitmap, s);
     }
 
@@ -225,7 +224,7 @@
         }
     }
 
-    private Stats evaluateLightBarBitmap(Bitmap bitmap, int background) {
+    private Stats evaluateLightBarBitmap(Bitmap bitmap, int background, int shiftY) {
         int iconColor = 0x99000000;
         int iconPartialColor = 0x3d000000;
 
@@ -247,8 +246,17 @@
         Stats s = new Stats();
         float eps = 0.005f;
 
+        loadCutout(mActivityRule.getActivity());
         float [] hsvPixel = new float[3];
+        int i = 0;
         for (int c : pixels) {
+            int x = i % bitmap.getWidth();
+            int y = i / bitmap.getWidth();
+            i++;
+            if (isInsideCutout(x, shiftY + y)) {
+                continue;
+            }
+
             if (isColorSame(c, background)) {
                 s.backgroundPixels++;
                 continue;
diff --git a/tests/tests/view/AndroidManifest.xml b/tests/tests/view/AndroidManifest.xml
index a9cb2cd..4217959 100644
--- a/tests/tests/view/AndroidManifest.xml
+++ b/tests/tests/view/AndroidManifest.xml
@@ -297,7 +297,7 @@
         </activity>
 
         <activity android:name="android.view.cts.DragDropActivity"
-                  android:screenOrientation="portrait"
+                  android:screenOrientation="locked"
                   android:label="DragDropActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
index 52a0a8d..8b0d4c7 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
@@ -371,6 +371,12 @@
             if (mIsEGLWideGamut && !extensions.contains("EXT_pixel_format_float")) {
                 mEGLExtensionUnsupported = true;
             }
+            // If the extension is present but the device doesn't claim to have a wide color gamut
+            // display then it might not return any actual float formats.
+            if (mIsEGLWideGamut && !mEGLExtensionUnsupported
+                    && !getWindowManager().getDefaultDisplay().isWideColorGamut()) {
+                mEGLExtensionUnsupported = true;
+            }
 
             mEglConfig = chooseEglConfig();
             if (mEglConfig == null) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java b/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
index 68d944b..2996c76 100644
--- a/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
+++ b/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
@@ -69,6 +69,7 @@
     public static final String STOP_LOADING_URL = "webkit/test_stop_loading.html";
     public static final String BLANK_TAG_URL = "webkit/blank_tag.html";
     public static final String PAGE_WITH_LINK_URL = "webkit/page_with_link.html";
+    public static final String URL_IN_PAGE_WITH_LINK = "http://foo.com/";
     // Not a real page, just triggers a 404 response.
     public static final String NON_EXISTENT_PAGE_URL = "webkit/generate_404.html";
     public static final String BAD_IMAGE_PAGE_URL = "webkit/test_bad_image_url.html";
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index ae875a5..8cfaec3 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
@@ -554,6 +554,7 @@
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
         }
+        mSettings.setTextSize(TextSize.NORMAL);
         assertEquals(TextSize.NORMAL, mSettings.getTextSize());
 
         mSettings.setTextSize(TextSize.LARGER);
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 58e59e5..3ce66ac 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -137,6 +137,7 @@
 
         final WebView childWebView = mOnUiThread.createWebView();
 
+        WebViewOnUiThread childWebViewOnUiThread = new WebViewOnUiThread(this, childWebView);
         mOnUiThread.setWebChromeClient(new WebChromeClient() {
             @Override
             public boolean onCreateWindow(
@@ -152,21 +153,26 @@
                 return true;
             }
         });
-        mOnUiThread.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.BLANK_TAG_URL));
+        {
+          final int childCallCount = childWebViewClient.getShouldOverrideUrlLoadingCallCount();
+          mOnUiThread.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.BLANK_TAG_URL));
 
-        new PollingCheck(TEST_TIMEOUT) {
-            @Override
-            protected boolean check() {
-                return childWebViewClient.hasOnPageFinishedCalled();
-            }
-        }.run();
-        assertEquals(mWebServer.getAssetUrl(TestHtmlConstants.PAGE_WITH_LINK_URL),
-                childWebViewClient.getLastShouldOverrideUrl());
+          new PollingCheck(TEST_TIMEOUT) {
+              @Override
+              protected boolean check() {
+                  return childWebViewClient.hasOnPageFinishedCalled();
+              }
+          }.run();
+          new PollingCheck(TEST_TIMEOUT) {
+              @Override
+              protected boolean check() {
+                  return childWebViewClient.getShouldOverrideUrlLoadingCallCount() > childCallCount;
+              }
+          }.run();
+          assertEquals(mWebServer.getAssetUrl(TestHtmlConstants.PAGE_WITH_LINK_URL),
+                  childWebViewClient.getLastShouldOverrideUrl());
+        }
 
-        // Now test a navigation within the page
-        //TODO(hush) Enable this portion when b/12804986 is fixed.
-        /*
-        WebViewOnUiThread childWebViewOnUiThread = new WebViewOnUiThread(this, childWebView);
         final int childCallCount = childWebViewClient.getShouldOverrideUrlLoadingCallCount();
         final int mainCallCount = mainWebViewClient.getShouldOverrideUrlLoadingCallCount();
         clickOnLinkUsingJs("link", childWebViewOnUiThread);
@@ -177,8 +183,8 @@
             }
         }.run();
         assertEquals(mainCallCount, mainWebViewClient.getShouldOverrideUrlLoadingCallCount());
-        assertEquals(TEST_URL, childWebViewClient.getLastShouldOverrideUrl());
-        */
+        assertEquals(
+            TestHtmlConstants.URL_IN_PAGE_WITH_LINK, childWebViewClient.getLastShouldOverrideUrl());
     }
 
     private void clickOnLinkUsingJs(final String linkId, WebViewOnUiThread webViewOnUiThread) {
@@ -781,7 +787,6 @@
         @Override
         public void onLoadResource(WebView view, String url) {
             super.onLoadResource(view, url);
-            assertTrue(mOnPageStartedCalled);
             mOnLoadResourceCalled = true;
         }
 
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index 4bedbb1..f5f3139 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -1361,7 +1361,7 @@
         assertNull(mWebView.getUrl());
         String imgUrl = TestHtmlConstants.SMALL_IMG_URL; // relative
         // Snippet of HTML that will prevent favicon requests to the test server.
-        final String HTML_HEADER = "<html><head><link rel=\"shortcut icon\" href=\"#\" /></head>";
+        final String HTML_HEADER = "<html><head><link rel=\"shortcut icon\" href=\"%23\" /></head>";
 
         // Trying to resolve a relative URL against a data URL without a base URL
         // will fail and we won't make a request to the test web server.
@@ -1968,8 +1968,8 @@
         final String imgUrl = mWebServer.getAssetUrl(TestHtmlConstants.LARGE_IMG_URL);
         mOnUiThread.loadDataAndWaitForCompletion(
                 "<html><head><title>Title</title><style type=\"text/css\">"
-                + "#imgElement { -webkit-transform: translate3d(0,0,1); }"
-                + "#imgElement.finish { -webkit-transform: translate3d(0,0,0);"
+                + "%23imgElement { -webkit-transform: translate3d(0,0,1); }"
+                + "%23imgElement.finish { -webkit-transform: translate3d(0,0,0);"
                 + " -webkit-transition-duration: 1ms; }</style>"
                 + "<script type=\"text/javascript\">function imgLoad() {"
                 + "imgElement = document.getElementById('imgElement');"
diff --git a/tests/vr/jni/VrExtensionsJni.cpp b/tests/vr/jni/VrExtensionsJni.cpp
index 4ab4e2a..75031ce 100644
--- a/tests/vr/jni/VrExtensionsJni.cpp
+++ b/tests/vr/jni/VrExtensionsJni.cpp
@@ -86,10 +86,19 @@
     ASSERT((a) != (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
 #define ASSERT_GT(a, b) \
     ASSERT((a) > (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
-#define ASSERT_NEAR(a, b, delta)                     \
-    ASSERT((a - delta) <= (b) && (b) <= (a + delta), \
+#define ASSERT_NEAR_RGBA(a, b, delta) \
+    ASSERT(areNearRgba(a, b, delta),  \
            "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
 
+bool areNearRgba(int32_t actual, int32_t expected, int delta) {
+    for (int shift = 0; shift < 32; shift += 8) {
+        if (std::abs((actual >> shift & 0xFF) - (expected >> shift & 0xFF)) > delta) {
+            return false;
+        }
+    }
+    return true;
+}
+
 void fail(JNIEnv* env, const char* format, ...) {
     va_list args;
     va_start(args, format);
@@ -107,8 +116,8 @@
                               int nsamples) {
     ASSERT_GT(desc.layers, 1);
     AHardwareBuffer* hwbuffer = nullptr;
-    int error = AHardwareBuffer_allocate(&desc, &hwbuffer);
-    ASSERT_FALSE(error);
+    // If the format is unsupported and allocation fails, skip the test.
+    if (AHardwareBuffer_allocate(&desc, &hwbuffer) != NO_ERROR) return;
     // Create EGLClientBuffer from the AHardwareBuffer.
     EGLClientBuffer native_buffer = eglGetNativeClientBufferANDROID(hwbuffer);
     ASSERT_TRUE(native_buffer);
@@ -638,20 +647,20 @@
     uint32_t middle_pixel;
     // First do a sanity check with plain old pre-linearized textures.
     testLinearMagnification(env, 0, &middle_pixel);
-    ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
     testLinearMagnification(env, SrgbFlag::kHardwareBuffer, &middle_pixel);
-    ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
     // Try a "normally allocated" OpenGL texture with an sRGB source format.
     testLinearMagnification(env, SrgbFlag::kSrgbFormat, &middle_pixel);
-    ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
+    ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
     // Try EGL_EXT_image_gl_colorspace.
     if (egl_colorspace_supported) {
         testLinearMagnification(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceDefault, &middle_pixel);
-        ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
         testLinearMagnification(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceLinear, &middle_pixel);
-        ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
         testLinearMagnification(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceSrgb, &middle_pixel);
-        ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
+        ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
     }
 
     // Blending test.
@@ -660,19 +669,19 @@
     uint32_t final_color;
     // First do a sanity check with plain old pre-linearized textures.
     testFramebufferBlending(env, 0, &final_color);
-    ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
     testFramebufferBlending(env, SrgbFlag::kHardwareBuffer, &final_color);
-    ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
     // Try a "normally allocated" OpenGL texture with an sRGB source format.
     testFramebufferBlending(env, SrgbFlag::kSrgbFormat, &final_color);
-    ASSERT_NEAR(final_color, kExpectedBlendedPixel_Srgb, 1);
+    ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_Srgb, 1);
     // Try EGL_EXT_image_gl_colorspace.
     if (egl_colorspace_supported) {
         testFramebufferBlending(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceDefault, &final_color);
-        ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
         testFramebufferBlending(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceLinear, &final_color);
-        ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
         testFramebufferBlending(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceSrgb, &final_color);
-        ASSERT_NEAR(final_color, kExpectedBlendedPixel_Srgb, 1);
+        ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_Srgb, 1);
     }
 }