Merge "CameraITS: make RAW in test_exposure for debug purposes" into oc-dev
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index 54fdb08..a8b9863 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -391,8 +391,6 @@
         s,e,_,_,_ = cam.do_3a(get_results=True, do_af=False)
         req = its.objects.manual_capture_request(s, e)
         fps = 30
-        if "60fps" in sys.argv:
-            fps = 60
         req["android.control.aeTargetFpsRange"] = [fps, fps]
         print "Capturing %dx%d with sens. %d, exp. time %.1fms" % (
                 W, H, s, e*NSEC_TO_MSEC)
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index a613050..1787b42 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -48,6 +48,7 @@
                   android:required="false" />
     <uses-feature android:name="android.software.vr.mode" android:required="false" />
     <uses-feature android:name="android.hardware.vr.high_performance" android:required="false"/>
+    <uses-feature android:name="android.software.companion_device_setup" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.RECORD_AUDIO" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 63968b6..d9b87d16 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -3018,9 +3018,13 @@
         5) In the screen that opens, verify that you are not told that your administrator installed any apps.\n
         6) Use the Back button to return to this page.\n
         7) Press the Install button.\n
-        8) Repeat steps (4) through (6), verifying that in step (5), you are told now that your administrator installed at least one app.\n
-        9) Press the Uninstall button.\n
-        10) Issue the following command on the host:\n
+        8) Press the Open Settings button.\n
+        9) In the screen that opens, verify that you are told now that your administrator installed at least one app.\n
+        10) Tap on that information. Verify that a list of apps installed shows.\n
+        11) Verify that the list contains the CTS Robot app.\n
+        12) Use the Back button to return to this page.\n
+        13) Press the Uninstall button.\n
+        14) Issue the following command on the host:\n
             adb shell rm /sdcard/NotificationBot.apk
     </string>
     <string name="enterprise_privacy_install">Install</string>
@@ -3036,7 +3040,7 @@
         6) Press the Open Settings button.\n
         7) In the screen that opens, verify that you are told now that your administrator has granted location access to at least one app.\n
         8) Tap on that information. Verify that a list of apps which have location access shows.\n
-        9) Verify that the list indicates CTS Verifier\'s location access was enabled by your administrator.\n
+        9) Verify that the list contains the CTS Verifier app.\n
         10) Use the Back button to return to this page.\n
         11) Press the Reset button.
     </string>
@@ -3053,7 +3057,7 @@
         6) Press the Open Settings button.\n
         7) In the screen that opens, verify that you are told now that your administrator has granted microphone access to at least one app.\n
         8) Tap on that information. Verify that a list of apps that have microphone access shows.\n
-        9) Verify that the list indicates CTS Verifier\'s microphone access was enabled by your administrator.\n
+        9) Verify that the list contains the CTS Verifier app.\n
         10) Use the Back button to return to this page.\n
         11) Press the Reset button.
     </string>
@@ -3068,7 +3072,7 @@
         6) Press the Open Settings button.\n
         7) In the screen that opens, verify that you are told now that your administrator has granted camera access to at least one app.\n
         8) Tap on that information. Verify that a list of apps that have camera access shows.\n
-        9) Verify that the list indicates CTS Verifier\'s camera access was enabled by your administrator.\n
+        9) Verify that the list contains the CTS Verifier app.\n
         10) Use the Back button to return to this page.\n
         11) Press the Reset button.
     </string>
@@ -3080,8 +3084,12 @@
         3) In the screen that opens, verify that you are not told that your administrator set any default apps.\n
         4) Use the Back button to return to this page.\n
         5) Press the Set Default Apps button.\n
-        6) Repeat steps (2) through (4), verifying that in step (3), you are told now that your administrator has set seven default apps.\n
-        7) Press the Reset button.
+        6) Press the Open Settings button.\n
+        7) In the screen that opens, verify that you are now told that your administrator has set 7 default apps.\n
+        8) Tap on that information. Verify that a list of default apps shows, with 7 elements in it.\n
+        9) Verify that each element shows the CTS Verifier is the default app.\n
+        10) Use the Back button to return to this page.\n
+        11) Press the Reset button.
     </string>
     <string name="enterprise_privacy_set_default_apps">Set Default Apps</string>
     <string name="enterprise_privacy_default_ime">Default keyboard</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java
index 19adda0..635d066 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java
@@ -290,7 +290,7 @@
                         : discoverySession.createNetworkSpecifierPassphrase(peerHandle,
                                 PASSPHRASE)).build();
         CallbackUtils.NetworkCb networkCb = new CallbackUtils.NetworkCb();
-        cm.requestNetwork(nr, CALLBACK_TIMEOUT_SEC * 1000, networkCb);
+        cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
         mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_requested));
         if (DBG) Log.d(TAG, "executeTestSubscriber: requested network");
         boolean networkAvailable = networkCb.waitForNetwork();
@@ -378,7 +378,7 @@
                         : discoverySession.createNetworkSpecifierPassphrase(peerHandle,
                                 PASSPHRASE)).build();
         CallbackUtils.NetworkCb networkCb = new CallbackUtils.NetworkCb();
-        cm.requestNetwork(nr, CALLBACK_TIMEOUT_SEC * 1000, networkCb);
+        cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
         mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_requested));
         if (DBG) Log.d(TAG, "executeTestPublisher: requested network");
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java
index d707c6a..b054781 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java
@@ -273,7 +273,7 @@
                                 WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER, peerMac,
                                 PASSPHRASE)).build();
         CallbackUtils.NetworkCb networkCb = new CallbackUtils.NetworkCb();
-        cm.requestNetwork(nr, CALLBACK_TIMEOUT_SEC * 1000, networkCb);
+        cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
         mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_requested));
         if (DBG) Log.d(TAG, "executeTestResponder: requested network");
         boolean networkAvailable = networkCb.waitForNetwork();
@@ -405,7 +405,7 @@
                                 WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR, peerMac,
                                 PASSPHRASE)).build();
         CallbackUtils.NetworkCb networkCb = new CallbackUtils.NetworkCb();
-        cm.requestNetwork(nr, CALLBACK_TIMEOUT_SEC * 1000, networkCb);
+        cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
         mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_requested));
         if (DBG) Log.d(TAG, "executeTestInitiator: requested network");
         boolean networkAvailable = networkCb.waitForNetwork();
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BitmapUtils.java b/common/device-side/util/src/com/android/compatibility/common/util/BitmapUtils.java
index 5799e70..7f94d6f 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/BitmapUtils.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BitmapUtils.java
@@ -21,13 +21,19 @@
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.CompressFormat;
 import android.graphics.Color;
+import android.util.Log;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
 import java.lang.reflect.Method;
 import java.util.Random;
 
 public class BitmapUtils {
+    private static final String TAG = "BitmapUtils";
+
     private BitmapUtils() {}
 
     // Compares two bitmaps by pixels.
@@ -67,11 +73,7 @@
 
     public static Bitmap generateWhiteBitmap(int width, int height) {
         final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
-        for (int x = 0; x < width; x++) {
-            for (int y = 0; y < height; y++) {
-                bmp.setPixel(x, y, Color.WHITE);
-            }
-        }
+        bmp.eraseColor(Color.WHITE);
         return bmp;
     }
 
@@ -89,4 +91,38 @@
         byte[] bitmapData = bos.toByteArray();
         return new ByteArrayInputStream(bitmapData);
     }
+
+    private static void logIfBitmapSolidColor(String fileName, Bitmap bitmap) {
+        int firstColor = bitmap.getPixel(0, 0);
+        for (int x = 0; x < bitmap.getWidth(); x++) {
+            for (int y = 0; y < bitmap.getHeight(); y++) {
+                if (bitmap.getPixel(x, y) != firstColor) {
+                    return;
+                }
+            }
+        }
+
+        Log.w(TAG, String.format("%s entire bitmap color is %x", fileName, firstColor));
+    }
+
+    public static void saveBitmap(Bitmap bitmap, String directoryName, String fileName) {
+        new File(directoryName).mkdirs(); // create dirs if needed
+
+        Log.d(TAG, "Saving file: " + fileName + " in directory: " + directoryName);
+
+        if (bitmap == null) {
+            Log.d(TAG, "File not saved, bitmap was null");
+            return;
+        }
+
+        logIfBitmapSolidColor(fileName, bitmap);
+
+        File file = new File(directoryName, fileName);
+        try (FileOutputStream fileStream = new FileOutputStream(file)) {
+            bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* ignored for PNG */, fileStream);
+            fileStream.flush();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
 }
diff --git a/common/host-side/tradefed/res/report/compatibility_result.xsl b/common/host-side/tradefed/res/report/compatibility_result.xsl
index a0c337a..870f994 100644
--- a/common/host-side/tradefed/res/report/compatibility_result.xsl
+++ b/common/host-side/tradefed/res/report/compatibility_result.xsl
@@ -134,8 +134,8 @@
                         <xsl:for-each select="Result/Module">
                             <tr>
                                 <td>
-                                    <xsl:variable name="href"><xsl:value-of select="@name"/> - <xsl:value-of select="@abi"/></xsl:variable>
-                                    <a href="#{$href}"><xsl:value-of select="@name"/> - <xsl:value-of select="@abi"/></a>
+                                    <xsl:variable name="href"><xsl:value-of select="@abi"/>&#xA0;<xsl:value-of select="@name"/></xsl:variable>
+                                    <a href="#{$href}"><xsl:value-of select="@abi"/>&#xA0;<xsl:value-of select="@name"/></a>
                                 </td>
                                 <td>
                                     <xsl:value-of select="count(TestCase/Test[@result = 'pass'])"/>
@@ -195,8 +195,8 @@
                     <table class="testdetails">
                         <tr>
                             <td class="module" colspan="3">
-                                <xsl:variable name="href"><xsl:value-of select="@name"/> - <xsl:value-of select="@abi"/></xsl:variable>
-                                <a name="{$href}"><xsl:value-of select="@name"/> - <xsl:value-of select="@abi"/></a>
+                                <xsl:variable name="href"><xsl:value-of select="@abi"/>&#xA0;<xsl:value-of select="@name"/></xsl:variable>
+                                <a name="{$href}"><xsl:value-of select="@abi"/>&#xA0;<xsl:value-of select="@name"/></a>
                             </td>
                         </tr>
 
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
index e0ac96f..77513c5 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
@@ -42,6 +42,10 @@
     private static final String EPHEMERAL_2_APK = "CtsEphemeralTestsEphemeralApp2.apk";
     private static final String EPHEMERAL_2_PKG = "com.android.cts.ephemeralapp2";
 
+    // a normally installed application with implicitly exposed components
+    private static final String IMPLICIT_APK = "CtsEphemeralTestsImplicitApp.apk";
+    private static final String IMPLICIT_PKG = "com.android.cts.implicitapp";
+
     // a normally installed application with no exposed components
     private static final String UNEXPOSED_APK = "CtsEphemeralTestsUnexposedApp.apk";
     private static final String UNEXPOSED_PKG = "com.android.cts.unexposedapp";
@@ -143,6 +147,7 @@
     private void installTestPackages() throws Exception {
         installApp(NORMAL_APK);
         installApp(UNEXPOSED_APK);
+        installApp(IMPLICIT_APK);
         installEphemeralApp(EPHEMERAL_1_APK);
         installEphemeralApp(EPHEMERAL_2_APK);
     }
@@ -150,6 +155,7 @@
     private void uninstallTestPackages() throws Exception {
         getDevice().uninstallPackage(NORMAL_PKG);
         getDevice().uninstallPackage(UNEXPOSED_PKG);
+        getDevice().uninstallPackage(IMPLICIT_PKG);
         getDevice().uninstallPackage(EPHEMERAL_1_PKG);
         getDevice().uninstallPackage(EPHEMERAL_2_PKG);
     }
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 a047732..37744fa 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
@@ -317,7 +317,7 @@
                 .createDeviceProtectedStorageContext();
         final File probe = new File(otherContext.getFilesDir(),
                 getBootCount() + "." + action);
-        for (int i = 0; i < 60; i++) {
+        for (int i = 0; i < 150; i++) {
             Log.d(TAG, "Waiting for " + probe + "...");
             if (probe.exists()) {
                 return;
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
index 260f37a..8f44f89 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
@@ -392,9 +392,17 @@
 //            startViewIntent.addCategory(Intent.CATEGORY_BROWSABLE);
 //            startViewIntent.setData(Uri.parse("https://cts.google.com/normal"));
 //            InstrumentationRegistry.getContext().startActivity(startViewIntent, null /*options*/);
-//            final BroadcastResult testResult = getResult();
-//            assertThat("com.android.cts.normalapp", is(testResult.packageName));
-//            assertThat("NormalWebActivity", is(testResult.activityName));
+//            final TestResult testResult = getResult();
+//            assertThat(testResult.getPackageName(),
+//                    is("com.android.cts.normalapp"));
+//            assertThat(testResult.getComponentName(),
+//                    is("NormalWebActivity"));
+//            assertThat(testResult.getStatus(),
+//                    is("PASS"));
+//            assertThat(testResult.getEphemeralPackageInfoExposed(),
+//                    is(false));
+//            assertThat(testResult.getException(),
+//                    is(nullValue()));
 //        }
 
         // We don't attempt to start the service since it will merely return and not
@@ -447,7 +455,7 @@
 
     @Test
     public void testStartExposed() throws Exception {
-        // start the exposed activity
+        // start the explicitly exposed activity
         {
             final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
             InstrumentationRegistry
@@ -465,7 +473,7 @@
                     is(nullValue()));
         }
 
-        // start the exposed activity; directed package
+        // start the explicitly exposed activity; directed package
         {
             final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
             startExposedIntent.setPackage("com.android.cts.normalapp");
@@ -484,7 +492,7 @@
                     is(nullValue()));
         }
 
-        // start the exposed activity; directed component
+        // start the explicitly exposed activity; directed component
         {
             final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
             startExposedIntent.setComponent(new ComponentName(
@@ -504,6 +512,34 @@
                     is(nullValue()));
         }
 
+        // start the implicitly exposed activity; directed package
+        {
+            try {
+                final Intent startExposedIntent = new Intent(Intent.ACTION_VIEW);
+                startExposedIntent.setPackage("com.android.cts.implicitapp");
+                startExposedIntent.addCategory(Intent.CATEGORY_BROWSABLE);
+                startExposedIntent.setData(Uri.parse("https://cts.google.com/implicit"));
+                InstrumentationRegistry
+                        .getContext().startActivity(startExposedIntent, null /*options*/);
+                fail("activity started");
+            } catch (ActivityNotFoundException expected) { }
+        }
+
+        // start the implicitly exposed activity; directed component
+        {
+            try {
+                final Intent startExposedIntent = new Intent(Intent.ACTION_VIEW);
+                startExposedIntent.setComponent(new ComponentName(
+                        "com.android.cts.implicitapp",
+                        "com.android.cts.implicitapp.ImplicitActivity"));
+                startExposedIntent.addCategory(Intent.CATEGORY_BROWSABLE);
+                startExposedIntent.setData(Uri.parse("https://cts.google.com/implicit"));
+                InstrumentationRegistry
+                        .getContext().startActivity(startExposedIntent, null /*options*/);
+                fail("activity started");
+            } catch (ActivityNotFoundException expected) { }
+        }
+
         // start the exposed service; directed package
         {
             final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
@@ -879,19 +915,28 @@
     @Test
     public void testPackageInfo() throws Exception {
         PackageInfo info;
-        // Test own package info.
+        // own package info
         info = InstrumentationRegistry.getContext().getPackageManager()
                 .getPackageInfo("com.android.cts.ephemeralapp1", 0);
         assertThat(info.packageName,
                 is("com.android.cts.ephemeralapp1"));
 
-        // Test exposed app package info.
+        // exposed application package info
         info = InstrumentationRegistry.getContext().getPackageManager()
                 .getPackageInfo("com.android.cts.normalapp", 0);
         assertThat(info.packageName,
                 is("com.android.cts.normalapp"));
 
-        // Test unexposed app package info not accessible.
+        // implicitly exposed application package info not accessible
+        try {
+            info = InstrumentationRegistry.getContext().getPackageManager()
+                    .getPackageInfo("com.android.cts.implicitapp", 0);
+            fail("Instant apps should not be able to access PackageInfo for an app that does not" +
+                    " expose itself to Instant Apps.");
+        } catch (PackageManager.NameNotFoundException expected) {
+        }
+
+        // unexposed application package info not accessible
         try {
             info = InstrumentationRegistry.getContext().getPackageManager()
                     .getPackageInfo("com.android.cts.unexposedapp", 0);
@@ -899,7 +944,8 @@
                     " expose itself to Instant Apps.");
         } catch (PackageManager.NameNotFoundException expected) {
         }
-        // Test Instant App (with visibleToInstantApp components) still isn't accessible.
+
+        // instant application (with visibleToInstantApp component) package info not accessible
         try {
             info = InstrumentationRegistry.getContext().getPackageManager()
                     .getPackageInfo("com.android.cts.ephemeralapp2", 0);
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk
new file mode 100644
index 0000000..453dbcb
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk
@@ -0,0 +1,37 @@
+#
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-aia-util \
+    android-support-test \
+    legacy-android-test
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+LOCAL_PACKAGE_NAME := CtsEphemeralTestsImplicitApp
+
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/AndroidManifest.xml
new file mode 100644
index 0000000..f202a0a
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/AndroidManifest.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.cts.implicitapp">
+    <uses-sdk
+        android:minSdkVersion="24" />
+
+    <application
+        android:label="@string/app_name">
+        <uses-library android:name="android.test.runner" />
+        <activity
+            android:name=".ImplicitActivity"
+            android:theme="@android:style/Theme.NoDisplay">
+            <!-- TEST: implicitly exposes this activity to instant apps -->
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.BROWSABLE" />
+                <data android:scheme="https" />
+                <data android:host="cts.google.com" />
+                <data android:path="/implicit" />
+            </intent-filter>
+        </activity>
+    </application>
+
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.cts.implicitapp" />
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/res/values/strings.xml b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/res/values/strings.xml
new file mode 100644
index 0000000..90393aa
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/res/values/strings.xml
@@ -0,0 +1,18 @@
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources>
+  <string name="app_name">ImplicitlyExposedApp</string>
+</resources>
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/src/com/android/cts/implicitapp/ImplicitActivity.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/src/com/android/cts/implicitapp/ImplicitActivity.java
new file mode 100644
index 0000000..feffd84
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/src/com/android/cts/implicitapp/ImplicitActivity.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.implicitapp;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.ResolveInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.android.cts.util.TestResult;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.List;
+
+public class ImplicitActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        boolean canAccessInstantApp = false;
+        String exception = null;
+        try {
+            canAccessInstantApp = tryAccessingInstantApp();
+        } catch (Throwable t) {
+            exception = t.getClass().getName();
+        }
+
+        TestResult.getBuilder()
+                .setPackageName("com.android.cts.implicitapp")
+                .setComponentName("ImplicitActivity")
+                .setStatus("PASS")
+                .setException(exception)
+                .setEphemeralPackageInfoExposed(canAccessInstantApp)
+                .build()
+                .broadcast(this);
+        finish();
+    }
+
+    private boolean tryAccessingInstantApp() throws NameNotFoundException {
+        final PackageInfo info = getPackageManager()
+                .getPackageInfo("com.android.cts.ephemeralapp1", 0 /*flags*/);
+        return (info != null);
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java b/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java
index 9778f12..4a4eef1 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/StorageTest.java
@@ -22,6 +22,7 @@
 import static com.android.cts.storageapp.Utils.DATA_EXT;
 import static com.android.cts.storageapp.Utils.DATA_INT;
 import static com.android.cts.storageapp.Utils.MB_IN_BYTES;
+import static com.android.cts.storageapp.Utils.PKG_B;
 import static com.android.cts.storageapp.Utils.TAG;
 import static com.android.cts.storageapp.Utils.assertMostlyEquals;
 import static com.android.cts.storageapp.Utils.getSizeManual;
@@ -29,11 +30,15 @@
 import static com.android.cts.storageapp.Utils.shouldHaveQuota;
 import static com.android.cts.storageapp.Utils.useSpace;
 
+import android.app.usage.StorageStats;
+import android.app.usage.StorageStatsManager;
 import android.content.ComponentName;
 import android.content.Context;
+import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.os.Environment;
 import android.os.ParcelFileDescriptor;
+import android.os.UserHandle;
 import android.os.storage.StorageManager;
 import android.system.Os;
 import android.test.InstrumentationTestCase;
@@ -47,7 +52,6 @@
  * Client app for verifying storage behaviors.
  */
 public class StorageTest extends InstrumentationTestCase {
-
     private Context getContext() {
         return getInstrumentation().getContext();
     }
@@ -85,6 +89,7 @@
      */
     public void testVerifySpaceApi() throws Exception {
         final StorageManager sm = getContext().getSystemService(StorageManager.class);
+        final StorageStatsManager stats = getContext().getSystemService(StorageStatsManager.class);
 
         final long cacheSize = sm.getCacheSizeBytes(
                 sm.getUuidForPath(getContext().getCacheDir()));
@@ -96,6 +101,40 @@
             assertMostlyEquals(CACHE_INT, cacheSize);
             assertMostlyEquals(CACHE_EXT, extCacheSize);
         }
+
+        // Verify APIs that don't require any special permissions
+        assertTrue(stats.getTotalBytes(StorageManager.UUID_DEFAULT) >= Environment
+                .getDataDirectory().getTotalSpace());
+        assertTrue(stats.getFreeBytes(StorageManager.UUID_DEFAULT) >= Environment
+                .getDataDirectory().getUsableSpace());
+
+        // Verify that we can see our own stats, and that they look sane
+        ApplicationInfo ai = getContext().getApplicationInfo();
+        final StorageStats pstats = stats.queryStatsForPackage(ai.storageUuid, ai.packageName,
+                UserHandle.getUserHandleForUid(ai.uid));
+        final StorageStats ustats = stats.queryStatsForUid(ai.storageUuid, ai.uid);
+        assertEquals(cacheSize, pstats.getCacheBytes());
+        assertEquals(cacheSize, ustats.getCacheBytes());
+
+        // Verify that other packages are off-limits
+        ai = getContext().getPackageManager().getApplicationInfo(PKG_B, 0);
+        try {
+            stats.queryStatsForPackage(ai.storageUuid, ai.packageName,
+                    UserHandle.getUserHandleForUid(ai.uid));
+            fail("Unexpected access");
+        } catch (SecurityException expected) {
+        }
+        try {
+            stats.queryStatsForUid(ai.storageUuid, ai.uid);
+            fail("Unexpected access");
+        } catch (SecurityException expected) {
+        }
+        try {
+            stats.queryExternalStatsForUser(StorageManager.UUID_DEFAULT,
+                    android.os.Process.myUserHandle());
+            fail("Unexpected access");
+        } catch (SecurityException expected) {
+        }
     }
 
     public void testVerifyQuotaApi() throws Exception {
@@ -116,19 +155,19 @@
         final UUID extUuid = sm.getUuidForPath(extDir);
 
         assertTrue("Apps must be able to allocate internal space",
-                sm.getAllocatableBytes(filesUuid, 0) > 10 * MB_IN_BYTES);
+                sm.getAllocatableBytes(filesUuid) > 10 * MB_IN_BYTES);
         assertTrue("Apps must be able to allocate external space",
-                sm.getAllocatableBytes(extUuid, 0) > 10 * MB_IN_BYTES);
+                sm.getAllocatableBytes(extUuid) > 10 * MB_IN_BYTES);
 
         // Should always be able to allocate 1MB indirectly
-        sm.allocateBytes(filesUuid, 1 * MB_IN_BYTES, 0);
+        sm.allocateBytes(filesUuid, 1 * MB_IN_BYTES);
 
         // Should always be able to allocate 1MB directly
         final File filesFile = makeUniqueFile(filesDir);
         assertEquals(0L, filesFile.length());
         try (ParcelFileDescriptor pfd = ParcelFileDescriptor.open(filesFile,
                 ParcelFileDescriptor.parseMode("rwt"))) {
-            sm.allocateBytes(pfd.getFileDescriptor(), 1 * MB_IN_BYTES, 0);
+            sm.allocateBytes(pfd.getFileDescriptor(), 1 * MB_IN_BYTES);
         }
         assertEquals(1 * MB_IN_BYTES, filesFile.length());
     }
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/Utils.java b/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/Utils.java
index e47f6ed..2e43a14 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/Utils.java
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/src/com/android/cts/storageapp/Utils.java
@@ -16,7 +16,6 @@
 
 package com.android.cts.storageapp;
 
-import android.app.usage.StorageStatsManager;
 import android.content.Context;
 import android.system.Os;
 import android.system.OsConstants;
@@ -41,6 +40,9 @@
 public class Utils {
     public static final String TAG = "StorageApp";
 
+    public static final String PKG_A = "com.android.cts.storageapp_a";
+    public static final String PKG_B = "com.android.cts.storageapp_b";
+
     // You will pry my kibibytes from my cold dead hands! But to make test
     // results easier to debug, we'll use kilobytes...
     public static final long KB_IN_BYTES = 1000;
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java b/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
index 4f8b151..de13476 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
@@ -21,6 +21,8 @@
 import static com.android.cts.storageapp.Utils.CACHE_ALL;
 import static com.android.cts.storageapp.Utils.DATA_ALL;
 import static com.android.cts.storageapp.Utils.MB_IN_BYTES;
+import static com.android.cts.storageapp.Utils.PKG_A;
+import static com.android.cts.storageapp.Utils.PKG_B;
 import static com.android.cts.storageapp.Utils.TAG;
 import static com.android.cts.storageapp.Utils.assertAtLeast;
 import static com.android.cts.storageapp.Utils.assertMostlyEquals;
@@ -65,9 +67,6 @@
  */
 public class StorageStatsTest extends InstrumentationTestCase {
 
-    private static final String PKG_A = "com.android.cts.storageapp_a";
-    private static final String PKG_B = "com.android.cts.storageapp_b";
-
     private Context getContext() {
         return getInstrumentation().getContext();
     }
@@ -230,7 +229,7 @@
         final File filesDir = context.getFilesDir();
         final UUID filesUuid = sm.getUuidForPath(filesDir);
 
-        final long beforeAllocatable = sm.getAllocatableBytes(filesUuid, 0);
+        final long beforeAllocatable = sm.getAllocatableBytes(filesUuid);
         final long beforeFree = stats.getFreeBytes(UUID_DEFAULT);
         final long beforeRaw = filesDir.getUsableSpace();
 
@@ -250,12 +249,12 @@
         // disk space.
         if (stats.isQuotaSupported(UUID_DEFAULT)) {
             assertMostlyEquals(beforeAllocatable,
-                    sm.getAllocatableBytes(filesUuid, 0), 10 * MB_IN_BYTES);
+                    sm.getAllocatableBytes(filesUuid), 10 * MB_IN_BYTES);
             assertMostlyEquals(beforeFree,
                     stats.getFreeBytes(UUID_DEFAULT), 10 * MB_IN_BYTES);
         } else {
             assertMostlyEquals(beforeAllocatable - totalAllocated,
-                    sm.getAllocatableBytes(filesUuid, 0), 10 * MB_IN_BYTES);
+                    sm.getAllocatableBytes(filesUuid), 10 * MB_IN_BYTES);
             assertMostlyEquals(beforeFree - totalAllocated,
                     stats.getFreeBytes(UUID_DEFAULT), 10 * MB_IN_BYTES);
         }
@@ -268,7 +267,7 @@
         // Allocate some space for ourselves, which should trim away at
         // over-quota app first, even though its files are newer.
         final long clear1 = filesDir.getUsableSpace() + (targetB / 2);
-        sm.allocateBytes(filesUuid, clear1, 0);
+        sm.allocateBytes(filesUuid, clear1);
 
         assertMostlyEquals(targetA, getCacheBytes(PKG_A, user));
         assertMostlyEquals(targetB / 2, getCacheBytes(PKG_B, user), 2 * MB_IN_BYTES);
@@ -278,7 +277,7 @@
         // they're tied for cache ratios, we expect to clear about half of the
         // remaining space from each of them.
         final long clear2 = filesDir.getUsableSpace() + (targetB / 2);
-        sm.allocateBytes(filesUuid, clear2, 0);
+        sm.allocateBytes(filesUuid, clear2);
 
         assertMostlyEquals(targetA / 2, getCacheBytes(PKG_A, user), 2 * MB_IN_BYTES);
         assertMostlyEquals(targetA / 2, getCacheBytes(PKG_B, user), 2 * MB_IN_BYTES);
@@ -322,7 +321,7 @@
         tomb.setLastModified(tombTime);
 
         final long clear1 = group.getUsableSpace() + (8 * MB_IN_BYTES);
-        sm.allocateBytes(sm.getUuidForPath(group), clear1, 0);
+        sm.allocateBytes(sm.getUuidForPath(group), clear1);
 
         assertTrue(a.exists());
         assertTrue(b.exists());
diff --git a/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java b/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java
index ce8f760..2fc3e1e 100644
--- a/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java
+++ b/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java
@@ -263,7 +263,7 @@
         while (owner.startsWith(" ")) {
             owner = owner.substring(1);
         }
-        executePush(localProfileFile.getAbsolutePath(), targetPath);
+        executePush(localProfileFile.getAbsolutePath(), targetPath, targetDir);
         executeSuShellAdbCommand(0, "chown", owner, targetPath);
         // Verify that the file was written successfully
         assertTrue("failed to create profile file", doesFileExist(targetPath));
@@ -352,11 +352,61 @@
         return lines;
     }
 
-    private void executePush(String hostPath, String targetPath)
+    private String getSelinuxLabel(String path) throws DeviceNotAvailableException {
+        // ls -aZ (-a so it sees directories, -Z so it prints the label).
+        String[] res = executeSuShellAdbCommand(String.format(
+            "ls -aZ '%s'", path));
+
+        if (res.length == 0) {
+          return null;
+        }
+
+        // For directories, it will print many outputs. Filter to first line which contains '.'
+        // The target line will look like
+        //      "u:object_r:shell_data_file:s0 /data/local/tmp/android.cts.compilation.primary.prof"
+        // Remove the second word to only return "u:object_r:shell_data_file:s0".
+
+        return res[0].replaceAll("\\s+.*","");  // remove everything following the first whitespace
+    }
+
+    private void checkSelinuxLabelMatches(String a, String b) throws DeviceNotAvailableException {
+      String labelA = getSelinuxLabel(a);
+      String labelB = getSelinuxLabel(b);
+
+      assertEquals("expected the selinux labels to match", labelA, labelB);
+    }
+
+    private void executePush(String hostPath, String targetPath, String targetDirectory)
             throws DeviceNotAvailableException {
+        // Cannot push to a privileged directory with one command.
+        // (i.e. there is no single-command equivalent of 'adb root; adb push src dst')
+        //
+        // Push to a tmp directory and then move it to the final destination
+        // after updating the selinux label.
         String tmpPath = "/data/local/tmp/" + APPLICATION_PACKAGE + ".push.tmp";
         assertTrue(mDevice.pushFile(new File(hostPath), tmpPath));
+
+        // Important: Use "cp" here because it newly copied files will inherit the security context
+        // of the targetDirectory according to the default policy.
+        //
+        // (Other approaches, such as moving the file retain the invalid security context
+        // of the tmp directory - b/37425296)
+        //
+        // This mimics the behavior of 'adb root; adb push $targetPath'.
         executeSuShellAdbCommand("mv", tmpPath, targetPath);
+
+        // Important: Use "restorecon" here because the file in tmpPath retains the
+        // incompatible security context of /data/local/tmp.
+        //
+        // This mimics the behavior of 'adb root; adb push $targetPath'.
+        executeSuShellAdbCommand("restorecon", targetPath);
+
+        // Validate that the security context of the file matches the security context
+        // of the directory it was pushed to.
+        //
+        // This is a reasonable default behavior to check because most selinux policies
+        // are configured to behave like this.
+        checkSelinuxLabelMatches(targetDirectory, targetPath);
     }
 
     private void executePull(String targetPath, String hostPath)
diff --git a/hostsidetests/devicepolicy/app/Assistant/Android.mk b/hostsidetests/devicepolicy/app/Assistant/Android.mk
new file mode 100644
index 0000000..196f323
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/Assistant/Android.mk
@@ -0,0 +1,39 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := optional
+
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_PACKAGE_NAME := CtsDevicePolicyAssistApp
+
+LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 compatibility-device-util android-support-test
+
+LOCAL_SDK_VERSION := current
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/Assistant/AndroidManifest.xml b/hostsidetests/devicepolicy/app/Assistant/AndroidManifest.xml
new file mode 100644
index 0000000..5fc20de
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/Assistant/AndroidManifest.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.cts.devicepolicy.assistapp" >
+
+    <application>
+
+        <service android:name=".MyInteractionService"
+                android:label="CTS test voice interaction service"
+                android:permission="android.permission.BIND_VOICE_INTERACTION"
+                android:exported="true">
+            <meta-data android:name="android.voice_interaction"
+                    android:resource="@xml/interaction_service" />
+            <intent-filter>
+                <action android:name="android.service.voice.VoiceInteractionService" />
+            </intent-filter>
+        </service>
+
+        <service android:name=".MyInteractionSessionService"
+                android:permission="android.permission.BIND_VOICE_INTERACTION">
+        </service>
+
+        <activity android:name=".SettingsActivity"
+                android:exported="true">
+        </activity>
+    </application>
+
+    <instrumentation
+            android:name="android.support.test.runner.AndroidJUnitRunner"
+            android:targetPackage="com.android.cts.devicepolicy.assistapp"
+            android:label="Assistant related device policy CTS" />
+
+</manifest>
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/Assistant/res/xml/interaction_service.xml b/hostsidetests/devicepolicy/app/Assistant/res/xml/interaction_service.xml
new file mode 100644
index 0000000..a3fe680
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/Assistant/res/xml/interaction_service.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android"
+        android:sessionService="com.android.cts.devicepolicy.assistapp.MyInteractionSessionService"
+        android:recognitionService="com.android.cts.devicepolicy.assistapp.MyInteractionService"
+        android:settingsActivity="com.android.cts.devicepolicy.assistapp.SettingsActivity"
+        android:supportsAssist="true" />
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/MyInteractionService.java b/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/MyInteractionService.java
new file mode 100644
index 0000000..e232540
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/MyInteractionService.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.devicepolicy.assistapp;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.service.voice.VoiceInteractionService;
+import android.util.Log;
+
+import static android.service.voice.VoiceInteractionSession.SHOW_WITH_ASSIST;
+import static android.service.voice.VoiceInteractionSession.SHOW_WITH_SCREENSHOT;
+
+public class MyInteractionService extends VoiceInteractionService {
+    private static final String TAG = "DevicePolicyAssistTest";
+    private static final String ACTION_CHECK_IS_READY = "voice_interaction_service.is_ready";
+    private static final String ACTION_SHOW_SESSION = "voice_interaction_service.show_session";
+    private AssistReceiver mReceiver;
+    private boolean mReady;
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mReceiver = new AssistReceiver();
+        IntentFilter intentFilter = new IntentFilter();
+        intentFilter.addAction(ACTION_CHECK_IS_READY);
+        intentFilter.addAction(ACTION_SHOW_SESSION);
+        registerReceiver(mReceiver, intentFilter);
+    }
+
+    @Override
+    public void onReady() {
+        super.onReady();
+        Log.d(TAG, "onReady() called");
+        mReady = true;
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        Log.d(TAG, "onDestroy() called");
+        unregisterReceiver(mReceiver);
+        mReceiver = null;
+    }
+
+    private class AssistReceiver extends BroadcastReceiver {
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            Log.d(TAG, "AssistReceiver: " + intent + " mReady: " + mReady);
+            if (ACTION_CHECK_IS_READY.equals(intent.getAction())) {
+                setResultCode(mReady ? Activity.RESULT_OK : Activity.RESULT_CANCELED);
+            } else if (ACTION_SHOW_SESSION.equals(intent.getAction())) {
+                showSession(
+                        new Bundle(),
+                        SHOW_WITH_ASSIST | SHOW_WITH_SCREENSHOT);
+            }
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/MyInteractionSessionService.java b/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/MyInteractionSessionService.java
new file mode 100644
index 0000000..5eae4f7
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/MyInteractionSessionService.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.devicepolicy.assistapp;
+
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.os.Bundle;
+import android.service.voice.VoiceInteractionSession;
+import android.service.voice.VoiceInteractionSessionService;
+import android.util.Log;
+
+public class MyInteractionSessionService extends VoiceInteractionSessionService {
+    private static final String TAG = "DevicePolicyAssistTest";
+    private static final String ACTION_HANDLE_SCREENSHOT =
+            "voice_interaction_session_service.handle_screenshot";
+    private static final String KEY_HAS_SCREENSHOT = "has_screenshot";
+
+    @Override
+    public VoiceInteractionSession onNewSession(Bundle args) {
+        return new MainInteractionSession(this);
+    }
+
+    public static class MainInteractionSession extends VoiceInteractionSession {
+
+        public MainInteractionSession(Context context) {
+            super(context);
+        }
+
+        @Override
+        public void onHandleScreenshot(Bitmap screenshot) {
+            Log.d(TAG, "onHandleScreenshot() called with: screenshot = [" + screenshot + "]");
+            Intent intent = new Intent(ACTION_HANDLE_SCREENSHOT);
+            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+            intent.putExtra(KEY_HAS_SCREENSHOT, screenshot != null);
+            getContext().sendBroadcast(intent);
+            finish();
+        }
+    }
+}
\ No newline at end of file
diff --git a/hostsidetests/jvmti/base/jni/common.h b/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/SettingsActivity.java
similarity index 69%
rename from hostsidetests/jvmti/base/jni/common.h
rename to hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/SettingsActivity.java
index ded4fc5..1f6d34f 100644
--- a/hostsidetests/jvmti/base/jni/common.h
+++ b/hostsidetests/devicepolicy/app/Assistant/src/com/android/cts/devicepolicy/assistapp/SettingsActivity.java
@@ -13,22 +13,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.android.cts.devicepolicy.assistapp;
 
-#ifndef COMMON_H_
-#define COMMON_H_
+import android.app.Activity;
 
-#include "jni.h"
-#include "jvmti.h"
-
-namespace cts {
-namespace jvmti {
-
-jvmtiEnv* GetJvmtiEnv();
-
-int JniThrowNullPointerException(JNIEnv* env, const char* msg);
-
-}  // namespace jvmti
-}  // namespace cts
-
-
-#endif  // COMMON_H_
+public class SettingsActivity extends Activity {
+}
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/AndroidManifest.xml
index 89ac4ae..820f1be 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/AndroidManifest.xml
@@ -37,11 +37,12 @@
         </receiver>
         <activity android:name="com.android.compatibility.common.util.devicepolicy.provisioning.StartProvisioningActivity"/>
 
-        <service android:name=".CrossUserService"
-                android:exported="false">
+        <service android:name=".ProtectedCrossUserService"
+                android:exported="true"
+                android:permission="android.permission.BIND_DEVICE_ADMIN">
         </service>
 
-        <service android:name=".ExportedCrossUserService"
+        <service android:name=".UnprotectedCrossUserService"
                 android:exported="true">
         </service>
     </application>
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceFailsTest.java b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceFailsTest.java
index 476b99c..319d7ec 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceFailsTest.java
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceFailsTest.java
@@ -66,7 +66,7 @@
     private void checkCannotBind(String targetPackageName, UserHandle otherProfile) {
         try {
             final Intent serviceIntent = new Intent();
-            serviceIntent.setClassName(targetPackageName, CrossUserService.class.getName());
+            serviceIntent.setClassName(targetPackageName, ProtectedCrossUserService.class.getName());
             bind(serviceIntent, EMPTY_SERVICE_CONNECTION, otherProfile);
             fail("SecurityException should be thrown");
         } catch (SecurityException ex) {
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceGoodSetupTest.java b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceGoodSetupTest.java
index ad65367..e7386cd 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceGoodSetupTest.java
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/BindDeviceAdminServiceGoodSetupTest.java
@@ -33,7 +33,6 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserHandle;
-import android.os.UserManager;
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 import android.util.Log;
@@ -107,16 +106,17 @@
     }
 
     /**
-     * Make sure we cannot bind exported service.
+     * Make sure we cannot bind unprotected service.
      */
-    public void testCannotBind_exportedCrossUserService() throws Exception {
-        final Intent serviceIntent = new Intent(mContext, ExportedCrossUserService.class);
+    public void testCannotBind_unprotectedCrossUserService() throws Exception {
+        final Intent serviceIntent = new Intent(mContext, UnprotectedCrossUserService.class);
         for (UserHandle targetUser : mTargetUsers) {
             try {
                 bind(serviceIntent, EMPTY_SERVICE_CONNECTION, targetUser);
                 fail("SecurityException should be thrown for target user " + targetUser);
             } catch (SecurityException ex) {
-                MoreAsserts.assertContainsRegex("must be unexported", ex.getMessage());
+                MoreAsserts.assertContainsRegex(
+                        "must be protected by BIND_DEVICE_ADMIN", ex.getMessage());
             }
         }
     }
@@ -126,7 +126,7 @@
      */
     public void testCheckCannotBind_nonManagingPackage() throws Exception {
         final Intent serviceIntent = new Intent();
-        serviceIntent.setClassName(NON_MANAGING_PACKAGE, CrossUserService.class.getName());
+        serviceIntent.setClassName(NON_MANAGING_PACKAGE, ProtectedCrossUserService.class.getName());
         for (UserHandle targetUser : mTargetUsers) {
             try {
                 bind(serviceIntent, EMPTY_SERVICE_CONNECTION, targetUser);
@@ -142,7 +142,7 @@
      */
     public void testCannotBind_sameUser() throws Exception {
         try {
-            final Intent serviceIntent = new Intent(mContext, CrossUserService.class);
+            final Intent serviceIntent = new Intent(mContext, ProtectedCrossUserService.class);
             bind(serviceIntent, EMPTY_SERVICE_CONNECTION, Process.myUserHandle());
             fail("IllegalArgumentException should be thrown");
         } catch (IllegalArgumentException ex) {
@@ -199,7 +199,7 @@
                 Log.d(TAG, "onServiceDisconnected is called");
             }
         };
-        final Intent serviceIntent = new Intent(mContext, CrossUserService.class);
+        final Intent serviceIntent = new Intent(mContext, ProtectedCrossUserService.class);
         assertTrue(bind(serviceIntent, serviceConnection, targetUserHandle));
         IInterface service = queue.poll(5, TimeUnit.SECONDS);
         assertNotNull("binding to the target service timed out", service);
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/CrossUserService.java b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/ProtectedCrossUserService.java
similarity index 95%
rename from hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/CrossUserService.java
rename to hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/ProtectedCrossUserService.java
index 3b95b94..76e926a 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/CrossUserService.java
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/ProtectedCrossUserService.java
@@ -25,7 +25,7 @@
 /**
  * Handle the cross user call from the device admin in other side.
  */
-public class CrossUserService extends Service {
+public class ProtectedCrossUserService extends Service {
 
     private final ICrossUserService.Stub mBinder = new ICrossUserService.Stub() {
         public String echo(String msg) {
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/ExportedCrossUserService.java b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/UnprotectedCrossUserService.java
similarity index 93%
rename from hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/ExportedCrossUserService.java
rename to hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/UnprotectedCrossUserService.java
index e7a9e73..8540737 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/ExportedCrossUserService.java
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/UnprotectedCrossUserService.java
@@ -23,7 +23,7 @@
 /**
  * Dummy service that is exported.
  */
-public class ExportedCrossUserService extends Service {
+public class UnprotectedCrossUserService extends Service {
     @Override
     public IBinder onBind(Intent intent) {
         return null;
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/provisioning/AffiliationTest.java b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/provisioning/AffiliationTest.java
index 7a1fa40..442e544 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/provisioning/AffiliationTest.java
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/provisioning/AffiliationTest.java
@@ -21,9 +21,11 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.test.AndroidTestCase;
+
 import com.android.cts.comp.AdminReceiver;
-import java.util.Arrays;
-import java.util.List;
+
+import java.util.Collections;
+import java.util.Set;
 
 public class AffiliationTest extends AndroidTestCase {
 
@@ -39,7 +41,7 @@
         ComponentName admin = AdminReceiver.getComponentName(getContext());
         DevicePolicyManager dpm = (DevicePolicyManager)
                 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
-        List<String> ids = Arrays.asList(id);
+        Set<String> ids = Collections.singleton(id);
         dpm.setAffiliationIds(admin, ids);
         assertEquals(ids, dpm.getAffiliationIds(admin));
     }
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package1/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAdminService/package1/AndroidManifest.xml
index 5d63794..47f3c6a6 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package1/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package1/AndroidManifest.xml
@@ -32,7 +32,8 @@
 
         <service
                 android:name=".MyService"
-                android:exported="false">
+                android:exported="true"
+                android:permission="android.permission.BIND_DEVICE_ADMIN" >
             <intent-filter>
                 <action android:name="android.app.action.DEVICE_ADMIN_SERVICE" />
             </intent-filter>
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package2/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAdminService/package2/AndroidManifest.xml
index 5d63794..0ff8e68 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package2/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package2/AndroidManifest.xml
@@ -32,7 +32,8 @@
 
         <service
                 android:name=".MyService"
-                android:exported="false">
+                android:exported="false"
+                android:permission="android.permission.BIND_DEVICE_ADMIN" >
             <intent-filter>
                 <action android:name="android.app.action.DEVICE_ADMIN_SERVICE" />
             </intent-filter>
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package3/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAdminService/package3/AndroidManifest.xml
index 84dacbd..5d63794 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package3/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package3/AndroidManifest.xml
@@ -32,7 +32,7 @@
 
         <service
                 android:name=".MyService"
-                android:exported="true">
+                android:exported="false">
             <intent-filter>
                 <action android:name="android.app.action.DEVICE_ADMIN_SERVICE" />
             </intent-filter>
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package4/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAdminService/package4/AndroidManifest.xml
index 1b8497d..b43d086 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package4/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package4/AndroidManifest.xml
@@ -31,14 +31,14 @@
         </receiver>
         <service
                 android:name=".MyService"
-                android:exported="false">
+                android:permission="android.permission.BIND_DEVICE_ADMIN" >
             <intent-filter>
                 <action android:name="android.app.action.DEVICE_ADMIN_SERVICE" />
             </intent-filter>
         </service>
         <service
                 android:name=".MyService2"
-                android:exported="false">
+                android:permission="android.permission.BIND_DEVICE_ADMIN" >
             <intent-filter>
                 <action android:name="android.app.action.DEVICE_ADMIN_SERVICE" />
             </intent-filter>
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/AndroidManifest.xml
index 894d13c..95d203a 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/AndroidManifest.xml
@@ -31,7 +31,8 @@
         </receiver>
         <service
                 android:name="com.android.cts.deviceadminservice.MyService"
-                android:exported="false">
+                android:exported="true"
+                android:permission="android.permission.BIND_DEVICE_ADMIN" >
             <intent-filter>
                 <action android:name="android.app.action.DEVICE_ADMIN_SERVICE" />
             </intent-filter>
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java
new file mode 100644
index 0000000..db54ac3
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java
@@ -0,0 +1,98 @@
+package com.android.cts.deviceandprofileowner;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.os.Handler;
+import android.os.Looper;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+import android.util.Log;
+
+import com.android.compatibility.common.util.BlockingBroadcastReceiver;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Testing
+ * {@link android.app.admin.DevicePolicyManager#setScreenCaptureDisabled(ComponentName, boolean)}
+ * is enforced in {@link android.service.voice.VoiceInteractionSession#onHandleScreenshot(Bitmap)}.
+ */
+@RunWith(AndroidJUnit4.class)
+public class AssistScreenCaptureDisabledTest {
+    private static final String TAG = "DevicePolicyAssistTest";
+    
+    private static final String ACTION_CHECK_IS_READY = "voice_interaction_service.is_ready";
+    private static final String ACTION_SHOW_SESSION = "voice_interaction_service.show_session";
+    private static final String ACTION_HANDLE_SCREENSHOT =
+            "voice_interaction_session_service.handle_screenshot";
+    private static final String KEY_HAS_SCREENSHOT = "has_screenshot";
+    private static final String ASSIST_PACKAGE = "com.android.cts.devicepolicy.assistapp";
+
+    private static final int MAX_ATTEMPTS_COUNT = 5;
+    private static final int WAIT_IN_SECOND = 5;
+    private Context mContext;
+
+    @Before
+    public void setup() {
+        mContext = InstrumentationRegistry.getContext();
+    }
+
+    @Test
+    public void testScreenCaptureImpossible_assist() throws Exception {
+        assertScreenCapturePossible(false);
+    }
+
+    @Test
+    public void testScreenCapturePossible_assist() throws Exception {
+        assertScreenCapturePossible(true);
+    }
+
+    private void assertScreenCapturePossible(boolean possible) throws InterruptedException {
+        // Wait until voice interaction service is ready by sending broadcast to ask for status.
+        Intent checkIsReadyIntent = new Intent(ACTION_CHECK_IS_READY);
+        checkIsReadyIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+        checkIsReadyIntent.setPackage(ASSIST_PACKAGE);
+        boolean isAssistReady = false;
+        for (int i = 0; i < MAX_ATTEMPTS_COUNT && !isAssistReady; i++) {
+            Log.d(TAG, "assertScreenCapturePossible: wait for assist service ready, attempt " + i);
+            final LinkedBlockingQueue<Boolean> q = new LinkedBlockingQueue<>();
+            mContext.sendOrderedBroadcast(checkIsReadyIntent, null, new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    q.offer(getResultCode() == Activity.RESULT_OK);
+                }
+            }, null, Activity.RESULT_CANCELED, null, null);
+            Boolean result = q.poll(WAIT_IN_SECOND, TimeUnit.SECONDS);
+            isAssistReady = result != null && result;
+        }
+        Assert.assertTrue(isAssistReady);
+
+        // Send broadcast to voice interaction service and ask for screnshot.
+        BlockingBroadcastReceiver receiver = new BlockingBroadcastReceiver(
+                mContext, ACTION_HANDLE_SCREENSHOT);
+        try {
+            receiver.register();
+            Intent showSessionIntent = new Intent(ACTION_SHOW_SESSION);
+            showSessionIntent.setPackage(ASSIST_PACKAGE);
+            mContext.sendBroadcast(showSessionIntent);
+            Intent screenShotIntent = receiver.awaitForBroadcast();
+            Assert.assertNotNull(screenShotIntent);
+            Assert.assertTrue(screenShotIntent.hasExtra(KEY_HAS_SCREENSHOT));
+            assertEquals(possible, screenShotIntent.getBooleanExtra(KEY_HAS_SCREENSHOT, false));
+        } finally {
+            receiver.unregisterQuietly();
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
index b7f9066..c5b3e96 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
@@ -16,7 +16,7 @@
 package com.android.cts.deviceandprofileowner;
 
 import android.app.admin.DevicePolicyManager;
-import android.util.Log;
+import android.support.v4.content.LocalBroadcastManager;
 
 /**
  * Tests for {@link DevicePolicyManager#setScreenCaptureDisabled} and
@@ -26,6 +26,12 @@
 
     private static final String TAG = "ScreenCaptureDisabledTest";
 
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
     public void testSetScreenCaptureDisabled_false() throws Exception {
         mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, false);
         assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/BaseUserRestrictionsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/BaseUserRestrictionsTest.java
index ddd704d..39235b0 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/BaseUserRestrictionsTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/BaseUserRestrictionsTest.java
@@ -66,7 +66,8 @@
             UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
             UserManager.DISALLOW_DATA_ROAMING,
             UserManager.DISALLOW_SET_USER_ICON,
-            UserManager.DISALLOW_BLUETOOTH
+            UserManager.DISALLOW_BLUETOOTH,
+            UserManager.DISALLOW_BLUETOOTH_SHARING
     };
 
     /**
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/ManagedProfileOwnerUserRestrictionsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/ManagedProfileOwnerUserRestrictionsTest.java
new file mode 100644
index 0000000..81f1b1c
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/userrestrictions/ManagedProfileOwnerUserRestrictionsTest.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.deviceandprofileowner.userrestrictions;
+
+import android.os.UserManager;
+
+/**
+ * Test for managed profile owner restriction behavior. It is mostly the same as just secondary
+ * profile owner but some restrictions are set by default.
+ */
+public class ManagedProfileOwnerUserRestrictionsTest
+        extends SecondaryProfileOwnerUserRestrictionsTest {
+
+    private static final String[] DEFAULT_ENABLED = new String[] {
+            UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
+            UserManager.DISALLOW_BLUETOOTH_SHARING
+    };
+
+    @Override
+    protected String[] getDefaultEnabledRestrictions() {
+        return DEFAULT_ENABLED;
+    }
+}
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AffiliationTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AffiliationTest.java
index 4ccb3c6..a9b43c6 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AffiliationTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AffiliationTest.java
@@ -16,26 +16,24 @@
 
 package com.android.cts.deviceowner;
 
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.fail;
-
-import static org.junit.Assert.assertArrayEquals;
-
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
 import android.content.Context;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.runner.AndroidJUnit4;
 
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 import java.util.Collections;
-import java.util.List;
+import java.util.Set;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+import static org.junit.Assert.assertArrayEquals;
 
 @RunWith(AndroidJUnit4.class)
 public class AffiliationTest {
@@ -52,13 +50,33 @@
     }
 
     @Test
+    public void testSetAffiliationId_null() {
+        try {
+            mDevicePolicyManager.setAffiliationIds(mAdminComponent, null);
+            fail("Should throw IllegalArgumentException");
+        } catch (IllegalArgumentException ex) {
+            // Expected
+        }
+    }
+
+    @Test
+    public void testSetAffiliationId_containsEmptyString() {
+        try {
+            mDevicePolicyManager.setAffiliationIds(mAdminComponent, Collections.singleton(null));
+            fail("Should throw IllegalArgumentException");
+        } catch (IllegalArgumentException ex) {
+            // Expected
+        }
+    }
+
+    @Test
     public void testSetAffiliationId1() {
-        setAffiliationIds(Collections.singletonList("id.number.1"));
+        setAffiliationIds(Collections.singleton("id.number.1"));
     }
 
     @Test
     public void testSetAffiliationId2() {
-        setAffiliationIds(Collections.singletonList("id.number.2"));
+        setAffiliationIds(Collections.singleton("id.number.2"));
     }
 
     @Test
@@ -75,11 +93,11 @@
         assertTrue(mDevicePolicyManager.isLockTaskPermitted("package1"));
         assertFalse(mDevicePolicyManager.isLockTaskPermitted("package3"));
 
-        final List<String> previousAffiliationIds =
+        final Set<String> previousAffiliationIds =
                 mDevicePolicyManager.getAffiliationIds(mAdminComponent);
         try {
             // Clearing affiliation ids for this user. Lock task methods unavailable.
-            setAffiliationIds(Collections.<String>emptyList());
+            setAffiliationIds(Collections.emptySet());
             checkLockTaskMethodsThrow();
             assertFalse(mDevicePolicyManager.isLockTaskPermitted("package1"));
 
@@ -92,7 +110,7 @@
         }
     }
 
-    private void setAffiliationIds(List<String> ids) {
+    private void setAffiliationIds(Set<String> ids) {
         mDevicePolicyManager.setAffiliationIds(mAdminComponent, ids);
         assertEquals(ids, mDevicePolicyManager.getAffiliationIds(mAdminComponent));
     }
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BluetoothRestrictionTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BluetoothRestrictionTest.java
index 0ddf842..552503b 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BluetoothRestrictionTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BluetoothRestrictionTest.java
@@ -16,7 +16,6 @@
 
 package com.android.cts.deviceowner;
 
-import android.app.admin.DevicePolicyManager;
 import android.bluetooth.BluetoothAdapter;
 import android.content.ComponentName;
 import android.content.pm.PackageManager;
@@ -103,7 +102,8 @@
     }
 
     /**
-     * Tests that BluetoothOppLauncherActivity gets disabled when Bluetooth is disallowed.
+     * Tests that BluetoothOppLauncherActivity gets disabled when Bluetooth itself or Bluetooth
+     * sharing is disallowed.
      *
      * <p> It also checks the state of the activity is set back to default if Bluetooth is not
      * disallowed anymore.
@@ -113,15 +113,24 @@
             return;
         }
 
+        // First verify DISALLOW_BLUETOOTH.
+        testOppDisabledWhenRestrictionSet(UserManager.DISALLOW_BLUETOOTH);
+        // Verify DISALLOW_BLUETOOTH_SHARING which leaves bluetooth workable but the sharing
+        // component should be disabled.
+        testOppDisabledWhenRestrictionSet(UserManager.DISALLOW_BLUETOOTH_SHARING);
+    }
+
+    /** Verifies that a given restriction disables the bluetooth sharing component. */
+    private void testOppDisabledWhenRestrictionSet(String restriction) {
         // Add the user restriction.
-        mDevicePolicyManager.addUserRestriction(getWho(), UserManager.DISALLOW_BLUETOOTH);
+        mDevicePolicyManager.addUserRestriction(getWho(), restriction);
 
         // The BluetoothOppLauncherActivity's component should be disabled.
         assertComponentStateAfterTimeout(
                 OPP_LAUNCHER_COMPONENT, PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
 
         // Remove the user restriction.
-        mDevicePolicyManager.clearUserRestriction(getWho(), UserManager.DISALLOW_BLUETOOTH);
+        mDevicePolicyManager.clearUserRestriction(getWho(), restriction);
 
         // The BluetoothOppLauncherActivity's component should be in the default state.
         assertComponentStateAfterTimeout(
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java
index 031763d..956e03d 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java
@@ -25,14 +25,12 @@
 import android.support.v4.content.LocalBroadcastManager;
 import android.util.Log;
 
+import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.UnknownHostException;
 import java.net.URL;
-import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -127,13 +125,13 @@
         mCurrentBatchToken = FAKE_BATCH_TOKEN;
         mGenerateNetworkTraffic = true;
         // register a receiver that listens for DeviceAdminReceiver#onNetworkLogsAvailable()
-        IntentFilter filterNetworkLogsAvailable = new IntentFilter(
+        final IntentFilter filterNetworkLogsAvailable = new IntentFilter(
                 BaseDeviceOwnerTest.ACTION_NETWORK_LOGS_AVAILABLE);
         LocalBroadcastManager.getInstance(mContext).registerReceiver(mNetworkLogsReceiver,
                 filterNetworkLogsAvailable);
 
         // visit websites that shouldn't be logged as network logging isn't enabled yet
-        for (String url : NOT_LOGGED_URLS_LIST) {
+        for (final String url : NOT_LOGGED_URLS_LIST) {
             connectToWebsite(url);
         }
 
@@ -146,7 +144,7 @@
         // visit websites in a loop to generate enough network traffic
         int iterationsDone = 0;
         while (mGenerateNetworkTraffic && iterationsDone < MAX_VISITING_WEBPAGES_ITERATIONS) {
-            for (String url : LOGGED_URLS_LIST) {
+            for (final String url : LOGGED_URLS_LIST) {
                 connectToWebsite(url);
             }
             iterationsDone++;
@@ -162,7 +160,7 @@
         }
 
         // retrieve and verify network logs
-        List<NetworkEvent> networkEvents = mDevicePolicyManager.retrieveNetworkLogs(getWho(),
+        final List<NetworkEvent> networkEvents = mDevicePolicyManager.retrieveNetworkLogs(getWho(),
                 mCurrentBatchToken);
         if (networkEvents == null) {
             fail("Failed to retrieve batch of network logs with batch token " + mCurrentBatchToken);
@@ -176,10 +174,10 @@
         int ctsPackageNameCounter = 0;
         // allow a small down margin for verification, to avoid flakyness
         final int iterationsDoneWithMargin = iterationsDone - 5;
-        int[] visitedFrequencies = new int[LOGGED_URLS_LIST.length];
+        final int[] visitedFrequencies = new int[LOGGED_URLS_LIST.length];
 
         for (int i = 0; i < networkEvents.size(); i++) {
-            NetworkEvent currentEvent = networkEvents.get(i);
+            final NetworkEvent currentEvent = networkEvents.get(i);
             // verify that the events are in chronological order
             if (i > 0) {
                 assertTrue(currentEvent.getTimestamp() >= networkEvents.get(i - 1).getTimestamp());
@@ -188,7 +186,7 @@
             if (CTS_APP_PACKAGE_NAME.equals(currentEvent.getPackageName())) {
                 ctsPackageNameCounter++;
                 if (currentEvent instanceof DnsEvent) {
-                    DnsEvent dnsEvent = (DnsEvent) currentEvent;
+                    final DnsEvent dnsEvent = (DnsEvent) currentEvent;
                     // verify that we didn't log a hostname lookup when network logging was disabled
                     if (dnsEvent.getHostname().contains(NOT_LOGGED_URLS_LIST[0])
                             || dnsEvent.getHostname().contains(NOT_LOGGED_URLS_LIST[1])) {
@@ -203,18 +201,19 @@
                         }
                     }
                     // verify that as many IP addresses were logged as were reported (max 10)
-                    String[] ips = dnsEvent.getIpAddresses();
+                    final InetAddress[] ips = dnsEvent.getInetAddresses();
                     assertTrue(ips.length <= MAX_IP_ADDRESSES_LOGGED);
-                    assertEquals(Math.min(MAX_IP_ADDRESSES_LOGGED, dnsEvent.getIpAddressesCount()),
-                            ips.length);
+                    final int expectedAddressCount = Math.min(MAX_IP_ADDRESSES_LOGGED,
+                            dnsEvent.getTotalResolvedAddressCount());
+                    assertEquals(expectedAddressCount, ips.length);
                     // verify the IP addresses are valid IPv4 or IPv6 addresses
-                    for (String ipAddress : ips) {
-                        assertTrue(isValidIpv4OrIpv6Address(ipAddress));
+                    for (final InetAddress ipAddress : ips) {
+                        assertTrue(isIpv4OrIpv6Address(ipAddress));
                     }
                 } else if (currentEvent instanceof ConnectEvent) {
-                    ConnectEvent connectEvent = (ConnectEvent) currentEvent;
+                    final ConnectEvent connectEvent = (ConnectEvent) currentEvent;
                     // verify the IP address is a valid IPv4 or IPv6 address
-                    assertTrue(isValidIpv4OrIpv6Address(connectEvent.getIpAddress()));
+                    assertTrue(isIpv4OrIpv6Address(connectEvent.getInetAddress()));
                     // verify that the port is a valid port
                     assertTrue(connectEvent.getPort() >= 0 && connectEvent.getPort() <= 65535);
                 } else {
@@ -236,13 +235,11 @@
     private void connectToWebsite(String urlString) {
         HttpURLConnection urlConnection = null;
         try {
-            URL url = new URL("http://" + urlString);
+            final URL url = new URL("http://" + urlString);
             urlConnection = (HttpURLConnection) url.openConnection();
             urlConnection.setConnectTimeout(2000);
             urlConnection.setReadTimeout(2000);
             urlConnection.getResponseCode();
-        } catch (MalformedURLException e) {
-            Log.w(TAG, "Failed to connect to " + urlString, e);
         } catch (IOException e) {
             Log.w(TAG, "Failed to connect to " + urlString, e);
         } finally {
@@ -252,12 +249,7 @@
         }
     }
 
-    private boolean isValidIpv4OrIpv6Address(String ipAddress) {
-        try {
-            InetAddress addr = InetAddress.getByName(ipAddress);
-            return (addr instanceof Inet4Address) || (addr instanceof Inet6Address);
-        } catch (UnknownHostException e) {
-            return false;
-        }
+    private boolean isIpv4OrIpv6Address(InetAddress addr) {
+        return ((addr instanceof Inet4Address) || (addr instanceof Inet6Address));
     }
 }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionPrimaryProfileTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionPrimaryProfileTest.java
new file mode 100644
index 0000000..58bcc8f
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionPrimaryProfileTest.java
@@ -0,0 +1,36 @@
+
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.managedprofile;
+
+import static com.android.cts.managedprofile.BluetoothSharingRestrictionTest.assertBluetoothSharingAvailable;
+
+import android.bluetooth.BluetoothAdapter;
+import android.test.InstrumentationTestCase;
+
+/**
+ * Auxiliary test to check that Bluetooth sharing in primary profile is not affected.
+ */
+public class BluetoothSharingRestrictionPrimaryProfileTest extends InstrumentationTestCase {
+    /** Verifies that bluetooth sharing is available in personal profile. */
+    public void testBluetoothSharingAvailable() throws Exception {
+        if (BluetoothAdapter.getDefaultAdapter() == null) {
+            // No Bluetooth - nothing to test.
+            return;
+        }
+        assertBluetoothSharingAvailable(getInstrumentation().getContext(), true);
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java
new file mode 100644
index 0000000..4c5659b
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.managedprofile;
+
+
+import android.bluetooth.BluetoothAdapter;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ComponentInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.os.SystemClock;
+import android.os.UserManager;
+
+import junit.framework.TestCase;
+
+import java.util.List;
+
+
+/**
+ * Test {@link UserManager#DISALLOW_BLUETOOTH_SHARING} in profile owner.
+ *
+ * Shamelessly copied from BluetoothRestrictionTest, would be nice to extract common stuff to a lib.
+ */
+public class BluetoothSharingRestrictionTest extends BaseManagedProfileTest {
+    /** How long should we wait for the component state to change. */
+    private static final int COMPONENT_STATE_TIMEOUT_MS = 2000;
+    /** How often to check component state. */
+    private static final int POLL_TIME_MS = 400;
+    /** Activity that handles Bluetooth sharing. */
+    private static final ComponentName OPP_LAUNCHER_COMPONENT = new ComponentName(
+            "com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
+
+    /**
+     * Tests that Bluetooth sharing activity gets disabled when the restriction is enforced.
+     */
+    public void testOppDisabledWhenRestrictionSet() throws Exception {
+        if (BluetoothAdapter.getDefaultAdapter() == null) {
+            // No Bluetooth - nothing to test.
+            return;
+        }
+
+        // The restriction is active by default for managed profiles.
+        assertBluetoothSharingAvailable(mContext, false);
+
+        // Remove the user restriction.
+        mDevicePolicyManager.clearUserRestriction(
+                ADMIN_RECEIVER_COMPONENT, UserManager.DISALLOW_BLUETOOTH_SHARING);
+        // Bluetooth sharing should become available.
+        assertBluetoothSharingAvailable(mContext, true);
+
+        // Add the user restriction back (which is the default state).
+        mDevicePolicyManager.addUserRestriction(
+                ADMIN_RECEIVER_COMPONENT, UserManager.DISALLOW_BLUETOOTH_SHARING);
+        // Bluetooth sharing should be disabled once again.
+        assertBluetoothSharingAvailable(mContext, false);
+    }
+
+    /** Verifies restriction enforcement. */
+    private static void assertRestrictionEnforced(Context context, boolean enforced) {
+        final UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
+        assertEquals("Invalid restriction enforcement status", enforced,
+                um.getUserRestrictions().getBoolean(UserManager.DISALLOW_BLUETOOTH_SHARING, false));
+    }
+
+    /**
+     * Builds an intent to share an image file. If Bluetooth sharing is allowed, it should be
+     * handled by {@link #OPP_LAUNCHER_COMPONENT}.
+     */
+    private static Intent fileSharingIntent() {
+        final Intent result = new Intent(Intent.ACTION_SEND);
+        final Uri uri = Uri.parse("content://foo/bar");
+        result.setDataAndType(uri, "image/*");
+        return result;
+    }
+
+    /**
+     * Verifies bluetooth sharing availability.
+     */
+    static void assertBluetoothSharingAvailable(Context context, boolean available)
+            throws Exception {
+        // Check restriction.
+        assertRestrictionEnforced(context, !available);
+        // Check component status.
+        final int componentEnabledState = available
+                ? PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
+                : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
+        assertComponentStateAfterTimeout(context, OPP_LAUNCHER_COMPONENT, componentEnabledState);
+        // Check whether sharing activity is offered.
+        assertHandlerAvailable(context, fileSharingIntent(), OPP_LAUNCHER_COMPONENT, available);
+    }
+
+    /** Waits for package state to change to a desired one or fails. */
+    private static void assertComponentStateAfterTimeout(Context context, ComponentName component,
+            int expectedState)
+            throws Exception {
+        final long timeout = SystemClock.elapsedRealtime() + COMPONENT_STATE_TIMEOUT_MS;
+        int state = -1;
+        while (SystemClock.elapsedRealtime() < timeout) {
+            state = context.getPackageManager().getComponentEnabledSetting(component);
+            if (expectedState == state) {
+                // Success
+                return;
+            }
+            Thread.sleep(POLL_TIME_MS);
+        }
+        TestCase.fail("The state of " + component + " should have been " + expectedState
+                + ", it but was " + state + " after timeout.");
+    }
+
+    /** Verifies that {@code component} is offered when handling {@code intent}. */
+    private static void assertHandlerAvailable(Context context, Intent intent,
+            ComponentName component,
+            boolean shouldResolve) {
+        final List<ResolveInfo> infos =
+                context.getPackageManager().queryIntentActivities(intent, 0);
+        for (final ResolveInfo info : infos) {
+            final ComponentInfo componentInfo =
+                    info.activityInfo != null ? info.activityInfo :
+                            info.serviceInfo != null ? info.serviceInfo :
+                                    info.providerInfo;
+            final ComponentName resolvedComponent =
+                    new ComponentName(componentInfo.packageName, componentInfo.name);
+
+            if (resolvedComponent.equals(component)) {
+                if (shouldResolve) {
+                    // Found it, assertion passed.
+                    return;
+                } else {
+                    TestCase.fail(component + " is available as a handler for " + intent);
+                }
+            }
+        }
+        // If we get to this point, there was no match.
+        if (shouldResolve) {
+            TestCase.fail(component + " isn't available as a handler for " + intent);
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java
index d81b15c..fa74db7 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/LockNowTest.java
@@ -27,7 +27,7 @@
 public class LockNowTest extends BaseManagedProfileTest {
 
   public void testLockNowWithKeyEviction() throws InterruptedException {
-        mDevicePolicyManager.lockNow(DevicePolicyManager.FLAG_EVICT_CE_KEY);
+        mDevicePolicyManager.lockNow(DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY);
         // The test that the managed profile was locked is done in the host
     }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
index d3cde44..d20d5e4 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -138,7 +138,7 @@
         removeOwners();
         removeTestUsers();
         // Unlock keyguard before test
-        executeShellCommand("wm dismiss-keyguard");
+        wakeupAndDismissKeyguard();
     }
 
     @Override
@@ -764,4 +764,9 @@
             }
         }
     }
+
+    protected void wakeupAndDismissKeyguard() throws Exception {
+        executeShellCommand("input keyevent KEYCODE_WAKEUP");
+        executeShellCommand("wm dismiss-keyguard");
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index da902d3..865d785 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -96,9 +96,15 @@
     private static final String AUTOFILL_APP_PKG = "com.android.cts.devicepolicy.autofillapp";
     private static final String AUTOFILL_APP_APK = "CtsDevicePolicyAutofillApp.apk";
 
+    protected static final String ASSIST_APP_PKG = "com.android.cts.devicepolicy.assistapp";
+    protected static final String ASSIST_APP_APK = "CtsDevicePolicyAssistApp.apk";
+
     private static final String ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES
             = "enabled_notification_policy_access_packages";
 
+    protected static final String ASSIST_INTERACTION_SERVICE =
+            ASSIST_APP_PKG + "/.MyInteractionService";
+
     // ID of the user all tests are run as. For device owner this will be the primary user, for
     // profile owner it is the user id of the created profile.
     protected int mUserId;
@@ -364,6 +370,21 @@
         }
     }
 
+    public void testScreenCaptureDisabled_assist() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        try {
+            // Install and enable assistant, notice that profile can't have assistant.
+            installAppAsUser(ASSIST_APP_APK, mPrimaryUserId);
+            setVoiceInteractionService(ASSIST_INTERACTION_SERVICE);
+            setScreenCaptureDisabled_assist(mUserId, true /* disabled */);
+        } finally {
+            setScreenCaptureDisabled_assist(mUserId, false /* disabled */);
+            clearVoiceInteractionService();
+        }
+    }
+
     public void testSupportMessage() throws Exception {
         if (!mHasFeature) {
             return;
@@ -773,35 +794,44 @@
      */
     protected void startSimpleActivityAsUser(int userId) throws Exception {
         installAppAsUser(TEST_APP_APK, userId);
+        wakeupAndDismissKeyguard();
         String command = "am start -W --user " + userId + " " + TEST_APP_PKG + "/"
                 + TEST_APP_PKG + ".SimpleActivity";
         getDevice().executeShellCommand(command);
     }
 
-    // TODO: Remove this after investigation in b/28995242 is done
-    // So we can check which one is the top window / activity.
-    private void runDumpsysWindow() throws Exception {
-        String command = "dumpsys window displays";
-        CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
-        command = "dumpsys activity a";
-        CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
-    }
-
     protected void setScreenCaptureDisabled(int userId, boolean disabled) throws Exception {
         String testMethodName = disabled
                 ? "testSetScreenCaptureDisabled_true"
                 : "testSetScreenCaptureDisabled_false";
         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
         startSimpleActivityAsUser(userId);
-        // [b/28995242], dump windows to make sure the top window is
-        // ScreenCaptureDisabledActivity.
-        runDumpsysWindow();
         testMethodName = disabled
                 ? "testScreenCaptureImpossible"
                 : "testScreenCapturePossible";
         executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
     }
 
+    protected void setScreenCaptureDisabled_assist(int userId, boolean disabled) throws Exception {
+        // Set the policy.
+        String testMethodName = disabled
+                ? "testSetScreenCaptureDisabled_true"
+                : "testSetScreenCaptureDisabled_false";
+        executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
+        // Make sure the foreground activity is from the target user.
+        startSimpleActivityAsUser(userId);
+        // Check whether the VoiceInteractionService can retrieve the screenshot.
+        testMethodName = disabled
+                ? "testScreenCaptureImpossible_assist"
+                : "testScreenCapturePossible_assist";
+        installAppAsUser(DEVICE_ADMIN_APK, mPrimaryUserId);
+        runDeviceTestsAsUser(
+                DEVICE_ADMIN_PKG,
+                ".AssistScreenCaptureDisabledTest",
+                testMethodName,
+                mPrimaryUserId);
+    }
+
     /**
      * Allows packageName to manage notification policy configuration, which
      * includes toggling zen mode.
@@ -843,4 +873,16 @@
         }
         return new ArrayList<String>(Arrays.asList(settingValue.split(":|\n")));
     }
+
+    protected void setVoiceInteractionService(String componentName)
+            throws DeviceNotAvailableException {
+        getDevice().setSetting(
+                mPrimaryUserId, "secure", "voice_interaction_service", componentName);
+        getDevice().setSetting(mPrimaryUserId, "secure", "assist_structure_enabled", "1");
+        getDevice().setSetting(mPrimaryUserId, "secure", "assist_screenshot_enabled", "1");
+    }
+
+    protected void clearVoiceInteractionService() throws DeviceNotAvailableException {
+        getDevice().executeShellCommand("settings delete secure voice_interaction_service");
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index 8fce788..ac846a3 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -346,6 +346,14 @@
         executeDeviceTestMethod(".NetworkLoggingTest", "testNetworkLoggingAndRetrieval");
     }
 
+    public void testSetAffiliationId_IllegalArgumentException() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        executeDeviceTestMethod(".AffiliationTest", "testSetAffiliationId_null");
+        executeDeviceTestMethod(".AffiliationTest", "testSetAffiliationId_containsEmptyString");
+    }
+
     public void testLockTask_deviceOwnerUser() throws Exception {
         if (!mHasFeature) {
             return;
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 84a08ee..26da677 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -20,7 +20,6 @@
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.log.LogUtil.CLog;
 
-import java.lang.System;
 import junit.framework.AssertionFailedError;
 
 import java.util.concurrent.Callable;
@@ -449,8 +448,8 @@
 
     // Test the bluetooth API from a managed profile.
     public void testBluetooth() throws Exception {
-        boolean mHasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
-        if (!mHasFeature || !mHasBluetooth) {
+        boolean hasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
+        if (!mHasFeature || !hasBluetooth) {
             return ;
         }
 
@@ -881,6 +880,21 @@
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SanityTest", mProfileUserId);
     }
 
+    public void testBluetoothSharingRestriction() throws Exception {
+        final boolean hasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
+        if (!mHasFeature || !hasBluetooth) {
+            return;
+        }
+
+        // Primary profile should be able to use bluetooth sharing.
+        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionPrimaryProfileTest",
+                "testBluetoothSharingAvailable", mPrimaryUserId);
+
+        // Managed profile owner should be able to control it via DISALLOW_BLUETOOTH_SHARING.
+        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionTest",
+                "testOppDisabledWhenRestrictionSet", mProfileUserId);
+    }
+
     private void disableActivityForUser(String activityName, int userId)
             throws DeviceNotAvailableException {
         String command = "am start -W --user " + userId
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
index a2d8057..0022804 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
@@ -78,6 +78,36 @@
         executeDeviceTestMethod(".ScreenCaptureDisabledTest", "testScreenCapturePossible");
     }
 
+    public void testScreenCaptureDisabled_assist_allowedPrimaryUser() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        // disable screen capture in profile
+        executeDeviceTestMethod(".ScreenCaptureDisabledTest", "testSetScreenCaptureDisabled_true");
+        try {
+            // Install and enable assistant in personal side.
+            installAppAsUser(ASSIST_APP_APK, mParentUserId);
+            setVoiceInteractionService(ASSIST_INTERACTION_SERVICE);
+
+            // Start an activity in parent user.
+            installAppAsUser(DEVICE_ADMIN_APK, mParentUserId);
+            startSimpleActivityAsUser(mParentUserId);
+
+            // Verify assistant app can't take a screenshot.
+            runDeviceTestsAsUser(
+                    DEVICE_ADMIN_PKG,
+                    ".AssistScreenCaptureDisabledTest",
+                    "testScreenCapturePossible_assist",
+                    mPrimaryUserId);
+        } finally {
+            // enable screen capture in profile
+            executeDeviceTestMethod(
+                    ".ScreenCaptureDisabledTest",
+                    "testSetScreenCaptureDisabled_false");
+            clearVoiceInteractionService();
+        }
+    }
+
     @Override
     public void testDisallowSetWallpaper_allowed() throws Exception {
         // Managed profile doesn't have wallpaper.
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserRestrictionsTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserRestrictionsTest.java
index bd7bb63..90c35f4 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserRestrictionsTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserRestrictionsTest.java
@@ -105,10 +105,11 @@
                 "testDefaultRestrictions", mDeviceOwnerUserId);
         runTests("userrestrictions.PrimaryProfileOwnerUserRestrictionsTest",
                 "testSetAllRestrictions", mDeviceOwnerUserId);
-        runTests("userrestrictions.DeviceOwnerUserRestrictionsTest",
+        runTests("userrestrictions.PrimaryProfileOwnerUserRestrictionsTest",
                 "testBroadcast", mDeviceOwnerUserId);
     }
 
+    // Checks restrictions for managed user (NOT managed profile).
     public void testUserRestrictions_secondaryProfileOwnerOnly() throws Exception {
         if (!mHasFeature || !mSupportsMultiUser) {
             return;
@@ -120,10 +121,30 @@
                 "testDefaultRestrictions", secondaryUserId);
         runTests("userrestrictions.SecondaryProfileOwnerUserRestrictionsTest",
                 "testSetAllRestrictions", secondaryUserId);
-        runTests("userrestrictions.DeviceOwnerUserRestrictionsTest",
+        runTests("userrestrictions.SecondaryProfileOwnerUserRestrictionsTest",
                 "testBroadcast", secondaryUserId);
     }
 
+    // Checks restrictions for managed profile.
+    public void testUserRestrictions_managedProfileOwnerOnly() throws Exception {
+        if (!mHasFeature || !mSupportsMultiUser) {
+            return;
+        }
+
+        // Create managed profile.
+        final int profileUserId = createManagedProfile(mDeviceOwnerUserId /* parentUserId */);
+        // createManagedProfile doesn't start the user automatically.
+        startUser(profileUserId);
+        setPoAsUser(profileUserId);
+
+        runTests("userrestrictions.ManagedProfileOwnerUserRestrictionsTest",
+                "testDefaultRestrictions", profileUserId);
+        runTests("userrestrictions.ManagedProfileOwnerUserRestrictionsTest",
+                "testSetAllRestrictions", profileUserId);
+        runTests("userrestrictions.ManagedProfileOwnerUserRestrictionsTest",
+                "testBroadcast", profileUserId);
+    }
+
     /**
      * DO + PO combination.  Make sure global DO restrictions are visible on secondary users.
      */
diff --git a/hostsidetests/inputmethodservice/hostside/AndroidTest.xml b/hostsidetests/inputmethodservice/hostside/AndroidTest.xml
index c943aee..470e666 100644
--- a/hostsidetests/inputmethodservice/hostside/AndroidTest.xml
+++ b/hostsidetests/inputmethodservice/hostside/AndroidTest.xml
@@ -16,6 +16,10 @@
 -->
 
 <configuration description="Config for CTS Input Method Service host test cases">
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="input keyevent KEYCODE_WAKEUP" />
+        <option name="run-command" value="wm dismiss-keyguard" />
+    </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsInputMethodServiceEventProvider.apk" />
diff --git a/hostsidetests/jvmti/allocation-tracking/AndroidTest.xml b/hostsidetests/jvmti/allocation-tracking/AndroidTest.xml
index fc26aae..84f074d 100644
--- a/hostsidetests/jvmti/allocation-tracking/AndroidTest.xml
+++ b/hostsidetests/jvmti/allocation-tracking/AndroidTest.xml
@@ -21,5 +21,7 @@
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsJvmtiTrackingHostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiTrackingDeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.tracking" />
     </test>
 </configuration>
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 70434d1..7a13e79 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
@@ -19,6 +19,8 @@
 import org.junit.Before;
 import org.junit.Test;
 
+import art.Main;
+
 /**
  * Check tagging-related functionality.
  */
@@ -27,7 +29,7 @@
     @Before
     public void setUp() throws Exception {
         // Bind our native methods.
-        JniBindings.bindAgentJNI("android/jvmti/cts/JvmtiTrackingTest",
+        Main.bindAgentJNI("android/jvmti/cts/JvmtiTrackingTest",
                 getClass().getClassLoader());
 
         prefetchClassNames();
diff --git a/hostsidetests/jvmti/allocation-tracking/app/src/art/Main.java b/hostsidetests/jvmti/allocation-tracking/app/src/art/Main.java
new file mode 100644
index 0000000..6f569d1
--- /dev/null
+++ b/hostsidetests/jvmti/allocation-tracking/app/src/art/Main.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package art;
+
+/**
+ * This is a definition of generically exposed implementations by the CTS JVMTI agent.
+ */
+public class Main {
+    // Load the given class with the given classloader, and bind all native methods to corresponding
+    // C methods in the agent. Will abort if any of the steps fail.
+    public static native void bindAgentJNI(String className, ClassLoader classLoader);
+    // Same as above, giving the class directly.
+    public static native void bindAgentJNIForClass(Class<?> klass);
+
+    // General functionality shared between tests.
+    public static native void setTag(Object o, long tag);
+
+    public static native long getTag(Object o);
+}
diff --git a/hostsidetests/jvmti/base/app/src/android/jvmti/cts/JvmtiTestBase.java b/hostsidetests/jvmti/base/app/src/android/jvmti/cts/JvmtiTestBase.java
index b0c02cf..0b54a93 100644
--- a/hostsidetests/jvmti/base/app/src/android/jvmti/cts/JvmtiTestBase.java
+++ b/hostsidetests/jvmti/base/app/src/android/jvmti/cts/JvmtiTestBase.java
@@ -15,14 +15,17 @@
  */
 package android.jvmti.cts;
 
-import android.jvmti.JvmtiActivity;
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.runner.RunWith;
 
+import android.jvmti.JvmtiActivity;
+import art.CtsMain;
+
 /**
  * Base class for JVMTI tests. Ensures that the agent is connected for the tests. If you
  * do not subclass this test, make sure that JniBindings.waitFor is appropriately called.
@@ -45,6 +48,6 @@
         mActivity = mActivityRule.getActivity();
 
         // Make sure that the agent is ready.
-        JniBindings.waitFor();
+        CtsMain.waitFor();
     }
 }
diff --git a/hostsidetests/jvmti/base/app/src/android/jvmti/cts/JniBindings.java b/hostsidetests/jvmti/base/app/src/art/CtsMain.java
similarity index 70%
rename from hostsidetests/jvmti/base/app/src/android/jvmti/cts/JniBindings.java
rename to hostsidetests/jvmti/base/app/src/art/CtsMain.java
index cc473d2..4970c07 100644
--- a/hostsidetests/jvmti/base/app/src/android/jvmti/cts/JniBindings.java
+++ b/hostsidetests/jvmti/base/app/src/art/CtsMain.java
@@ -12,15 +12,15 @@
  * the License.
  */
 
-package android.jvmti.cts;
+package art;
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
 /**
- * A class that contains all bindings to JNI implementations provided by the CTS JVMTI agent.
+ * An entrypoint for the CTS JVMTI agent to signal to the Java side that it has attached.
  */
-public class JniBindings {
+public class CtsMain {
 
     private static CountDownLatch sStartWaiter = new CountDownLatch(1);
 
@@ -42,13 +42,4 @@
             throw new RuntimeException("Got interrupted waiting for agent.");
         }
     }
-
-    // Load the given class with the given classloader, and bind all native methods to corresponding
-    // C methods in the agent. Will abort if any of the steps fail.
-    public static native void bindAgentJNI(String className, ClassLoader classLoader);
-
-    // General functionality shared between tests.
-    public static native void setTag(Object o, long tag);
-
-    public static native long getTag(Object o);
 }
diff --git a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
index 326ff96..6894a21 100644
--- a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
+++ b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
@@ -19,6 +19,7 @@
 import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
 import com.android.ddmlib.testrunner.TestIdentifier;
 import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.config.Option;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceTestCase;
@@ -41,17 +42,23 @@
  */
 public class JvmtiHostTest extends DeviceTestCase implements IBuildReceiver, IAbiReceiver {
     private static final String RUNNER = "android.support.test.runner.AndroidJUnitRunner";
+    // inject these options from HostTest directly using --set-option <option name>:<option value>
+    @Option(name = "package-name",
+            description = "The package name of the device test",
+            mandatory = true)
+    private String mTestPackageName = null;
+
+    @Option(name = "test-file-name",
+            description = "the name of a test zip file to install on device.",
+            mandatory = true)
+    private String mTestApk = null;
 
     private CompatibilityBuildHelper mBuildHelper;
     private IAbi mAbi;
-    private String mTestPackageName;
-    private String mTestApk;
 
     @Override
     public void setBuild(IBuildInfo arg0) {
         mBuildHelper = new CompatibilityBuildHelper(arg0);
-        mTestPackageName = arg0.getBuildAttributes().get(JvmtiPreparer.PACKAGE_NAME_ATTRIBUTE);
-        mTestApk = arg0.getBuildAttributes().get(JvmtiPreparer.APK_ATTRIBUTE);
     }
 
     @Override
@@ -109,8 +116,8 @@
 
                 String agentInDataData = installLibToDataData(pwd, "libctsjvmtiagent.so");
 
-                String attachReply = mDevice
-                        .executeShellCommand("am attach-agent " + mPkg + " " + agentInDataData);
+                String attachCmd = "cmd activity attach-agent " + mPkg + " " + agentInDataData;
+                String attachReply = mDevice.executeShellCommand(attachCmd);
                 // Don't try to parse the output. The test will time out anyways if this didn't
                 // work.
                 if (attachReply != null && !attachReply.trim().isEmpty()) {
diff --git a/hostsidetests/jvmti/base/jni/Android.mk b/hostsidetests/jvmti/base/jni/Android.mk
index a634c1a..28b7ea3 100644
--- a/hostsidetests/jvmti/base/jni/Android.mk
+++ b/hostsidetests/jvmti/base/jni/Android.mk
@@ -21,9 +21,7 @@
 # Don't include this package in any configuration by default.
 LOCAL_MODULE_TAGS := optional
 
-LOCAL_SRC_FILES := cts_agent.cpp \
-                   jni_binder.cpp \
-                   jvmti_helper.cpp \
+LOCAL_SRC_FILES := cts_agent.cpp
 
 # Tagging.
 LOCAL_SRC_FILES += tagging.cpp
@@ -40,13 +38,17 @@
 LOCAL_SHARED_LIBRARIES := liblog \
                           libdl
 
+# The test implementation. We get this provided by ART.
+# Note: Needs to be "whole" as this exposes JNI functions.
+LOCAL_WHOLE_STATIC_LIBRARIES := libctstiagent
+
 # Platform libraries that are not available to apps. Link in statically.
-LOCAL_STATIC_LIBRARIES := libbase
+LOCAL_STATIC_LIBRARIES += libbase
 
 LOCAL_STRIP_MODULE := keep_symbols
 
 # Turn on all warnings.
-LOCAL_C_FLAGS := -fno-rtti \
+LOCAL_CFLAGS :=  -fno-rtti \
                  -ggdb3 \
                  -Wall \
                  -Wextra \
diff --git a/hostsidetests/jvmti/base/jni/cts_agent.cpp b/hostsidetests/jvmti/base/jni/cts_agent.cpp
index 50f7841..bb1e620 100644
--- a/hostsidetests/jvmti/base/jni/cts_agent.cpp
+++ b/hostsidetests/jvmti/base/jni/cts_agent.cpp
@@ -18,43 +18,33 @@
 #include <jvmti.h>
 
 #include "android-base/logging.h"
-#include "common.h"
 #include "jni_binder.h"
 #include "jvmti_helper.h"
+#include "scoped_local_ref.h"
+#include "test_env.h"
 
-namespace cts {
-namespace jvmti {
+namespace art {
 
-static jvmtiEnv* jvmti_env;
+static void InformMainAttach(jvmtiEnv* jenv,
+                             JNIEnv* env,
+                             const char* class_name,
+                             const char* method_name) {
+  // Use JNI to load the class.
+  ScopedLocalRef<jclass> klass(env, FindClass(jenv, env, class_name, nullptr));
+  CHECK(klass.get() != nullptr) << class_name;
 
-jvmtiEnv* GetJvmtiEnv() {
-  return jvmti_env;
+  jmethodID method = env->GetStaticMethodID(klass.get(), method_name, "()V");
+  CHECK(method != nullptr);
+
+  env->CallStaticVoidMethod(klass.get(), method);
 }
 
-int JniThrowNullPointerException(JNIEnv* env, const char* msg) {
-  JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
-
-  if (env->ExceptionCheck()) {
-    env->ExceptionClear();
-  }
-
-  jclass exc_class = env->FindClass("java/lang/NullPointerException");
-  if (exc_class == nullptr) {
-    return -1;
-  }
-
-  bool ok = env->ThrowNew(exc_class, msg) == JNI_OK;
-
-  env->DeleteLocalRef(exc_class);
-
-  return ok ? 0 : -1;
-}
+static constexpr const char* kMainClass = "art/CtsMain";
+static constexpr const char* kMainClassStartup = "startup";
 
 extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm,
                                                char* options ATTRIBUTE_UNUSED,
                                                void* reserved ATTRIBUTE_UNUSED) {
-  BindOnLoad(vm);
-
   if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
     LOG(FATAL) << "Could not get shared jvmtiEnv";
   }
@@ -66,15 +56,17 @@
 extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm,
                                                  char* options ATTRIBUTE_UNUSED,
                                                  void* reserved ATTRIBUTE_UNUSED) {
-  BindOnAttach(vm);
+  JNIEnv* env;
+  CHECK_EQ(0, vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6))
+      << "Could not get JNIEnv";
 
   if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
     LOG(FATAL) << "Could not get shared jvmtiEnv";
   }
 
   SetAllCapabilities(jvmti_env);
+  InformMainAttach(jvmti_env, env, kMainClass, kMainClassStartup);
   return 0;
 }
 
-}
-}
+}  // namespace art
diff --git a/hostsidetests/jvmti/base/jni/jni_binder.cpp b/hostsidetests/jvmti/base/jni/jni_binder.cpp
deleted file mode 100644
index 14658a1..0000000
--- a/hostsidetests/jvmti/base/jni/jni_binder.cpp
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "jni_binder.h"
-
-#include <dlfcn.h>
-#include <inttypes.h>
-#include <stdio.h>
-
-#include "android-base/logging.h"
-#include "android-base/stringprintf.h"
-#include "common.h"
-#include "jvmti_helper.h"
-#include "scoped_local_ref.h"
-#include "scoped_utf_chars.h"
-
-namespace cts {
-namespace jvmti {
-
-static constexpr const char* kMainClass = "android/jvmti/cts/JniBindings";
-static constexpr const char* kMainClassStartup = "startup";
-
-size_t CountModifiedUtf8Chars(const char* utf8, size_t byte_count) {
-  DCHECK_LE(byte_count, strlen(utf8));
-  size_t len = 0;
-  const char* end = utf8 + byte_count;
-  for (; utf8 < end; ++utf8) {
-    int ic = *utf8;
-    len++;
-    if (LIKELY((ic & 0x80) == 0)) {
-      // One-byte encoding.
-      continue;
-    }
-    // Two- or three-byte encoding.
-    utf8++;
-    if ((ic & 0x20) == 0) {
-      // Two-byte encoding.
-      continue;
-    }
-    utf8++;
-    if ((ic & 0x10) == 0) {
-      // Three-byte encoding.
-      continue;
-    }
-
-    // Four-byte encoding: needs to be converted into a surrogate
-    // pair.
-    utf8++;
-    len++;
-  }
-  return len;
-}
-
-static uint16_t GetTrailingUtf16Char(uint32_t maybe_pair) {
-  return static_cast<uint16_t>(maybe_pair >> 16);
-}
-
-static uint16_t GetLeadingUtf16Char(uint32_t maybe_pair) {
-  return static_cast<uint16_t>(maybe_pair & 0x0000FFFF);
-}
-
-static uint32_t GetUtf16FromUtf8(const char** utf8_data_in) {
-  const uint8_t one = *(*utf8_data_in)++;
-  if ((one & 0x80) == 0) {
-    // one-byte encoding
-    return one;
-  }
-
-  const uint8_t two = *(*utf8_data_in)++;
-  if ((one & 0x20) == 0) {
-    // two-byte encoding
-    return ((one & 0x1f) << 6) | (two & 0x3f);
-  }
-
-  const uint8_t three = *(*utf8_data_in)++;
-  if ((one & 0x10) == 0) {
-    return ((one & 0x0f) << 12) | ((two & 0x3f) << 6) | (three & 0x3f);
-  }
-
-  // Four byte encodings need special handling. We'll have
-  // to convert them into a surrogate pair.
-  const uint8_t four = *(*utf8_data_in)++;
-
-  // Since this is a 4 byte UTF-8 sequence, it will lie between
-  // U+10000 and U+1FFFFF.
-  //
-  // TODO: What do we do about values in (U+10FFFF, U+1FFFFF) ? The
-  // spec says they're invalid but nobody appears to check for them.
-  const uint32_t code_point = ((one & 0x0f) << 18) | ((two & 0x3f) << 12)
-      | ((three & 0x3f) << 6) | (four & 0x3f);
-
-  uint32_t surrogate_pair = 0;
-  // Step two: Write out the high (leading) surrogate to the bottom 16 bits
-  // of the of the 32 bit type.
-  surrogate_pair |= ((code_point >> 10) + 0xd7c0) & 0xffff;
-  // Step three : Write out the low (trailing) surrogate to the top 16 bits.
-  surrogate_pair |= ((code_point & 0x03ff) + 0xdc00) << 16;
-
-  return surrogate_pair;
-}
-
-static std::string MangleForJni(const std::string& s) {
-  std::string result;
-  size_t char_count = CountModifiedUtf8Chars(s.c_str(), s.length());
-  const char* cp = &s[0];
-  for (size_t i = 0; i < char_count; ++i) {
-    uint32_t ch = GetUtf16FromUtf8(&cp);
-    if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
-      result.push_back(ch);
-    } else if (ch == '.' || ch == '/') {
-      result += "_";
-    } else if (ch == '_') {
-      result += "_1";
-    } else if (ch == ';') {
-      result += "_2";
-    } else if (ch == '[') {
-      result += "_3";
-    } else {
-      const uint16_t leading = GetLeadingUtf16Char(ch);
-      const uint32_t trailing = GetTrailingUtf16Char(ch);
-
-      android::base::StringAppendF(&result, "_0%04x", leading);
-      if (trailing != 0) {
-        android::base::StringAppendF(&result, "_0%04x", trailing);
-      }
-    }
-  }
-  return result;
-}
-
-static std::string GetJniShortName(const std::string& class_descriptor, const std::string& method) {
-  // Remove the leading 'L' and trailing ';'...
-  std::string class_name(class_descriptor);
-  CHECK_EQ(class_name[0], 'L') << class_name;
-  CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
-  class_name.erase(0, 1);
-  class_name.erase(class_name.size() - 1, 1);
-
-  std::string short_name;
-  short_name += "Java_";
-  short_name += MangleForJni(class_name);
-  short_name += "_";
-  short_name += MangleForJni(method);
-  return short_name;
-}
-
-static void BindMethod(jvmtiEnv* jvmti_env,
-                       JNIEnv* env,
-                       jclass klass,
-                       jmethodID method) {
-  std::string name;
-  std::string signature;
-  std::string mangled_names[2];
-  {
-    char* name_cstr;
-    char* sig_cstr;
-    jvmtiError name_result = jvmti_env->GetMethodName(method, &name_cstr, &sig_cstr, nullptr);
-    CheckJvmtiError(jvmti_env, name_result);
-    CHECK(name_cstr != nullptr);
-    CHECK(sig_cstr != nullptr);
-    name = name_cstr;
-    signature = sig_cstr;
-
-    char* klass_name;
-    jvmtiError klass_result = jvmti_env->GetClassSignature(klass, &klass_name, nullptr);
-    CheckJvmtiError(jvmti_env, klass_result);
-
-    mangled_names[0] = GetJniShortName(klass_name, name);
-    // TODO: Long JNI name.
-
-    CheckJvmtiError(jvmti_env, Deallocate(jvmti_env, name_cstr));
-    CheckJvmtiError(jvmti_env, Deallocate(jvmti_env, sig_cstr));
-    CheckJvmtiError(jvmti_env, Deallocate(jvmti_env, klass_name));
-  }
-
-  for (const std::string& mangled_name : mangled_names) {
-    if (mangled_name.empty()) {
-      continue;
-    }
-    void* sym = dlsym(RTLD_DEFAULT, mangled_name.c_str());
-    if (sym == nullptr) {
-      continue;
-    }
-
-    JNINativeMethod native_method;
-    native_method.fnPtr = sym;
-    native_method.name = name.c_str();
-    native_method.signature = signature.c_str();
-
-    env->RegisterNatives(klass, &native_method, 1);
-
-    return;
-  }
-
-  LOG(FATAL) << "Could not find " << mangled_names[0];
-}
-
-static std::string DescriptorToDot(const char* descriptor) {
-  size_t length = strlen(descriptor);
-  if (length > 1) {
-    if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
-      // Descriptors have the leading 'L' and trailing ';' stripped.
-      std::string result(descriptor + 1, length - 2);
-      std::replace(result.begin(), result.end(), '/', '.');
-      return result;
-    } else {
-      // For arrays the 'L' and ';' remain intact.
-      std::string result(descriptor);
-      std::replace(result.begin(), result.end(), '/', '.');
-      return result;
-    }
-  }
-  // Do nothing for non-class/array descriptors.
-  return descriptor;
-}
-
-static jobject GetSystemClassLoader(JNIEnv* env) {
-  ScopedLocalRef<jclass> cl_klass(env, env->FindClass("java/lang/ClassLoader"));
-  CHECK(cl_klass.get() != nullptr);
-  jmethodID getsystemclassloader_method = env->GetStaticMethodID(cl_klass.get(),
-                                                                 "getSystemClassLoader",
-                                                                 "()Ljava/lang/ClassLoader;");
-  CHECK(getsystemclassloader_method != nullptr);
-  return env->CallStaticObjectMethod(cl_klass.get(), getsystemclassloader_method);
-}
-
-static jclass FindClassWithClassLoader(JNIEnv* env, const char* class_name, jobject class_loader) {
-  // Create a String of the name.
-  std::string descriptor = android::base::StringPrintf("L%s;", class_name);
-  std::string dot_name = DescriptorToDot(descriptor.c_str());
-  ScopedLocalRef<jstring> name_str(env, env->NewStringUTF(dot_name.c_str()));
-
-  // Call Class.forName with it.
-  ScopedLocalRef<jclass> c_klass(env, env->FindClass("java/lang/Class"));
-  CHECK(c_klass.get() != nullptr);
-  jmethodID forname_method = env->GetStaticMethodID(
-      c_klass.get(),
-      "forName",
-      "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
-  CHECK(forname_method != nullptr);
-
-  return static_cast<jclass>(env->CallStaticObjectMethod(c_klass.get(),
-                                                         forname_method,
-                                                         name_str.get(),
-                                                         JNI_FALSE,
-                                                         class_loader));
-}
-
-// Find the given classname. First try the implied classloader, then the system classloader,
-// then use JVMTI to find all classloaders.
-static jclass FindClass(jvmtiEnv* jvmti_env,
-                        JNIEnv* env,
-                        const char* class_name,
-                        jobject class_loader) {
-  if (class_loader != nullptr) {
-    return FindClassWithClassLoader(env, class_name, class_loader);
-  }
-
-  jclass from_implied = env->FindClass(class_name);
-  if (from_implied != nullptr) {
-    return from_implied;
-  }
-  env->ExceptionClear();
-
-  ScopedLocalRef<jobject> system_class_loader(env, GetSystemClassLoader(env));
-  CHECK(system_class_loader.get() != nullptr);
-  jclass from_system = FindClassWithClassLoader(env, class_name, system_class_loader.get());
-  if (from_system != nullptr) {
-    return from_system;
-  }
-  env->ExceptionClear();
-
-  // Look at the context classloaders of all threads.
-  jint thread_count;
-  jthread* threads;
-  CheckJvmtiError(jvmti_env, jvmti_env->GetAllThreads(&thread_count, &threads));
-  JvmtiUniquePtr threads_uptr = MakeJvmtiUniquePtr(jvmti_env, threads);
-
-  jclass result = nullptr;
-  for (jint t = 0; t != thread_count; ++t) {
-    // Always loop over all elements, as we need to free the local references.
-    if (result == nullptr) {
-      jvmtiThreadInfo info;
-      CheckJvmtiError(jvmti_env, jvmti_env->GetThreadInfo(threads[t], &info));
-      CheckJvmtiError(jvmti_env, Deallocate(jvmti_env, info.name));
-      if (info.thread_group != nullptr) {
-        env->DeleteLocalRef(info.thread_group);
-      }
-      if (info.context_class_loader != nullptr) {
-        result = FindClassWithClassLoader(env, class_name, info.context_class_loader);
-        env->ExceptionClear();
-        env->DeleteLocalRef(info.context_class_loader);
-      }
-    }
-    env->DeleteLocalRef(threads[t]);
-  }
-
-  if (result != nullptr) {
-    return result;
-  }
-
-  // TODO: Implement scanning *all* classloaders.
-  LOG(FATAL) << "Unimplemented";
-
-  return nullptr;
-}
-
-void BindFunctions(jvmtiEnv* jvmti_env, JNIEnv* env, const char* class_name, jobject class_loader) {
-  // Use JNI to load the class.
-  ScopedLocalRef<jclass> klass(env, FindClass(jvmti_env, env, class_name, class_loader));
-  CHECK(klass.get() != nullptr) << class_name;
-
-  // Use JVMTI to get the methods.
-  jint method_count;
-  jmethodID* methods;
-  jvmtiError methods_result = jvmti_env->GetClassMethods(klass.get(), &method_count, &methods);
-  CheckJvmtiError(jvmti_env, methods_result);
-
-  // Check each method.
-  for (jint i = 0; i < method_count; ++i) {
-    jint modifiers;
-    jvmtiError mod_result = jvmti_env->GetMethodModifiers(methods[i], &modifiers);
-    CheckJvmtiError(jvmti_env, mod_result);
-    constexpr jint kNative = static_cast<jint>(0x0100);
-    if ((modifiers & kNative) != 0) {
-      BindMethod(jvmti_env, env, klass.get(), methods[i]);
-    }
-  }
-
-  CheckJvmtiError(jvmti_env, Deallocate(jvmti_env, methods));
-}
-
-// Inform the main instrumentation class of our successful attach.
-static void InformMainAttach(jvmtiEnv* jvmti_env,
-                             JNIEnv* jni_env,
-                             const char* class_name,
-                             const char* method_name) {
-  // Use JNI to load the class.
-  ScopedLocalRef<jclass> klass(jni_env, FindClass(jvmti_env, jni_env, class_name, nullptr));
-  CHECK(klass.get() != nullptr) << class_name;
-
-  jmethodID method = jni_env->GetStaticMethodID(klass.get(), method_name, "()V");
-  CHECK(method != nullptr);
-
-  jni_env->CallStaticVoidMethod(klass.get(), method);
-}
-
-// TODO: Check this. This may not work on device. The classloader containing the app's classes
-//       may not have been created at this point (i.e., if it's not the system classloader).
-static void JNICALL VMInitCallback(jvmtiEnv* jvmti_env,
-                                   JNIEnv* jni_env,
-                                   jthread thread ATTRIBUTE_UNUSED) {
-  // Bind kMainClass native methods.
-  BindFunctions(jvmti_env, jni_env, kMainClass);
-
-  // And let the test know that we have started up.
-  InformMainAttach(jvmti_env, jni_env, kMainClass, kMainClassStartup);
-
-  // And delete the jvmtiEnv.
-  jvmti_env->DisposeEnvironment();
-}
-
-// Install a phase callback that will bind JNI functions on VMInit.
-void BindOnLoad(JavaVM* vm) {
-  // Use a new jvmtiEnv. Otherwise we might collide with table changes.
-  jvmtiEnv* install_env;
-  if (vm->GetEnv(reinterpret_cast<void**>(&install_env), JVMTI_VERSION_1_0) != 0) {
-    LOG(FATAL) << "Could not get jvmtiEnv";
-  }
-  SetAllCapabilities(install_env);
-
-  {
-    jvmtiEventCallbacks callbacks;
-    memset(&callbacks, 0, sizeof(jvmtiEventCallbacks));
-    callbacks.VMInit = VMInitCallback;
-
-    CheckJvmtiError(install_env, install_env->SetEventCallbacks(&callbacks, sizeof(callbacks)));
-  }
-
-  {
-    CheckJvmtiError(install_env, install_env->SetEventNotificationMode(JVMTI_ENABLE,
-                                                                       JVMTI_EVENT_VM_INIT,
-                                                                       nullptr));
-  }
-}
-
-// Ensure binding of the Main class when the agent is started through OnAttach.
-void BindOnAttach(JavaVM* vm) {
-  // Get a JNIEnv. As the thread is attached, we must not destroy it.
-  JNIEnv* env;
-  if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != 0) {
-    LOG(FATAL) << "Could not get JNIEnv";
-  }
-
-  jvmtiEnv* jvmti_env;
-  if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
-    LOG(FATAL) << "Could not get jvmtiEnv";
-  }
-  SetAllCapabilities(jvmti_env);
-
-  BindFunctions(jvmti_env, env, kMainClass);
-
-  // And let the test know that we have started up.
-  InformMainAttach(jvmti_env, env, kMainClass, kMainClassStartup);
-
-  if (jvmti_env->DisposeEnvironment() != JVMTI_ERROR_NONE) {
-    LOG(FATAL) << "Could not dispose temporary jvmtiEnv";
-  }
-}
-
-extern "C" JNIEXPORT void JNICALL Java_android_jvmti_cts_JniBindings_bindAgentJNI(
-    JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jstring className, jobject classLoader) {
-  ScopedUtfChars name(env, className);
-  BindFunctions(GetJvmtiEnv(), env, name.c_str(), classLoader);
-}
-
-}  // namespace jvmti
-}  // namespace cts
diff --git a/hostsidetests/jvmti/base/jni/jni_binder.h b/hostsidetests/jvmti/base/jni/jni_binder.h
deleted file mode 100644
index fb311ee..0000000
--- a/hostsidetests/jvmti/base/jni/jni_binder.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef JNI_BINDER_H_
-#define JNI_BINDER_H_
-
-#include "jni.h"
-#include "jvmti.h"
-
-namespace cts {
-namespace jvmti {
-
-// Load the class through JNI. Inspect it, find all native methods. Construct the corresponding
-// mangled name, run dlsym and bind the method.
-//
-// This will abort on failure.
-void BindFunctions(jvmtiEnv* jvmti_env,
-                   JNIEnv* env,
-                   const char* class_name,
-                   jobject class_loader = nullptr);
-
-// Ensure binding of the Main class when the agent is started through OnLoad.
-void BindOnLoad(JavaVM* vm);
-
-// Ensure binding of the Main class when the agent is started through OnAttach.
-void BindOnAttach(JavaVM* vm);
-
-}  // namespace jvmti
-}  // namespace cts
-
-#endif  // JNI_BINDER_H_
diff --git a/hostsidetests/jvmti/base/jni/jni_helper.h b/hostsidetests/jvmti/base/jni/jni_helper.h
deleted file mode 100644
index 14aba8b..0000000
--- a/hostsidetests/jvmti/base/jni/jni_helper.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef JNI_HELPER_H_
-#define JNI_HELPER_H_
-
-#include "jni.h"
-#include "scoped_local_ref.h"
-
-namespace cts {
-namespace jvmti {
-
-// Create an object array using a lambda that returns a local ref for each element.
-template <typename T>
-static jobjectArray CreateObjectArray(JNIEnv* env,
-                                      jint length,
-                                      const char* component_type_descriptor,
-                                      T src) {
-  if (length < 0) {
-    return nullptr;
-  }
-
-  ScopedLocalRef<jclass> obj_class(env, env->FindClass(component_type_descriptor));
-  if (obj_class.get() == nullptr) {
-    return nullptr;
-  }
-
-  ScopedLocalRef<jobjectArray> ret(env, env->NewObjectArray(length, obj_class.get(), nullptr));
-  if (ret.get() == nullptr) {
-    return nullptr;
-  }
-
-  for (jint i = 0; i < length; ++i) {
-    jobject element = src(i);
-    env->SetObjectArrayElement(ret.get(), static_cast<jint>(i), element);
-    env->DeleteLocalRef(element);
-    if (env->ExceptionCheck()) {
-      return nullptr;
-    }
-  }
-
-  return ret.release();
-}
-
-}  // namespace jvmti
-}  // namespace cts
-
-#endif  // JNI_HELPER_H_
diff --git a/hostsidetests/jvmti/base/jni/jvmti_helper.cpp b/hostsidetests/jvmti/base/jni/jvmti_helper.cpp
deleted file mode 100644
index a8a1aec..0000000
--- a/hostsidetests/jvmti/base/jni/jvmti_helper.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "jvmti_helper.h"
-
-#include <algorithm>
-#include <dlfcn.h>
-#include <stdio.h>
-#include <sstream>
-#include <string.h>
-
-#include "android-base/logging.h"
-#include "scoped_local_ref.h"
-
-namespace cts {
-namespace jvmti {
-
-void CheckJvmtiError(jvmtiEnv* env, jvmtiError error) {
-  if (error != JVMTI_ERROR_NONE) {
-    char* error_name;
-    jvmtiError name_error = env->GetErrorName(error, &error_name);
-    if (name_error != JVMTI_ERROR_NONE) {
-      LOG(FATAL) << "Unable to get error name for " << error;
-    }
-    LOG(FATAL) << "Unexpected error: " << error_name;
-  }
-}
-
-void SetAllCapabilities(jvmtiEnv* env) {
-  jvmtiCapabilities caps;
-  jvmtiError error1 = env->GetPotentialCapabilities(&caps);
-  CheckJvmtiError(env, error1);
-  jvmtiError error2 = env->AddCapabilities(&caps);
-  CheckJvmtiError(env, error2);
-}
-
-bool JvmtiErrorToException(JNIEnv* env, jvmtiEnv* jvmti_env, jvmtiError error) {
-  if (error == JVMTI_ERROR_NONE) {
-    return false;
-  }
-
-  ScopedLocalRef<jclass> rt_exception(env, env->FindClass("java/lang/RuntimeException"));
-  if (rt_exception.get() == nullptr) {
-    // CNFE should be pending.
-    return true;
-  }
-
-  char* err;
-  CheckJvmtiError(jvmti_env, jvmti_env->GetErrorName(error, &err));
-
-  env->ThrowNew(rt_exception.get(), err);
-
-  Deallocate(jvmti_env, err);
-  return true;
-}
-
-std::ostream& operator<<(std::ostream& os, const jvmtiError& rhs) {
-  switch (rhs) {
-    case JVMTI_ERROR_NONE:
-      return os << "NONE";
-    case JVMTI_ERROR_INVALID_THREAD:
-      return os << "INVALID_THREAD";
-    case JVMTI_ERROR_INVALID_THREAD_GROUP:
-      return os << "INVALID_THREAD_GROUP";
-    case JVMTI_ERROR_INVALID_PRIORITY:
-      return os << "INVALID_PRIORITY";
-    case JVMTI_ERROR_THREAD_NOT_SUSPENDED:
-      return os << "THREAD_NOT_SUSPENDED";
-    case JVMTI_ERROR_THREAD_SUSPENDED:
-      return os << "THREAD_SUSPENDED";
-    case JVMTI_ERROR_THREAD_NOT_ALIVE:
-      return os << "THREAD_NOT_ALIVE";
-    case JVMTI_ERROR_INVALID_OBJECT:
-      return os << "INVALID_OBJECT";
-    case JVMTI_ERROR_INVALID_CLASS:
-      return os << "INVALID_CLASS";
-    case JVMTI_ERROR_CLASS_NOT_PREPARED:
-      return os << "CLASS_NOT_PREPARED";
-    case JVMTI_ERROR_INVALID_METHODID:
-      return os << "INVALID_METHODID";
-    case JVMTI_ERROR_INVALID_LOCATION:
-      return os << "INVALID_LOCATION";
-    case JVMTI_ERROR_INVALID_FIELDID:
-      return os << "INVALID_FIELDID";
-    case JVMTI_ERROR_NO_MORE_FRAMES:
-      return os << "NO_MORE_FRAMES";
-    case JVMTI_ERROR_OPAQUE_FRAME:
-      return os << "OPAQUE_FRAME";
-    case JVMTI_ERROR_TYPE_MISMATCH:
-      return os << "TYPE_MISMATCH";
-    case JVMTI_ERROR_INVALID_SLOT:
-      return os << "INVALID_SLOT";
-    case JVMTI_ERROR_DUPLICATE:
-      return os << "DUPLICATE";
-    case JVMTI_ERROR_NOT_FOUND:
-      return os << "NOT_FOUND";
-    case JVMTI_ERROR_INVALID_MONITOR:
-      return os << "INVALID_MONITOR";
-    case JVMTI_ERROR_NOT_MONITOR_OWNER:
-      return os << "NOT_MONITOR_OWNER";
-    case JVMTI_ERROR_INTERRUPT:
-      return os << "INTERRUPT";
-    case JVMTI_ERROR_INVALID_CLASS_FORMAT:
-      return os << "INVALID_CLASS_FORMAT";
-    case JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION:
-      return os << "CIRCULAR_CLASS_DEFINITION";
-    case JVMTI_ERROR_FAILS_VERIFICATION:
-      return os << "FAILS_VERIFICATION";
-    case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED:
-      return os << "UNSUPPORTED_REDEFINITION_METHOD_ADDED";
-    case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED:
-      return os << "UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED";
-    case JVMTI_ERROR_INVALID_TYPESTATE:
-      return os << "INVALID_TYPESTATE";
-    case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED:
-      return os << "UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED";
-    case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED:
-      return os << "UNSUPPORTED_REDEFINITION_METHOD_DELETED";
-    case JVMTI_ERROR_UNSUPPORTED_VERSION:
-      return os << "UNSUPPORTED_VERSION";
-    case JVMTI_ERROR_NAMES_DONT_MATCH:
-      return os << "NAMES_DONT_MATCH";
-    case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED:
-      return os << "UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED";
-    case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED:
-      return os << "UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED";
-    case JVMTI_ERROR_UNMODIFIABLE_CLASS:
-      return os << "JVMTI_ERROR_UNMODIFIABLE_CLASS";
-    case JVMTI_ERROR_NOT_AVAILABLE:
-      return os << "NOT_AVAILABLE";
-    case JVMTI_ERROR_MUST_POSSESS_CAPABILITY:
-      return os << "MUST_POSSESS_CAPABILITY";
-    case JVMTI_ERROR_NULL_POINTER:
-      return os << "NULL_POINTER";
-    case JVMTI_ERROR_ABSENT_INFORMATION:
-      return os << "ABSENT_INFORMATION";
-    case JVMTI_ERROR_INVALID_EVENT_TYPE:
-      return os << "INVALID_EVENT_TYPE";
-    case JVMTI_ERROR_ILLEGAL_ARGUMENT:
-      return os << "ILLEGAL_ARGUMENT";
-    case JVMTI_ERROR_NATIVE_METHOD:
-      return os << "NATIVE_METHOD";
-    case JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED:
-      return os << "CLASS_LOADER_UNSUPPORTED";
-    case JVMTI_ERROR_OUT_OF_MEMORY:
-      return os << "OUT_OF_MEMORY";
-    case JVMTI_ERROR_ACCESS_DENIED:
-      return os << "ACCESS_DENIED";
-    case JVMTI_ERROR_WRONG_PHASE:
-      return os << "WRONG_PHASE";
-    case JVMTI_ERROR_INTERNAL:
-      return os << "INTERNAL";
-    case JVMTI_ERROR_UNATTACHED_THREAD:
-      return os << "UNATTACHED_THREAD";
-    case JVMTI_ERROR_INVALID_ENVIRONMENT:
-      return os << "INVALID_ENVIRONMENT";
-  }
-  LOG(FATAL) << "Unexpected error type " << static_cast<int>(rhs);
-  __builtin_unreachable();
-}
-
-}  // namespace jvmti
-}  // namespace cts
diff --git a/hostsidetests/jvmti/base/jni/jvmti_helper.h b/hostsidetests/jvmti/base/jni/jvmti_helper.h
deleted file mode 100644
index 898fa96..0000000
--- a/hostsidetests/jvmti/base/jni/jvmti_helper.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef JVMTI_HELPER_H_
-#define JVMTI_HELPER_H_
-
-#include "jni.h"
-#include "jvmti.h"
-#include <memory>
-#include <ostream>
-
-#include "android-base/logging.h"
-
-namespace cts {
-namespace jvmti {
-
-// Add all capabilities to the given env.
-void SetAllCapabilities(jvmtiEnv* env);
-
-// Check whether the given error is NONE. If not, print out the corresponding error message
-// and abort.
-void CheckJvmtiError(jvmtiEnv* env, jvmtiError error);
-
-// Convert the given error to a RuntimeException with a message derived from the error. Returns
-// true on error, false if error is JVMTI_ERROR_NONE.
-bool JvmtiErrorToException(JNIEnv* env, jvmtiEnv* jvmti_env, jvmtiError error);
-
-class JvmtiDeleter {
- public:
-  JvmtiDeleter() : env_(nullptr) {}
-  explicit JvmtiDeleter(jvmtiEnv* env) : env_(env) {}
-
-  JvmtiDeleter(JvmtiDeleter&) = default;
-  JvmtiDeleter(JvmtiDeleter&&) = default;
-  JvmtiDeleter& operator=(const JvmtiDeleter&) = default;
-
-  void operator()(unsigned char* ptr) const {
-    CHECK(env_ != nullptr);
-    jvmtiError ret = env_->Deallocate(ptr);
-    CheckJvmtiError(env_, ret);
-  }
-
- private:
-  mutable jvmtiEnv* env_;
-};
-
-using JvmtiUniquePtr = std::unique_ptr<unsigned char, JvmtiDeleter>;
-
-template <typename T>
-static inline JvmtiUniquePtr MakeJvmtiUniquePtr(jvmtiEnv* env, T* mem) {
-  return JvmtiUniquePtr(reinterpret_cast<unsigned char*>(mem), JvmtiDeleter(env));
-}
-
-template <typename T>
-static inline jvmtiError Deallocate(jvmtiEnv* env, T* mem) {
-  return env->Deallocate(reinterpret_cast<unsigned char*>(mem));
-}
-
-// To print jvmtiError. Does not rely on GetErrorName, so is an approximation.
-std::ostream& operator<<(std::ostream& os, const jvmtiError& rhs);
-
-}  // namespace jvmti
-}  // namespace cts
-
-#endif  // JVMTI_HELPER_H_
diff --git a/hostsidetests/jvmti/base/jni/redefine.cpp b/hostsidetests/jvmti/base/jni/redefine.cpp
index d948b2c..c6e8726 100644
--- a/hostsidetests/jvmti/base/jni/redefine.cpp
+++ b/hostsidetests/jvmti/base/jni/redefine.cpp
@@ -23,15 +23,13 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
-#include "common.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
 #include "scoped_primitive_array.h"
+#include "test_env.h"
 
-namespace cts {
-namespace jvmti {
-namespace redefine {
+namespace art {
 
 extern "C" JNIEXPORT jint JNICALL Java_android_jvmti_cts_JvmtiRedefineClassesTest_redefineClass(
     JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jclass target, jbyteArray dex_bytes) {
@@ -39,21 +37,21 @@
   def.klass = target;
   def.class_byte_count = static_cast<jint>(env->GetArrayLength(dex_bytes));
   signed char* redef_bytes = env->GetByteArrayElements(dex_bytes, nullptr);
-  jvmtiError res = GetJvmtiEnv()->Allocate(def.class_byte_count,
-                                           const_cast<unsigned char**>(&def.class_bytes));
+  jvmtiError res =jvmti_env->Allocate(def.class_byte_count,
+                                      const_cast<unsigned char**>(&def.class_bytes));
   if (res != JVMTI_ERROR_NONE) {
     return static_cast<jint>(res);
   }
   memcpy(const_cast<unsigned char*>(def.class_bytes), redef_bytes, def.class_byte_count);
   env->ReleaseByteArrayElements(dex_bytes, redef_bytes, 0);
   // Do the redefinition.
-  res = GetJvmtiEnv()->RedefineClasses(1, &def);
+  res = jvmti_env->RedefineClasses(1, &def);
   return static_cast<jint>(res);
 }
 
 extern "C" JNIEXPORT jint JNICALL Java_android_jvmti_cts_JvmtiRedefineClassesTest_retransformClass(
     JNIEnv* env ATTRIBUTE_UNUSED, jclass klass ATTRIBUTE_UNUSED, jclass target) {
-  return GetJvmtiEnv()->RetransformClasses(1, &target);
+  return jvmti_env->RetransformClasses(1, &target);
 }
 
 class TransformationData {
@@ -105,7 +103,7 @@
 static TransformationData data;
 
 // The hook we are using.
-void JNICALL CommonClassFileLoadHookRetransformable(jvmtiEnv* jvmti_env,
+void JNICALL CommonClassFileLoadHookRetransformable(jvmtiEnv* local_jvmti_env,
                                                     JNIEnv* jni_env ATTRIBUTE_UNUSED,
                                                     jclass class_being_redefined ATTRIBUTE_UNUSED,
                                                     jobject loader ATTRIBUTE_UNUSED,
@@ -119,7 +117,7 @@
   std::vector<unsigned char> dex_data;
   if (data.RetrieveRedefinition(name_str, &dex_data)) {
     unsigned char* jvmti_dex_data;
-    if (JVMTI_ERROR_NONE != jvmti_env->Allocate(dex_data.size(), &jvmti_dex_data)) {
+    if (JVMTI_ERROR_NONE != local_jvmti_env->Allocate(dex_data.size(), &jvmti_dex_data)) {
       LOG(FATAL) << "Unable to allocate output buffer for " << name;
       return;
     }
@@ -136,12 +134,12 @@
   jvmtiEventCallbacks cb;
   memset(&cb, 0, sizeof(cb));
   cb.ClassFileLoadHook = CommonClassFileLoadHookRetransformable;
-  if (JvmtiErrorToException(env, GetJvmtiEnv(),
-                            GetJvmtiEnv()->SetEventCallbacks(&cb, sizeof(cb)))) {
+  if (JvmtiErrorToException(env, jvmti_env, jvmti_env->SetEventCallbacks(&cb, sizeof(cb)))) {
     return;
   }
-  JvmtiErrorToException(env, GetJvmtiEnv(),
-                        GetJvmtiEnv()->SetEventNotificationMode(
+  JvmtiErrorToException(env,
+                        jvmti_env,
+                        jvmti_env->SetEventNotificationMode(
                             enable == JNI_TRUE ? JVMTI_ENABLE : JVMTI_DISABLE,
                             JVMTI_EVENT_CLASS_FILE_LOAD_HOOK,
                             nullptr));
@@ -174,7 +172,5 @@
   env->ReleaseByteArrayElements(dex_bytes, redef_bytes, 0);
 }
 
-}  // namespace redefine
-}  // namespace jvmti
-}  // namespace cts
+}  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/scoped_local_ref.h b/hostsidetests/jvmti/base/jni/scoped_local_ref.h
deleted file mode 100644
index 4622480..0000000
--- a/hostsidetests/jvmti/base/jni/scoped_local_ref.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-#ifndef SCOPED_LOCAL_REF_H_
-#define SCOPED_LOCAL_REF_H_
-
-#include "jni.h"
-
-#include <stddef.h>
-
-#include "android-base/macros.h"
-
-namespace cts {
-namespace jvmti {
-
-template<typename T>
-class ScopedLocalRef {
-public:
-    ScopedLocalRef(JNIEnv* env, T localRef) : mEnv(env), mLocalRef(localRef) {
-    }
-
-    ~ScopedLocalRef() {
-        reset();
-    }
-
-    void reset(T ptr = NULL) {
-        if (ptr != mLocalRef) {
-            if (mLocalRef != NULL) {
-                mEnv->DeleteLocalRef(mLocalRef);
-            }
-            mLocalRef = ptr;
-        }
-    }
-
-    T release() __attribute__((warn_unused_result)) {
-        T localRef = mLocalRef;
-        mLocalRef = NULL;
-        return localRef;
-    }
-
-    T get() const {
-        return mLocalRef;
-    }
-
-private:
-    JNIEnv* const mEnv;
-    T mLocalRef;
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedLocalRef);
-};
-
-}
-}
-
-#endif  // SCOPED_LOCAL_REF_H_
diff --git a/hostsidetests/jvmti/base/jni/scoped_primitive_array.h b/hostsidetests/jvmti/base/jni/scoped_primitive_array.h
deleted file mode 100644
index c030b7d..0000000
--- a/hostsidetests/jvmti/base/jni/scoped_primitive_array.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-#ifndef SCOPED_PRIMITIVE_ARRAY_H_
-#define SCOPED_PRIMITIVE_ARRAY_H_
-
-#include "jni.h"
-
-#include "android-base/macros.h"
-#include "common.h"
-
-namespace cts {
-namespace jvmti {
-
-#ifdef POINTER_TYPE
-#error POINTER_TYPE is defined.
-#else
-#define POINTER_TYPE(T) T*  /* NOLINT */
-#endif
-
-#ifdef REFERENCE_TYPE
-#error REFERENCE_TYPE is defined.
-#else
-#define REFERENCE_TYPE(T) T&  /* NOLINT */
-#endif
-
-// ScopedBooleanArrayRO, ScopedByteArrayRO, ScopedCharArrayRO, ScopedDoubleArrayRO,
-// ScopedFloatArrayRO, ScopedIntArrayRO, ScopedLongArrayRO, and ScopedShortArrayRO provide
-// convenient read-only access to Java arrays from JNI code. This is cheaper than read-write
-// access and should be used by default.
-#define INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(PRIMITIVE_TYPE, NAME) \
-    class Scoped ## NAME ## ArrayRO { \
-    public: \
-        explicit Scoped ## NAME ## ArrayRO(JNIEnv* env) \
-        : mEnv(env), mJavaArray(nullptr), mRawArray(nullptr), mSize(0) {} \
-        Scoped ## NAME ## ArrayRO(JNIEnv* env, PRIMITIVE_TYPE ## Array javaArray) \
-        : mEnv(env) { \
-            if (javaArray == nullptr) { \
-                mJavaArray = nullptr; \
-                mSize = 0; \
-                mRawArray = nullptr; \
-                JniThrowNullPointerException(env, nullptr); \
-            } else { \
-                reset(javaArray); \
-            } \
-        } \
-        ~Scoped ## NAME ## ArrayRO() { \
-            if (mRawArray != nullptr && mRawArray != mBuffer) { \
-                mEnv->Release ## NAME ## ArrayElements(mJavaArray, mRawArray, JNI_ABORT); \
-            } \
-        } \
-        void reset(PRIMITIVE_TYPE ## Array javaArray) { \
-            mJavaArray = javaArray; \
-            mSize = mEnv->GetArrayLength(mJavaArray); \
-            if (mSize <= buffer_size) { \
-                mEnv->Get ## NAME ## ArrayRegion(mJavaArray, 0, mSize, mBuffer); \
-                mRawArray = mBuffer; \
-            } else { \
-                mRawArray = mEnv->Get ## NAME ## ArrayElements(mJavaArray, nullptr); \
-            } \
-        } \
-        const PRIMITIVE_TYPE* get() const { return mRawArray; } \
-        PRIMITIVE_TYPE ## Array getJavaArray() const { return mJavaArray; } \
-        const PRIMITIVE_TYPE& operator[](size_t n) const { return mRawArray[n]; } \
-        size_t size() const { return mSize; } \
-    private: \
-        static const jsize buffer_size = 1024; \
-        JNIEnv* const mEnv; \
-        PRIMITIVE_TYPE ## Array mJavaArray; \
-        POINTER_TYPE(PRIMITIVE_TYPE) mRawArray; \
-        jsize mSize; \
-        PRIMITIVE_TYPE mBuffer[buffer_size]; \
-        DISALLOW_COPY_AND_ASSIGN(Scoped ## NAME ## ArrayRO); \
-    }
-
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jboolean, Boolean);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jbyte, Byte);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jchar, Char);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jdouble, Double);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jfloat, Float);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jint, Int);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jlong, Long);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jshort, Short);
-
-#undef INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO
-
-// ScopedBooleanArrayRW, ScopedByteArrayRW, ScopedCharArrayRW, ScopedDoubleArrayRW,
-// ScopedFloatArrayRW, ScopedIntArrayRW, ScopedLongArrayRW, and ScopedShortArrayRW provide
-// convenient read-write access to Java arrays from JNI code. These are more expensive,
-// since they entail a copy back onto the Java heap, and should only be used when necessary.
-#define INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(PRIMITIVE_TYPE, NAME) \
-    class Scoped ## NAME ## ArrayRW { \
-    public: \
-        explicit Scoped ## NAME ## ArrayRW(JNIEnv* env) \
-        : mEnv(env), mJavaArray(nullptr), mRawArray(nullptr) {} \
-        Scoped ## NAME ## ArrayRW(JNIEnv* env, PRIMITIVE_TYPE ## Array javaArray) \
-        : mEnv(env), mJavaArray(javaArray), mRawArray(nullptr) { \
-            if (mJavaArray == nullptr) { \
-                JniThrowNullPointerException(env, nullptr); \
-            } else { \
-                mRawArray = mEnv->Get ## NAME ## ArrayElements(mJavaArray, nullptr); \
-            } \
-        } \
-        ~Scoped ## NAME ## ArrayRW() { \
-            if (mRawArray) { \
-                mEnv->Release ## NAME ## ArrayElements(mJavaArray, mRawArray, 0); \
-            } \
-        } \
-        void reset(PRIMITIVE_TYPE ## Array javaArray) { \
-            mJavaArray = javaArray; \
-            mRawArray = mEnv->Get ## NAME ## ArrayElements(mJavaArray, nullptr); \
-        } \
-        const PRIMITIVE_TYPE* get() const { return mRawArray; } \
-        PRIMITIVE_TYPE ## Array getJavaArray() const { return mJavaArray; } \
-        const PRIMITIVE_TYPE& operator[](size_t n) const { return mRawArray[n]; } \
-        POINTER_TYPE(PRIMITIVE_TYPE) get() { return mRawArray; }  \
-        REFERENCE_TYPE(PRIMITIVE_TYPE) operator[](size_t n) { return mRawArray[n]; } \
-        size_t size() const { return mEnv->GetArrayLength(mJavaArray); } \
-    private: \
-        JNIEnv* const mEnv; \
-        PRIMITIVE_TYPE ## Array mJavaArray; \
-        POINTER_TYPE(PRIMITIVE_TYPE) mRawArray; \
-        DISALLOW_COPY_AND_ASSIGN(Scoped ## NAME ## ArrayRW); \
-    }
-
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jboolean, Boolean);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jbyte, Byte);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jchar, Char);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jdouble, Double);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jfloat, Float);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jint, Int);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jlong, Long);
-INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(jshort, Short);
-
-#undef INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW
-#undef POINTER_TYPE
-#undef REFERENCE_TYPE
-
-}
-}
-
-#endif  // SCOPED_PRIMITIVE_ARRAY_H_
diff --git a/hostsidetests/jvmti/base/jni/scoped_utf_chars.h b/hostsidetests/jvmti/base/jni/scoped_utf_chars.h
deleted file mode 100644
index 8d28a7a..0000000
--- a/hostsidetests/jvmti/base/jni/scoped_utf_chars.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-#ifndef SCOPED_UTF_CHARS_H_
-#define SCOPED_UTF_CHARS_H_
-
-#include "jni.h"
-
-#include <string.h>
-
-#include "android-base/macros.h"
-#include "common.h"
-
-namespace cts {
-namespace jvmti {
-
-class ScopedUtfChars {
- public:
-  ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) {
-    if (s == nullptr) {
-      utf_chars_ = nullptr;
-      JniThrowNullPointerException(env, nullptr);
-    } else {
-      utf_chars_ = env->GetStringUTFChars(s, nullptr);
-    }
-  }
-
-  ScopedUtfChars(ScopedUtfChars&& rhs) :
-      env_(rhs.env_), string_(rhs.string_), utf_chars_(rhs.utf_chars_) {
-    rhs.env_ = nullptr;
-    rhs.string_ = nullptr;
-    rhs.utf_chars_ = nullptr;
-  }
-
-  ~ScopedUtfChars() {
-    if (utf_chars_) {
-      env_->ReleaseStringUTFChars(string_, utf_chars_);
-    }
-  }
-
-  ScopedUtfChars& operator=(ScopedUtfChars&& rhs) {
-    if (this != &rhs) {
-      // Delete the currently owned UTF chars.
-      this->~ScopedUtfChars();
-
-      // Move the rhs ScopedUtfChars and zero it out.
-      env_ = rhs.env_;
-      string_ = rhs.string_;
-      utf_chars_ = rhs.utf_chars_;
-      rhs.env_ = nullptr;
-      rhs.string_ = nullptr;
-      rhs.utf_chars_ = nullptr;
-    }
-    return *this;
-  }
-
-  const char* c_str() const {
-    return utf_chars_;
-  }
-
-  size_t size() const {
-    return strlen(utf_chars_);
-  }
-
-  const char& operator[](size_t n) const {
-    return utf_chars_[n];
-  }
-
- private:
-  JNIEnv* env_;
-  jstring string_;
-  const char* utf_chars_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedUtfChars);
-};
-
-}
-}
-
-#endif  // SCOPED_UTF_CHARS_H_
diff --git a/hostsidetests/jvmti/base/jni/tagging.cpp b/hostsidetests/jvmti/base/jni/tagging.cpp
index 1e59e13..372805b 100644
--- a/hostsidetests/jvmti/base/jni/tagging.cpp
+++ b/hostsidetests/jvmti/base/jni/tagging.cpp
@@ -18,26 +18,22 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
-#include "common.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
 #include "scoped_primitive_array.h"
+#include "test_env.h"
 
-namespace cts {
-namespace jvmti {
-namespace tagging {
+namespace art {
 
 extern "C" JNIEXPORT void JNICALL Java_android_jvmti_cts_JniBindings_setTag(
     JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jobject obj, jlong tag) {
-  jvmtiEnv* jvmti_env = GetJvmtiEnv();
   jvmtiError ret = jvmti_env->SetTag(obj, tag);
   JvmtiErrorToException(env, jvmti_env, ret);
 }
 
 extern "C" JNIEXPORT jlong JNICALL Java_android_jvmti_cts_JniBindings_getTag(
     JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jobject obj) {
-  jvmtiEnv* jvmti_env = GetJvmtiEnv();
   jlong tag = 0;
   jvmtiError ret = jvmti_env->GetTag(obj, &tag);
   if (JvmtiErrorToException(env, jvmti_env, ret)) {
@@ -52,7 +48,6 @@
     jlongArray searchTags,
     jboolean returnObjects,
     jboolean returnTags) {
-  jvmtiEnv* jvmti_env = GetJvmtiEnv();
   ScopedLongArrayRO scoped_array(env);
   if (searchTags != nullptr) {
     scoped_array.reset(searchTags);
@@ -132,7 +127,5 @@
   return CreateObjectArray(env, 3, "java/lang/Object", callback);
 }
 
-}  // namespace tagging
-}  // namespace jvmti
-}  // namespace cts
+}  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tracking.cpp b/hostsidetests/jvmti/base/jni/tracking.cpp
index a46f491..a07d653 100644
--- a/hostsidetests/jvmti/base/jni/tracking.cpp
+++ b/hostsidetests/jvmti/base/jni/tracking.cpp
@@ -21,14 +21,12 @@
 
 #include "android-base/logging.h"
 #include "android-base/stringprintf.h"
-#include "common.h"
 #include "jvmti_helper.h"
 #include "scoped_local_ref.h"
 #include "scoped_utf_chars.h"
+#include "test_env.h"
 
-namespace cts {
-namespace jvmti {
-namespace allocation_tracking {
+namespace art {
 
 static std::string GetClassName(JNIEnv* jni_env, jclass cls) {
   ScopedLocalRef<jclass> class_class(jni_env, jni_env->GetObjectClass(cls));
@@ -65,17 +63,17 @@
   memset(&callbacks, 0, sizeof(jvmtiEventCallbacks));
   callbacks.VMObjectAlloc = enable ? ObjectAllocated : nullptr;
 
-  jvmtiError ret = GetJvmtiEnv()->SetEventCallbacks(&callbacks, sizeof(callbacks));
-  JvmtiErrorToException(env, GetJvmtiEnv(), ret);
+  jvmtiError ret = jvmti_env->SetEventCallbacks(&callbacks, sizeof(callbacks));
+  JvmtiErrorToException(env, jvmti_env, ret);
 }
 
 extern "C" JNIEXPORT void JNICALL Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking(
     JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jthread thread, jboolean enable) {
-  jvmtiError ret = GetJvmtiEnv()->SetEventNotificationMode(
+  jvmtiError ret = jvmti_env->SetEventNotificationMode(
       enable ? JVMTI_ENABLE : JVMTI_DISABLE,
       JVMTI_EVENT_VM_OBJECT_ALLOC,
       thread);
-  JvmtiErrorToException(env, GetJvmtiEnv(), ret);
+  JvmtiErrorToException(env, jvmti_env, ret);
 }
 
 extern "C" JNIEXPORT
@@ -95,6 +93,4 @@
   return env->NewStringUTF(result.c_str());
 }
 
-}  // namespace allocation_tracking
-}  // namespace jvmti
-}  // namespace cts
+}  // namespace art
diff --git a/hostsidetests/jvmti/base/run-test-based-app/Android.mk b/hostsidetests/jvmti/base/run-test-based-app/Android.mk
new file mode 100644
index 0000000..7c8b417
--- /dev/null
+++ b/hostsidetests/jvmti/base/run-test-based-app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := CtsJvmtiDeviceRunTestAppBase
+
+# We explicitly enumerate, as we have a definition of art.Main to simplify development
+# in an IDE (but want the implementation of said class to come from the ART run-tests).
+LOCAL_SRC_FILES := \
+  src/android/jvmti/cts/JvmtiRunTestBasedTest.java \
+
+LOCAL_SDK_VERSION := current
+LOCAL_DEX_PREOPT := false
+LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceAppBase
+LOCAL_STATIC_JAVA_LIBRARIES += run-test-jvmti-java
+LOCAL_PROGUARD_ENABLED := disabled
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml b/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml
new file mode 100644
index 0000000..a2d6ca6
--- /dev/null
+++ b/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<!--
+ * This is a sample of how to create an app for a run-test-based JVMTI
+ * test.
+ -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_{NR}">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="{NR}" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_{NR}" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/base/run-test-based-app/src/android/jvmti/cts/JvmtiRunTestBasedTest.java b/hostsidetests/jvmti/base/run-test-based-app/src/android/jvmti/cts/JvmtiRunTestBasedTest.java
new file mode 100644
index 0000000..312a882
--- /dev/null
+++ b/hostsidetests/jvmti/base/run-test-based-app/src/android/jvmti/cts/JvmtiRunTestBasedTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package android.jvmti.cts;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.lang.reflect.Method;
+
+import android.content.pm.PackageManager;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Check redefineClasses-related functionality.
+ */
+public class JvmtiRunTestBasedTest extends JvmtiTestBase {
+
+    private PrintStream oldOut, oldErr;
+    private ByteArrayOutputStream bufferedOut, bufferedErr;
+
+    @Before
+    public void setUp() throws Exception {
+        oldOut = System.out;
+        oldErr = System.err;
+
+        System.setOut(new PrintStream(bufferedOut = new ByteArrayOutputStream(), true));
+        System.setErr(new PrintStream(bufferedErr = new ByteArrayOutputStream(), true));
+    }
+
+    @After
+    public void tearDown() {
+        System.setOut(oldOut);
+        System.setErr(oldErr);
+    }
+
+    protected int getTestNumber() throws Exception {
+        return mActivity.getPackageManager().getApplicationInfo(mActivity.getPackageName(),
+                PackageManager.GET_META_DATA).metaData.getInt("android.jvmti.cts.run_test_nr");
+    }
+
+    @Test
+    public void testRunTest() throws Exception {
+        final int nr = getTestNumber();
+
+        // Load the test class.
+        Class<?> testClass = Class.forName("art.Test" + nr);
+        Method runMethod = testClass.getDeclaredMethod("run");
+        runMethod.invoke(null);
+
+        // Load the expected txt file.
+        InputStream expectedStream = getClass().getClassLoader()
+                .getResourceAsStream("results." + nr + ".expected.txt");
+        compare(expectedStream, bufferedOut);
+
+        if (bufferedErr.size() > 0) {
+            throw new IllegalStateException(
+                    "Did not expect System.err output: " + bufferedErr.toString());
+        }
+    }
+
+    // Very primitive diff. Doesn't do any smart things...
+    private void compare(InputStream expectedStream, ByteArrayOutputStream resultStream)
+            throws Exception {
+        // This isn't really optimal in any way.
+        BufferedReader expectedReader = new BufferedReader(new InputStreamReader(expectedStream));
+        BufferedReader resultReader = new BufferedReader(
+                new InputStreamReader(new ByteArrayInputStream(resultStream.toByteArray())));
+        StringBuilder resultBuilder = new StringBuilder();
+        boolean failed = false;
+        for (;;) {
+            String expString = expectedReader.readLine();
+            String resString = resultReader.readLine();
+
+            if (expString == null && resString == null) {
+                // Done.
+                break;
+            }
+
+            if (expString != null && resString != null && expString.equals(resString)) {
+                resultBuilder.append("  ");
+                resultBuilder.append(expString);
+                resultBuilder.append('\n');
+                continue;
+            }
+
+            failed = true;
+            if (expString != null) {
+                resultBuilder.append("- ");
+                resultBuilder.append(expString);
+                resultBuilder.append('\n');
+            }
+            if (resString != null) {
+                resultBuilder.append("+ ");
+                resultBuilder.append(resString);
+                resultBuilder.append('\n');
+            }
+        }
+        if (failed) {
+            throw new IllegalStateException(resultBuilder.toString());
+        }
+    }
+}
diff --git a/hostsidetests/jvmti/base/run-test-based-app/src/art/Main.java b/hostsidetests/jvmti/base/run-test-based-app/src/art/Main.java
new file mode 100644
index 0000000..493c709
--- /dev/null
+++ b/hostsidetests/jvmti/base/run-test-based-app/src/art/Main.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package art;
+
+/**
+ * This is class is only provided to make development in an IDE easier. The art.Main version
+ * out of the ART run-tests will be used when building.
+ */
+public class Main {
+    // General functionality shared between tests.
+    public static native void setTag(Object o, long tag);
+
+    public static native long getTag(Object o);
+}
diff --git a/hostsidetests/jvmti/redefining/AndroidTest.xml b/hostsidetests/jvmti/redefining/AndroidTest.xml
index f2c20ed..3bc93a2 100644
--- a/hostsidetests/jvmti/redefining/AndroidTest.xml
+++ b/hostsidetests/jvmti/redefining/AndroidTest.xml
@@ -21,5 +21,7 @@
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsJvmtiRedefineClassesHostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRedefineClassesDeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.redefine" />
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
index 169afe2..d68d1dd 100644
--- a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
+++ b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
@@ -34,6 +34,8 @@
 import org.junit.BeforeClass;
 import org.junit.Test;
 
+import art.Main;
+
 /**
  * Check redefineClasses-related functionality.
  */
@@ -41,8 +43,6 @@
 
     @Before
     public void setUp() throws Exception {
-        JniBindings.bindAgentJNI("android/jvmti/cts/JvmtiRedefineClassesTest",
-                getClass().getClassLoader());
         // make sure everything is cleared.
         setTransformationEvent(false);
         setPopTransformations(true);
diff --git a/hostsidetests/jvmti/redefining/app/src/art/Main.java b/hostsidetests/jvmti/redefining/app/src/art/Main.java
new file mode 100644
index 0000000..6f569d1
--- /dev/null
+++ b/hostsidetests/jvmti/redefining/app/src/art/Main.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package art;
+
+/**
+ * This is a definition of generically exposed implementations by the CTS JVMTI agent.
+ */
+public class Main {
+    // Load the given class with the given classloader, and bind all native methods to corresponding
+    // C methods in the agent. Will abort if any of the steps fail.
+    public static native void bindAgentJNI(String className, ClassLoader classLoader);
+    // Same as above, giving the class directly.
+    public static native void bindAgentJNIForClass(Class<?> klass);
+
+    // General functionality shared between tests.
+    public static native void setTag(Object o, long tag);
+
+    public static native long getTag(Object o);
+}
diff --git a/hostsidetests/jvmti/run-tests/Android.mk b/hostsidetests/jvmti/run-tests/Android.mk
new file mode 100644
index 0000000..64fe597
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/Android.mk
@@ -0,0 +1,17 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-902/Android.mk b/hostsidetests/jvmti/run-tests/test-902/Android.mk
new file mode 100644
index 0000000..7479ad8
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-902/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest902HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml
new file mode 100644
index 0000000..ade4fac
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest902DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_902" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest902HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest902DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_902" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-902/app/Android.mk b/hostsidetests/jvmti/run-tests/test-902/app/Android.mk
new file mode 100644
index 0000000..3fd9dc9
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-902/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest902DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-902/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-902/app/AndroidManifest.xml
new file mode 100644
index 0000000..6a2edd6
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-902/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_902">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="902" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_902" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-903/Android.mk b/hostsidetests/jvmti/run-tests/test-903/Android.mk
new file mode 100644
index 0000000..1b67da1
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-903/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest903HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml
new file mode 100644
index 0000000..1390840
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest903DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_903" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest903HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest903DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_903" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-903/app/Android.mk b/hostsidetests/jvmti/run-tests/test-903/app/Android.mk
new file mode 100644
index 0000000..a501186
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-903/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest903DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-903/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-903/app/AndroidManifest.xml
new file mode 100644
index 0000000..4823c99
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-903/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_903">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="903" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_903" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-904/Android.mk b/hostsidetests/jvmti/run-tests/test-904/Android.mk
new file mode 100644
index 0000000..b814acb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-904/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest904HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml
new file mode 100644
index 0000000..f16ce94
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest904DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_904" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest904HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest904DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_904" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-904/app/Android.mk b/hostsidetests/jvmti/run-tests/test-904/app/Android.mk
new file mode 100644
index 0000000..83f0efc
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-904/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest904DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-904/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-904/app/AndroidManifest.xml
new file mode 100644
index 0000000..59ef42c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-904/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_904">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="904" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_904" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-905/Android.mk b/hostsidetests/jvmti/run-tests/test-905/Android.mk
new file mode 100644
index 0000000..9e58b9b
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-905/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest905HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml
new file mode 100644
index 0000000..c337e82
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest905DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_905" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest905HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest905DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_905" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-905/app/Android.mk b/hostsidetests/jvmti/run-tests/test-905/app/Android.mk
new file mode 100644
index 0000000..662ea5f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-905/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest905DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-905/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-905/app/AndroidManifest.xml
new file mode 100644
index 0000000..9092bf7
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-905/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_905">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="905" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_905" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-906/Android.mk b/hostsidetests/jvmti/run-tests/test-906/Android.mk
new file mode 100644
index 0000000..553b898
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-906/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest906HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml
new file mode 100644
index 0000000..dbd74f6
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest906DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_906" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest906HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest906DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_906" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-906/app/Android.mk b/hostsidetests/jvmti/run-tests/test-906/app/Android.mk
new file mode 100644
index 0000000..f383007
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-906/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest906DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-906/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-906/app/AndroidManifest.xml
new file mode 100644
index 0000000..c06dc7e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-906/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_906">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="906" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_906" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-907/Android.mk b/hostsidetests/jvmti/run-tests/test-907/Android.mk
new file mode 100644
index 0000000..cf79d0b
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-907/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest907HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml
new file mode 100644
index 0000000..99cd40d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest907DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_907" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest907HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest907DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_907" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-907/app/Android.mk b/hostsidetests/jvmti/run-tests/test-907/app/Android.mk
new file mode 100644
index 0000000..3ecb219
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-907/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest907DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-907/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-907/app/AndroidManifest.xml
new file mode 100644
index 0000000..0e96029
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-907/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_907">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="907" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_907" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-908/Android.mk b/hostsidetests/jvmti/run-tests/test-908/Android.mk
new file mode 100644
index 0000000..40ef837
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-908/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest908HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml
new file mode 100644
index 0000000..fca6567
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest908DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_908" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest908HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest908DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_908" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-908/app/Android.mk b/hostsidetests/jvmti/run-tests/test-908/app/Android.mk
new file mode 100644
index 0000000..c4eea2e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-908/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest908DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-908/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-908/app/AndroidManifest.xml
new file mode 100644
index 0000000..2dddb65
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-908/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_908">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="908" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_908" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-910/Android.mk b/hostsidetests/jvmti/run-tests/test-910/Android.mk
new file mode 100644
index 0000000..8cfe0a5
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-910/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest910HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml
new file mode 100644
index 0000000..a947621
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest910DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_910" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest910HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest910DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_910" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-910/app/Android.mk b/hostsidetests/jvmti/run-tests/test-910/app/Android.mk
new file mode 100644
index 0000000..108682a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-910/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest910DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-910/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-910/app/AndroidManifest.xml
new file mode 100644
index 0000000..6fbbb29
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-910/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_910">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="910" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_910" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-911/Android.mk b/hostsidetests/jvmti/run-tests/test-911/Android.mk
new file mode 100644
index 0000000..0906b99
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-911/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest911HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml
new file mode 100644
index 0000000..fb06812
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest911DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_911" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest911HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest911DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_911" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-911/app/Android.mk b/hostsidetests/jvmti/run-tests/test-911/app/Android.mk
new file mode 100644
index 0000000..d5d70d2
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-911/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest911DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-911/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-911/app/AndroidManifest.xml
new file mode 100644
index 0000000..1284b25
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-911/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_911">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="911" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_911" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-913/Android.mk b/hostsidetests/jvmti/run-tests/test-913/Android.mk
new file mode 100644
index 0000000..8075fe2
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-913/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest913HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml
new file mode 100644
index 0000000..a019d07
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest913DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_913" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest913HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest913DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_913" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-913/app/Android.mk b/hostsidetests/jvmti/run-tests/test-913/app/Android.mk
new file mode 100644
index 0000000..03cb328
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-913/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest913DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-913/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-913/app/AndroidManifest.xml
new file mode 100644
index 0000000..bd183b8
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-913/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_913">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="913" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_913" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-914/Android.mk b/hostsidetests/jvmti/run-tests/test-914/Android.mk
new file mode 100644
index 0000000..5f7ddee
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-914/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest914HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml
new file mode 100644
index 0000000..b70869e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest914DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_914" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest914HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest914DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_914" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-914/app/Android.mk b/hostsidetests/jvmti/run-tests/test-914/app/Android.mk
new file mode 100644
index 0000000..c294d56
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-914/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest914DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-914/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-914/app/AndroidManifest.xml
new file mode 100644
index 0000000..5d6869c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-914/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_914">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="914" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_914" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-915/Android.mk b/hostsidetests/jvmti/run-tests/test-915/Android.mk
new file mode 100644
index 0000000..2e2e438
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-915/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest915HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml
new file mode 100644
index 0000000..35f9903
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest915DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_915" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest915HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest915DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_915" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-915/app/Android.mk b/hostsidetests/jvmti/run-tests/test-915/app/Android.mk
new file mode 100644
index 0000000..d712a74
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-915/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest915DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-915/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-915/app/AndroidManifest.xml
new file mode 100644
index 0000000..12c417e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-915/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_915">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="915" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_915" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-917/Android.mk b/hostsidetests/jvmti/run-tests/test-917/Android.mk
new file mode 100644
index 0000000..1e84675
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-917/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest917HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml
new file mode 100644
index 0000000..ad988af
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest917DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_917" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest917HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest917DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_917" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-917/app/Android.mk b/hostsidetests/jvmti/run-tests/test-917/app/Android.mk
new file mode 100644
index 0000000..8b87082
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-917/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest917DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-917/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-917/app/AndroidManifest.xml
new file mode 100644
index 0000000..114aa4c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-917/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_917">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="917" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_917" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-918/Android.mk b/hostsidetests/jvmti/run-tests/test-918/Android.mk
new file mode 100644
index 0000000..5d6f8d0
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-918/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest918HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml
new file mode 100644
index 0000000..4a3feb1
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest918DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_918" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest918HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest918DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_918" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-918/app/Android.mk b/hostsidetests/jvmti/run-tests/test-918/app/Android.mk
new file mode 100644
index 0000000..30f9597
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-918/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest918DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-918/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-918/app/AndroidManifest.xml
new file mode 100644
index 0000000..96ce8aa
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-918/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_918">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="918" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_918" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-919/Android.mk b/hostsidetests/jvmti/run-tests/test-919/Android.mk
new file mode 100644
index 0000000..8916d6e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-919/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest919HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml
new file mode 100644
index 0000000..3183ad3
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest919DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_919" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest919HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest919DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_919" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-919/app/Android.mk b/hostsidetests/jvmti/run-tests/test-919/app/Android.mk
new file mode 100644
index 0000000..a9b7089
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-919/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest919DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-919/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-919/app/AndroidManifest.xml
new file mode 100644
index 0000000..7ce0424
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-919/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_919">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="919" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_919" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-920/Android.mk b/hostsidetests/jvmti/run-tests/test-920/Android.mk
new file mode 100644
index 0000000..f92ed94
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-920/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest920HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml
new file mode 100644
index 0000000..ba53a64
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest920DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_920" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest920HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest920DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_920" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-920/app/Android.mk b/hostsidetests/jvmti/run-tests/test-920/app/Android.mk
new file mode 100644
index 0000000..a24d668
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-920/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest920DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-920/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-920/app/AndroidManifest.xml
new file mode 100644
index 0000000..1c85104
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-920/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_920">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="920" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_920" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-922/Android.mk b/hostsidetests/jvmti/run-tests/test-922/Android.mk
new file mode 100644
index 0000000..2de665a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-922/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest922HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml
new file mode 100644
index 0000000..2b74f07
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest922DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_922" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest922HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest922DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_922" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-922/app/Android.mk b/hostsidetests/jvmti/run-tests/test-922/app/Android.mk
new file mode 100644
index 0000000..ada0edc
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-922/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest922DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-922/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-922/app/AndroidManifest.xml
new file mode 100644
index 0000000..985352d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-922/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_922">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="922" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_922" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-923/Android.mk b/hostsidetests/jvmti/run-tests/test-923/Android.mk
new file mode 100644
index 0000000..dd1de3c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-923/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest923HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml
new file mode 100644
index 0000000..9c8aa21
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest923DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_923" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest923HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest923DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_923" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-923/app/Android.mk b/hostsidetests/jvmti/run-tests/test-923/app/Android.mk
new file mode 100644
index 0000000..c94d431
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-923/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest923DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-923/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-923/app/AndroidManifest.xml
new file mode 100644
index 0000000..3c8bced
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-923/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_923">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="923" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_923" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-924/Android.mk b/hostsidetests/jvmti/run-tests/test-924/Android.mk
new file mode 100644
index 0000000..28c4b89
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-924/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest924HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml
new file mode 100644
index 0000000..5a2b567
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest924DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_924" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest924HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest924DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_924" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-924/app/Android.mk b/hostsidetests/jvmti/run-tests/test-924/app/Android.mk
new file mode 100644
index 0000000..f1acfd0
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-924/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest924DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-924/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-924/app/AndroidManifest.xml
new file mode 100644
index 0000000..bcc74c3
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-924/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_924">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="924" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_924" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-926/Android.mk b/hostsidetests/jvmti/run-tests/test-926/Android.mk
new file mode 100644
index 0000000..fcd46ad
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-926/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest926HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml
new file mode 100644
index 0000000..eea4602
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest926DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_926" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest926HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest926DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_926" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-926/app/Android.mk b/hostsidetests/jvmti/run-tests/test-926/app/Android.mk
new file mode 100644
index 0000000..a597fb1
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-926/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest926DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-926/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-926/app/AndroidManifest.xml
new file mode 100644
index 0000000..b2a855a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-926/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_926">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="926" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_926" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-927/Android.mk b/hostsidetests/jvmti/run-tests/test-927/Android.mk
new file mode 100644
index 0000000..939601c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-927/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest927HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml
new file mode 100644
index 0000000..71d452d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest927DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_927" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest927HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest927DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_927" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-927/app/Android.mk b/hostsidetests/jvmti/run-tests/test-927/app/Android.mk
new file mode 100644
index 0000000..9c71950
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-927/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest927DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-927/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-927/app/AndroidManifest.xml
new file mode 100644
index 0000000..966014a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-927/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_927">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="927" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_927" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-928/Android.mk b/hostsidetests/jvmti/run-tests/test-928/Android.mk
new file mode 100644
index 0000000..2eac8f9
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-928/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest928HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml
new file mode 100644
index 0000000..b7c59de
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest928DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_928" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest928HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest928DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_928" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-928/app/Android.mk b/hostsidetests/jvmti/run-tests/test-928/app/Android.mk
new file mode 100644
index 0000000..2eb3612
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-928/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest928DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-928/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-928/app/AndroidManifest.xml
new file mode 100644
index 0000000..1a4d25b
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-928/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_928">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="928" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_928" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-930/Android.mk b/hostsidetests/jvmti/run-tests/test-930/Android.mk
new file mode 100644
index 0000000..2ac9ae2
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-930/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest930HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml
new file mode 100644
index 0000000..3b241b2
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest930DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_930" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest930HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest930DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_930" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-930/app/Android.mk b/hostsidetests/jvmti/run-tests/test-930/app/Android.mk
new file mode 100644
index 0000000..873b273
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-930/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest930DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-930/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-930/app/AndroidManifest.xml
new file mode 100644
index 0000000..505448f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-930/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_930">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="930" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_930" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-931/Android.mk b/hostsidetests/jvmti/run-tests/test-931/Android.mk
new file mode 100644
index 0000000..ae04387
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-931/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest931HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml
new file mode 100644
index 0000000..4944067
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest931DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_931" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest931HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest931DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_931" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-931/app/Android.mk b/hostsidetests/jvmti/run-tests/test-931/app/Android.mk
new file mode 100644
index 0000000..c03028a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-931/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest931DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-931/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-931/app/AndroidManifest.xml
new file mode 100644
index 0000000..710e208
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-931/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_931">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="931" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_931" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-932/Android.mk b/hostsidetests/jvmti/run-tests/test-932/Android.mk
new file mode 100644
index 0000000..c952c86
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-932/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest932HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml
new file mode 100644
index 0000000..b6b1574
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest932DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_932" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest932HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest932DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_932" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-932/app/Android.mk b/hostsidetests/jvmti/run-tests/test-932/app/Android.mk
new file mode 100644
index 0000000..651a9ee
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-932/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest932DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-932/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-932/app/AndroidManifest.xml
new file mode 100644
index 0000000..6c4affd
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-932/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_932">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="932" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_932" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-940/Android.mk b/hostsidetests/jvmti/run-tests/test-940/Android.mk
new file mode 100644
index 0000000..4ed5dec
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-940/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest940HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml
new file mode 100644
index 0000000..56ebc24
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest940DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_940" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest940HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest940DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_940" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-940/app/Android.mk b/hostsidetests/jvmti/run-tests/test-940/app/Android.mk
new file mode 100644
index 0000000..c2121eb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-940/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest940DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-940/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-940/app/AndroidManifest.xml
new file mode 100644
index 0000000..227e058
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-940/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_940">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="940" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_940" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-942/Android.mk b/hostsidetests/jvmti/run-tests/test-942/Android.mk
new file mode 100644
index 0000000..d2605b7
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-942/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest942HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml
new file mode 100644
index 0000000..ffe2bf4
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest942DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_942" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest942HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest942DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_942" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-942/app/Android.mk b/hostsidetests/jvmti/run-tests/test-942/app/Android.mk
new file mode 100644
index 0000000..82d3b6a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-942/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest942DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-942/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-942/app/AndroidManifest.xml
new file mode 100644
index 0000000..c40171f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-942/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_942">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="942" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_942" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-944/Android.mk b/hostsidetests/jvmti/run-tests/test-944/Android.mk
new file mode 100644
index 0000000..16f9c7f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-944/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest944HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
new file mode 100644
index 0000000..c772bfb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest944DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_944" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest944HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest944DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_944" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-944/app/Android.mk b/hostsidetests/jvmti/run-tests/test-944/app/Android.mk
new file mode 100644
index 0000000..c820284
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-944/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest944DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-944/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-944/app/AndroidManifest.xml
new file mode 100644
index 0000000..2492237
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-944/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_944">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="944" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_944" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-945/Android.mk b/hostsidetests/jvmti/run-tests/test-945/Android.mk
new file mode 100644
index 0000000..e86d85e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-945/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest945HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml
new file mode 100644
index 0000000..431c5e6
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest945DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_945" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest945HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest945DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_945" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-945/app/Android.mk b/hostsidetests/jvmti/run-tests/test-945/app/Android.mk
new file mode 100644
index 0000000..b704807
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-945/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest945DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-945/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-945/app/AndroidManifest.xml
new file mode 100644
index 0000000..bfe5f24
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-945/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_945">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="945" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_945" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-947/Android.mk b/hostsidetests/jvmti/run-tests/test-947/Android.mk
new file mode 100644
index 0000000..4b4cead
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-947/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest947HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml
new file mode 100644
index 0000000..4ab0c9a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest947DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_947" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest947HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest947DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_947" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-947/app/Android.mk b/hostsidetests/jvmti/run-tests/test-947/app/Android.mk
new file mode 100644
index 0000000..42cc459
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-947/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest947DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-947/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-947/app/AndroidManifest.xml
new file mode 100644
index 0000000..36a85ef
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-947/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_947">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="947" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_947" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-951/Android.mk b/hostsidetests/jvmti/run-tests/test-951/Android.mk
new file mode 100644
index 0000000..ba45b86
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-951/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest951HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml
new file mode 100644
index 0000000..b489635
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest951DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_951" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest951HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest951DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_951" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-951/app/Android.mk b/hostsidetests/jvmti/run-tests/test-951/app/Android.mk
new file mode 100644
index 0000000..6b22274
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-951/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest951DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-951/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-951/app/AndroidManifest.xml
new file mode 100644
index 0000000..be50d55
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-951/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_951">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="951" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_951" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-981/Android.mk b/hostsidetests/jvmti/run-tests/test-981/Android.mk
new file mode 100644
index 0000000..4bbc20a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-981/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest981HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
new file mode 100644
index 0000000..3e2bb67
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest981DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_981" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest981HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest981DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_981" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/Android.mk b/hostsidetests/jvmti/run-tests/test-981/app/Android.mk
new file mode 100644
index 0000000..ec8f7aa
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-981/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest981DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
new file mode 100644
index 0000000..a0e898a
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_981">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="981" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_981" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-982/Android.mk b/hostsidetests/jvmti/run-tests/test-982/Android.mk
new file mode 100644
index 0000000..908adaf
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-982/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest982HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml
new file mode 100644
index 0000000..7c4833f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest982DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_982" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest982HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest982DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_982" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-982/app/Android.mk b/hostsidetests/jvmti/run-tests/test-982/app/Android.mk
new file mode 100644
index 0000000..a06c76d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-982/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest982DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-982/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-982/app/AndroidManifest.xml
new file mode 100644
index 0000000..d1cc7b1
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-982/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_982">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="982" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_982" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-984/Android.mk b/hostsidetests/jvmti/run-tests/test-984/Android.mk
new file mode 100644
index 0000000..3ddb2ad
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-984/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest984HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml
new file mode 100644
index 0000000..7ba284c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest984DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_984" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest984HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest984DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_984" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-984/app/Android.mk b/hostsidetests/jvmti/run-tests/test-984/app/Android.mk
new file mode 100644
index 0000000..b30ff35
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-984/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest984DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-984/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-984/app/AndroidManifest.xml
new file mode 100644
index 0000000..963cd51
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-984/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_984">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="984" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_984" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-985/Android.mk b/hostsidetests/jvmti/run-tests/test-985/Android.mk
new file mode 100644
index 0000000..0ed12de
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-985/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest985HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml
new file mode 100644
index 0000000..ba21091
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest985DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_985" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest985HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest985DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_985" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-985/app/Android.mk b/hostsidetests/jvmti/run-tests/test-985/app/Android.mk
new file mode 100644
index 0000000..e092712
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-985/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest985DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-985/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-985/app/AndroidManifest.xml
new file mode 100644
index 0000000..4b0ffa5
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-985/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_985">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="985" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_985" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-986/Android.mk b/hostsidetests/jvmti/run-tests/test-986/Android.mk
new file mode 100644
index 0000000..8e6ec6f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-986/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest986HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml
new file mode 100644
index 0000000..4bc581f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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 JVMTI test cases">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest986DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_986" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest986HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest986DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_986" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-986/app/Android.mk b/hostsidetests/jvmti/run-tests/test-986/app/Android.mk
new file mode 100644
index 0000000..6914162
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-986/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest986DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-986/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-986/app/AndroidManifest.xml
new file mode 100644
index 0000000..4c12d93
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-986/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_986">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="986" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_986" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/tagging/AndroidTest.xml b/hostsidetests/jvmti/tagging/AndroidTest.xml
index 6d76722..2cee989 100644
--- a/hostsidetests/jvmti/tagging/AndroidTest.xml
+++ b/hostsidetests/jvmti/tagging/AndroidTest.xml
@@ -21,5 +21,7 @@
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsJvmtiTaggingHostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiTaggingDeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.tagging" />
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/tagging/app/src/android/jvmti/cts/JvmtiTaggingTest.java b/hostsidetests/jvmti/tagging/app/src/android/jvmti/cts/JvmtiTaggingTest.java
index 6ba9376..d695f9f 100644
--- a/hostsidetests/jvmti/tagging/app/src/android/jvmti/cts/JvmtiTaggingTest.java
+++ b/hostsidetests/jvmti/tagging/app/src/android/jvmti/cts/JvmtiTaggingTest.java
@@ -24,41 +24,37 @@
 import org.junit.Before;
 import org.junit.Test;
 
+import art.Main;
+
 /**
  * Check tagging-related functionality.
  */
 public class JvmtiTaggingTest extends JvmtiTestBase {
 
-    @Before
-    public void setUp() throws Exception {
-        // Bind our native methods.
-        JniBindings.bindAgentJNI("android/jvmti/cts/JvmtiTaggingTest", getClass().getClassLoader());
-    }
-
     private static WeakReference<Object> test() {
         Object o1 = new Object();
-        JniBindings.setTag(o1, 1);
+        Main.setTag(o1, 1);
 
         Object o2 = new Object();
-        JniBindings.setTag(o2, 2);
+        Main.setTag(o2, 2);
 
-        assertEquals(1, JniBindings.getTag(o1));
-        assertEquals(2, JniBindings.getTag(o2));
+        assertEquals(1, Main.getTag(o1));
+        assertEquals(2, Main.getTag(o2));
 
         Runtime.getRuntime().gc();
         Runtime.getRuntime().gc();
 
-        assertEquals(1, JniBindings.getTag(o1));
-        assertEquals(2, JniBindings.getTag(o2));
+        assertEquals(1, Main.getTag(o1));
+        assertEquals(2, Main.getTag(o2));
 
         Runtime.getRuntime().gc();
         Runtime.getRuntime().gc();
 
-        JniBindings.setTag(o1, 10);
-        JniBindings.setTag(o2, 20);
+        Main.setTag(o1, 10);
+        Main.setTag(o2, 20);
 
-        assertEquals(10, JniBindings.getTag(o1));
-        assertEquals(20, JniBindings.getTag(o2));
+        assertEquals(10, Main.getTag(o1));
+        assertEquals(20, Main.getTag(o2));
 
         return new WeakReference<Object>(o1);
     }
@@ -93,7 +89,7 @@
             Integer o = new Integer(i);
             l.add(o);
             if (i % 10 != 0) {
-                JniBindings.setTag(o, i % 10);
+                Main.setTag(o, i % 10);
             }
         }
 
diff --git a/hostsidetests/jvmti/tagging/app/src/art/Main.java b/hostsidetests/jvmti/tagging/app/src/art/Main.java
new file mode 100644
index 0000000..6f569d1
--- /dev/null
+++ b/hostsidetests/jvmti/tagging/app/src/art/Main.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package art;
+
+/**
+ * This is a definition of generically exposed implementations by the CTS JVMTI agent.
+ */
+public class Main {
+    // Load the given class with the given classloader, and bind all native methods to corresponding
+    // C methods in the agent. Will abort if any of the steps fail.
+    public static native void bindAgentJNI(String className, ClassLoader classLoader);
+    // Same as above, giving the class directly.
+    public static native void bindAgentJNIForClass(Class<?> klass);
+
+    // General functionality shared between tests.
+    public static native void setTag(Object o, long tag);
+
+    public static native long getTag(Object o);
+}
diff --git a/hostsidetests/media/Android.mk b/hostsidetests/media/Android.mk
new file mode 100644
index 0000000..36e9066
--- /dev/null
+++ b/hostsidetests/media/Android.mk
@@ -0,0 +1,36 @@
+#
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+    $(call all-java-files-under, common) \
+    $(call all-java-files-under, src)
+
+LOCAL_MODULE_TAGS := tests
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_MODULE := CtsMediaHostTestCases
+
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
+
+include $(call first-makefiles-under,$(LOCAL_PATH))
+
diff --git a/hostsidetests/media/AndroidTest.xml b/hostsidetests/media/AndroidTest.xml
new file mode 100644
index 0000000..0a6410c
--- /dev/null
+++ b/hostsidetests/media/AndroidTest.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for CTS media host test cases">
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsMediaHostTestCases.jar" />
+        <option name="runtime-hint" value="30m" />
+    </test>
+</configuration>
+
diff --git a/hostsidetests/media/app/MediaSessionTest/Android.mk b/hostsidetests/media/app/MediaSessionTest/Android.mk
new file mode 100644
index 0000000..eb9059d
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTest/Android.mk
@@ -0,0 +1,36 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_PACKAGE_NAME := CtsMediaSessionHostTestApp
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := \
+    $(call all-java-files-under, src) \
+    $(call all-java-files-under, ../../common)
+
+
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test compatibility-device-util
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml b/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml
new file mode 100644
index 0000000..60e82dd
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.media.session.cts">
+
+    <uses-sdk android:minSdkVersion="26"/>
+
+    <application />
+
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.media.session.cts"
+        android:label="MediaSession multi-user case CTS Tests" />
+
+</manifest>
diff --git a/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java b/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
new file mode 100644
index 0000000..2186038
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.session.cts;
+
+import static android.media.cts.MediaSessionTestHelperConstants.MEDIA_SESSION_TEST_HELPER_PKG;
+
+import android.content.Context;
+import android.content.ComponentName;
+import android.test.AndroidTestCase;
+import android.media.session.MediaSessionManager;
+import android.media.session.MediaController;
+
+import java.util.List;
+
+/**
+ * Tests {@link MediaSessionManager} with the multi-user environment.
+ * <p>Don't run tests here directly. They aren't stand-alone tests and each test will be run
+ * indirectly by the host-side test CtsMediaHostTestCases after the proper device setup.
+ */
+public class MediaSessionManagerTest extends AndroidTestCase {
+    private MediaSessionManager mMediaSessionManager;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mMediaSessionManager = (MediaSessionManager) getContext().getSystemService(
+                Context.MEDIA_SESSION_SERVICE);
+    }
+
+    /**
+     * Tests if the MediaSessionTestHelper doesn't have an active media session.
+     */
+    public void testGetActiveSessions_noMediaSessionFromMediaSessionTestHelper() throws Exception {
+        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(
+                createFakeNotificationListener());
+        for (MediaController controller : controllers) {
+            if (controller.getPackageName().equals(MEDIA_SESSION_TEST_HELPER_PKG)) {
+                fail("Media session for the media session app shouldn't be available");
+                return;
+            }
+        }
+    }
+
+    /**
+     * Tests if the MediaSessionTestHelper has an active media session.
+     */
+    public void testGetActiveSessions_hasMediaSessionFromMediaSessionTestHelper() throws Exception {
+        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(
+                createFakeNotificationListener());
+        for (MediaController controller : controllers) {
+            if (controller.getPackageName().equals(MEDIA_SESSION_TEST_HELPER_PKG)) {
+                // Test success
+                return;
+            }
+        }
+        fail("Media session for the media session app is expected");
+    }
+
+    /**
+     * Tests if there's no media session.
+     */
+    public void testGetActiveSessions_noMediaSession() throws Exception {
+        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(
+                createFakeNotificationListener());
+        assertTrue(controllers.isEmpty());
+    }
+
+    /**
+     * Returns the ComponentName of the notification listener for this test.
+     * <p>Notification listener will be enabled by the host-side test.
+     */
+    private ComponentName createFakeNotificationListener() {
+        return new ComponentName(getContext(), MediaSessionManagerTest.class);
+    }
+}
+
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/Android.mk b/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
new file mode 100644
index 0000000..3944cb6
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
@@ -0,0 +1,40 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Don't include this package in any target
+LOCAL_MODULE_TAGS := tests
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_DEX_PREOPT := false
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+LOCAL_SRC_FILES := \
+    $(call all-java-files-under, src) \
+    $(call all-java-files-under, ../../common)
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_PACKAGE_NAME := CtsMediaSessionTestHelper
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_PACKAGE)
+
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/AndroidManifest.xml b/hostsidetests/media/app/MediaSessionTestHelper/AndroidManifest.xml
new file mode 100644
index 0000000..1e29eca
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTestHelper/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.media.app.media_session_test_helper"
+    android:versionCode="1"
+    android:versionName="1.0">
+
+    <application android:label="@string/label">
+        <service android:name=".MediaSessionTestHelperService">
+            <intent-filter>
+                <action android:name="android.media.app.media_session_test_helper.ACTION_CONTROL" />
+            </intent-filter>
+        </service>
+    </application>
+</manifest>
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/res/values/strings.xml b/hostsidetests/media/app/MediaSessionTestHelper/res/values/strings.xml
new file mode 100644
index 0000000..fb75fdb
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTestHelper/res/values/strings.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<resources>
+    <string name="label">MediaSessionTestHelper for media host-side CTS tests</string>
+</resources>
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java b/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java
new file mode 100644
index 0000000..a161ba5
--- /dev/null
+++ b/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.app.media_session_test_helper;
+
+import android.app.Notification;
+import android.app.Service;
+import android.content.Intent;
+import android.media.session.MediaSession;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import android.media.cts.MediaSessionTestHelperConstants;
+
+/**
+ * Service of the media session's host-side CTS helper.
+ * <p>This is the foreground service to prevent this process from being killed by the OOM killer
+ * while the host-side tests are running.
+ */
+public class MediaSessionTestHelperService extends Service {
+    private static final String TAG = "MediaSessionTestHelperService";
+
+    private static final int NOTIFICATION_ID = 100;
+
+    private MediaSession mMediaSession;
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+
+        // Build notification UI to make this a foreground service.
+        Notification notification = new Notification.Builder(this)
+                .setSmallIcon(android.R.drawable.sym_def_app_icon)
+                .setContentTitle(getString(R.string.label)).build();
+        startForeground(NOTIFICATION_ID, notification);
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        super.onStartCommand(intent, flags, startId);
+        if (!TextUtils.equals(intent.getAction(), MediaSessionTestHelperConstants.ACTION_CONTROL)) {
+            Log.e(TAG, "Invalid action " + intent.getAction() + ". Test may fail");
+            return START_STICKY;
+        }
+        int flag = intent.getIntExtra(MediaSessionTestHelperConstants.EXTRA_CONTROL_COMMAND, 0);
+        if ((flag & MediaSessionTestHelperConstants.FLAG_CREATE_MEDIA_SESSION) != 0) {
+            if (mMediaSession == null) {
+                mMediaSession = new MediaSession(this, TAG);
+            }
+        }
+        if (mMediaSession != null) {
+            if ((flag & MediaSessionTestHelperConstants.FLAG_SET_MEDIA_SESSION_ACTIVE) != 0) {
+                mMediaSession.setActive(true);
+            }
+            if ((flag & MediaSessionTestHelperConstants.FLAG_SET_MEDIA_SESSION_INACTIVE) != 0) {
+                mMediaSession.setActive(false);
+            }
+        }
+        if ((flag & MediaSessionTestHelperConstants.FLAG_RELEASE_MEDIA_SESSION) != 0) {
+            releaseMediaSession();
+        }
+        return START_STICKY;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        // It's not a bind service.
+        return null;
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        releaseMediaSession();
+    }
+
+    private void releaseMediaSession() {
+        if (mMediaSession != null) {
+            mMediaSession.release();
+            mMediaSession = null;
+        }
+    }
+}
diff --git a/hostsidetests/media/common/android/media/cts/MediaSessionTestHelperConstants.java b/hostsidetests/media/common/android/media/cts/MediaSessionTestHelperConstants.java
new file mode 100644
index 0000000..8c8dc54
--- /dev/null
+++ b/hostsidetests/media/common/android/media/cts/MediaSessionTestHelperConstants.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.cts;
+
+/**
+ * Defines constants for controlling the media session test helper app, which can start media
+ * playback and create the media session for test.
+ * <p>Any change in these constants should also be applied to the media session test helper app.
+ * <p>Don't add Android specific imports because this will be used by the both host-side and
+ * device-side.
+ */
+public class MediaSessionTestHelperConstants {
+    /**
+     * Package name of the media session test helper.
+     */
+    public static final String MEDIA_SESSION_TEST_HELPER_PKG =
+            "android.media.app.media_session_test_helper";
+    /**
+     * Package binary file name of the media session test helper`.
+     */
+    public static final String MEDIA_SESSION_TEST_HELPER_APK = "CtsMediaSessionTestHelper.apk";
+
+    /**
+     * Intent action name to control media sesion test helper.
+     */
+    public static final String ACTION_CONTROL =
+            "android.media.app.media_session_test_helper.ACTION_CONTROL";
+    /**
+     * Intent extra key name to control media session test helper.
+     */
+    public static final String EXTRA_CONTROL_COMMAND =
+            "android.media.app.media_session_test_helper.EXTRA_CONTROL_COMMAND";
+
+    /**
+     * Intent extra value for the key {@link #EXTRA_CONTROL_COMMAND} to create the media session
+     * if it doesn't exist.
+     * @see buildControlCommand
+     */
+    public static final int FLAG_CREATE_MEDIA_SESSION = 0x01;
+    /**
+     * Intent extra value for the key {@link #EXTRA_CONTROL_COMMAND} to set the media session active
+     * if it exists.
+     * @see buildControlCommand
+     */
+    public static final int FLAG_SET_MEDIA_SESSION_ACTIVE = 0x02;
+    /**
+     * Intent extra value for the key {@link #EXTRA_CONTROL_COMMAND} to set the media session
+     * inactive if it exists.
+     * @see buildControlCommand
+     */
+    public static final int FLAG_SET_MEDIA_SESSION_INACTIVE = 0x04;
+    /**
+     * Intent extra value for the key {@link #EXTRA_CONTROL_COMMAND} to release the media session
+     * if it was created.
+     * @see buildControlCommand
+     */
+    public static final int FLAG_RELEASE_MEDIA_SESSION = 0x08;
+
+    private MediaSessionTestHelperConstants() {
+        // Prevent from the instantiation.
+    }
+
+    /**
+     * Builds the control command for the media session test helper app.
+     *
+     * @param userId user id to send the command
+     * @param flag bit masked flag among {@link #FLAG_CREATE_MEDIA_SESSION},
+     *            {@link #FLAG_SET_MEDIA_SESSION_ACTIVE}, {@link #FLAG_SET_MEDIA_SESSION_INACTIVE},
+     *            and {@link #FLAG_RELEASE_MEDIA_SESSION}. If multiple flags are specificed,
+     *            operations will be exceuted in order.
+     **/
+    public static String buildControlCommand(int userId, int flag) {
+        return "am start-foreground-service --user " + userId + " -a " + ACTION_CONTROL + " --ei "
+                + EXTRA_CONTROL_COMMAND + " " + flag + " " + MEDIA_SESSION_TEST_HELPER_PKG;
+    }
+}
diff --git a/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java b/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
new file mode 100644
index 0000000..ef8ba5b
--- /dev/null
+++ b/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
@@ -0,0 +1,330 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.cts;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.ddmlib.testrunner.TestResult;
+import com.android.ddmlib.testrunner.TestResult.TestStatus;
+import com.android.ddmlib.testrunner.TestRunResult;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/**
+ * Base class for host-side tests for multi-user aware media APIs.
+ */
+public class BaseMultiUserTest extends DeviceTestCase implements IBuildReceiver {
+    private static final String RUNNER = "android.support.test.runner.AndroidJUnitRunner";
+
+    /**
+     * The defined timeout (in milliseconds) is used as a maximum waiting time when expecting the
+     * command output from the device. At any time, if the shell command does not output anything
+     * for a period longer than the defined timeout the Tradefed run terminates.
+     */
+    private static final long DEFAULT_SHELL_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
+
+    /**
+     * Instrumentation test runner argument key used for individual test timeout
+     **/
+    protected static final String TEST_TIMEOUT_INST_ARGS_KEY = "timeout_msec";
+
+    /**
+     * Sets timeout (in milliseconds) that will be applied to each test. In the
+     * event of a test timeout it will log the results and proceed with executing the next test.
+     */
+    private static final long DEFAULT_TEST_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
+    private static final String SETTINGS_PACKAGE_VERIFIER_NAMESPACE = "global";
+    private static final String SETTINGS_PACKAGE_VERIFIER_NAME = "package_verifier_enable";
+
+    /**
+     * User ID for all users.
+     * The value is from the UserHandle class.
+     */
+    protected static final int USER_ALL = -1;
+
+    /**
+     * User ID for the system user.
+     * The value is from the UserHandle class.
+     */
+    protected static final int USER_SYSTEM = 0;
+
+    private IBuildInfo mCtsBuild;
+    private String mPackageVerifier;
+
+    private Set<String> mExistingPackages;
+    private List<Integer> mExistingUsers;
+
+    @Override
+    protected void setUp() throws Exception {
+        // Ensure that build has been set before test is run.
+        assertNotNull(mCtsBuild);
+        mExistingPackages = getDevice().getInstalledPackageNames();
+
+        // Disable the package verifier to avoid the dialog when installing an app
+        mPackageVerifier = getSettings(SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
+                SETTINGS_PACKAGE_VERIFIER_NAME, USER_ALL);
+        putSettings(SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
+                SETTINGS_PACKAGE_VERIFIER_NAME, "0", USER_ALL);
+
+        mExistingUsers = new ArrayList();
+        int primaryUserId = getDevice().getPrimaryUserId();
+        mExistingUsers.add(primaryUserId);
+        mExistingUsers.add(USER_SYSTEM);
+
+        executeShellCommand("am switch-user " + primaryUserId);
+        executeShellCommand("wm dismiss-keyguard");
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        // Reset the package verifier setting to its original value.
+        putSettings(SETTINGS_PACKAGE_VERIFIER_NAMESPACE, SETTINGS_PACKAGE_VERIFIER_NAME,
+                mPackageVerifier, USER_ALL);
+
+        // Remove users created during the test.
+        for (int userId : getDevice().listUsers()) {
+            if (!mExistingUsers.contains(userId)) {
+                removeUser(userId);
+            }
+        }
+        // Remove packages installed during the test.
+        for (String packageName : getDevice().getUninstallablePackageNames()) {
+            if (mExistingPackages.contains(packageName)) {
+                continue;
+            }
+            CLog.d("Removing leftover package: " + packageName);
+            getDevice().uninstallPackage(packageName);
+        }
+        super.tearDown();
+    }
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mCtsBuild = buildInfo;
+    }
+
+    /**
+     * Installs the app as if the user of the ID {@param userId} has installed the app.
+     *
+     * @param appFileName file name of the app.
+     * @param userId user ID to install the app against.
+     */
+    protected void installAppAsUser(String appFileName, int userId)
+            throws FileNotFoundException, DeviceNotAvailableException {
+        CLog.d("Installing app " + appFileName + " for user " + userId);
+        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
+        String result = getDevice().installPackageForUser(
+                buildHelper.getTestFile(appFileName), true, true, userId, "-t");
+        assertNull("Failed to install " + appFileName + " for user " + userId + ": " + result,
+                result);
+    }
+
+    /**
+     * Excutes shell command and returns the result.
+     *
+     * @param command command to run.
+     * @return result from the command. If the result was {@code null}, empty string ("") will be
+     *    returned instead. Otherwise, trimmed result will be returned.
+     */
+    protected @Nonnull String executeShellCommand(final String command) throws Exception {
+        CLog.d("Starting command " + command);
+        String commandOutput = getDevice().executeShellCommand(command);
+        CLog.d("Output for command " + command + ": " + commandOutput);
+        return commandOutput != null ? commandOutput.trim() : "";
+    }
+
+    private int createAndStartUser(String extraParam) throws Exception {
+        String command = "pm create-user" + extraParam + " TestUser_" + System.currentTimeMillis();
+        String commandOutput = executeShellCommand(command);
+
+        String[] tokens = commandOutput.split("\\s+");
+        assertTrue(tokens.length > 0);
+        assertEquals("Success:", tokens[0]);
+        int userId = Integer.parseInt(tokens[tokens.length-1]);
+
+        // Start user for MediaSessionService to notice the created user.
+        getDevice().startUser(userId);
+        return userId;
+    }
+
+    /**
+     * Creates and starts a new user.
+     */
+    protected int createAndStartUser() throws Exception {
+        return createAndStartUser("");
+    }
+
+    /**
+     * Creates and starts a restricted profile for the {@param parentUserId}.
+     *
+     * @param parentUserId parent user id.
+     */
+    protected int createAndStartRestrictedProfile(int parentUserId) throws Exception {
+        return createAndStartUser(" --profileOf " + parentUserId + " --restricted");
+    }
+
+    /**
+     * Creates and starts a managed profile for the {@param parentUserId}.
+     *
+     * @param parentUserId parent user id.
+     */
+    protected int createAndStartManagedProfile(int parentUserId) throws Exception {
+        return createAndStartUser(" --profileOf " + parentUserId + " --managed");
+    }
+
+    /**
+     * Removes the user that is created during the test.
+     * <p>It will be no-op if the user cannot be removed or doesn't exist.
+     *
+     * @param userId user ID to remove.
+     */
+    protected void removeUser(int userId) throws Exception  {
+        if (getDevice().listUsers().contains(userId) && userId != USER_SYSTEM
+                && !mExistingUsers.contains(userId)) {
+            // Don't log output, as tests sometimes set no debug user restriction, which
+            // causes this to fail, we should still continue and remove the user.
+            String stopUserCommand = "am stop-user -w -f " + userId;
+            CLog.d("Stopping and removing user " + userId);
+            getDevice().executeShellCommand(stopUserCommand);
+            assertTrue("Couldn't remove user", getDevice().removeUser(userId));
+        }
+    }
+
+    /**
+     * Runs tests on the device as if it's {@param userId}.
+     *
+     * @param pkgName test package file name that contains the {@link AndroidTestCase}
+     * @param testClassName Class name to test within the test package. Can be {@code null} if you
+     *    want to run all test classes in the package.
+     * @param testMethodName Method name to test within the test class. Can be {@code null} if you
+     *    want to run all test methods in the class. Will be ignored if {@param testClassName} is
+     *    {@code null}.
+     * @param userId user ID to run the tests as.
+     */
+    protected void runDeviceTestsAsUser(
+            String pkgName, @Nullable String testClassName,
+            @Nullable String testMethodName, int userId) throws DeviceNotAvailableException {
+        if (testClassName != null && testClassName.startsWith(".")) {
+            testClassName = pkgName + testClassName;
+        }
+
+        RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(
+                pkgName, RUNNER, getDevice().getIDevice());
+        testRunner.setMaxTimeToOutputResponse(DEFAULT_SHELL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+        testRunner.addInstrumentationArg(
+                TEST_TIMEOUT_INST_ARGS_KEY, Long.toString(DEFAULT_TEST_TIMEOUT_MILLIS));
+        if (testClassName != null && testMethodName != null) {
+            testRunner.setMethodName(testClassName, testMethodName);
+        } else if (testClassName != null) {
+            testRunner.setClassName(testClassName);
+        }
+
+        CollectingTestListener listener = new CollectingTestListener();
+        assertTrue(getDevice().runInstrumentationTestsAsUser(testRunner, userId, listener));
+
+        final TestRunResult result = listener.getCurrentRunResults();
+        if (result.isRunFailure()) {
+            throw new AssertionError("Failed to successfully run device tests for "
+                    + result.getName() + ": " + result.getRunFailureMessage());
+        }
+        if (result.getNumTests() == 0) {
+            throw new AssertionError("No tests were run on the device");
+        }
+
+        if (result.hasFailedTests()) {
+            // Build a meaningful error message
+            StringBuilder errorBuilder = new StringBuilder("On-device tests failed:\n");
+            for (Map.Entry<TestIdentifier, TestResult> resultEntry :
+                    result.getTestResults().entrySet()) {
+                if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) {
+                    errorBuilder.append(resultEntry.getKey().toString());
+                    errorBuilder.append(":\n");
+                    errorBuilder.append(resultEntry.getValue().getStackTrace());
+                }
+            }
+            throw new AssertionError(errorBuilder.toString());
+        }
+    }
+
+    /**
+     * Checks whether it is possible to create the desired number of users.
+     */
+    protected boolean canCreateAdditionalUsers(int numberOfUsers)
+            throws DeviceNotAvailableException {
+        return getDevice().listUsers().size() + numberOfUsers <=
+                getDevice().getMaxNumberOfUsersSupported();
+    }
+
+    /**
+     * Gets the system setting as a string from the system settings provider for the user.
+     *
+     * @param namespace namespace of the setting.
+     * @param name name of the setting.
+     * @param userId user ID to query the setting. Can be {@link #USER_ALL}.
+     * @return value of the system setting provider with the given namespace and name.
+     *    {@code null}, empty string, or "null" will be returned to the empty string ("") instead.
+     */
+    protected @Nonnull String getSettings(@Nonnull String namespace, @Nonnull String name,
+            int userId) throws Exception {
+        String userFlag = (userId == USER_ALL) ? "" : " --user " + userId;
+        String commandOutput = executeShellCommand(
+                "settings" + userFlag + " get " + namespace + " " + name);
+        if (commandOutput == null || commandOutput.isEmpty() || commandOutput.equals("null")) {
+            commandOutput = "";
+        }
+        return commandOutput;
+    }
+
+    /**
+     * Puts the string to the system settings provider for the user.
+     * <p>This deletes the setting for an empty {@param value} as 'settings put' doesn't allow
+     * putting empty value.
+     *
+     * @param namespace namespace of the setting.
+     * @param name name of the setting.
+     * @param value value of the system setting provider with the given namespace and name.
+     * @param userId user ID to set the setting. Can be {@link #USER_ALL}.
+     */
+    protected void putSettings(@Nonnull String namespace, @Nonnull String name,
+            @Nullable String value, int userId) throws Exception {
+        if (value == null || value.isEmpty()) {
+            // Delete the setting if the value is null or empty as 'settings put' doesn't accept
+            // them.
+            // Ignore userId here because 'settings delete' doesn't support it.
+            executeShellCommand("settings delete " + namespace + " " + name);
+        } else {
+            String userFlag = (userId == USER_ALL) ? "" : " --user " + userId;
+            executeShellCommand("settings" + userFlag + " put " + namespace + " " + name
+                    + " " + value);
+        }
+    }
+}
diff --git a/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java b/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
new file mode 100644
index 0000000..d665f5f
--- /dev/null
+++ b/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.session.cts;
+
+import static android.media.cts.MediaSessionTestHelperConstants.FLAG_CREATE_MEDIA_SESSION;
+import static android.media.cts.MediaSessionTestHelperConstants.FLAG_SET_MEDIA_SESSION_ACTIVE;
+import static android.media.cts.MediaSessionTestHelperConstants.MEDIA_SESSION_TEST_HELPER_APK;
+import static android.media.cts.MediaSessionTestHelperConstants.MEDIA_SESSION_TEST_HELPER_PKG;
+
+import android.media.cts.BaseMultiUserTest;
+import android.media.cts.MediaSessionTestHelperConstants;
+
+import android.platform.test.annotations.RequiresDevice;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.StringJoiner;
+import java.util.StringTokenizer;
+
+/**
+ * Host-side test for the media session manager that installs and runs device-side tests after the
+ * proper device setup.
+ * <p>Corresponding device-side tests are written in the {@link #DEVICE_SIDE_TEST_CLASS}
+ * which is in the {@link #DEVICE_SIDE_TEST_APK}.
+ */
+public class MediaSessionManagerHostTest extends BaseMultiUserTest {
+    /**
+     * Package name of the device-side tests.
+     */
+    private static final String DEVICE_SIDE_TEST_PKG = "android.media.session.cts";
+    /**
+     * Package file name (.apk) for the device-side tests.
+     */
+    private static final String DEVICE_SIDE_TEST_APK = "CtsMediaSessionHostTestApp.apk";
+    /**
+     * Fully qualified class name for the device-side tests.
+     */
+    private static final String DEVICE_SIDE_TEST_CLASS =
+            "android.media.session.cts.MediaSessionManagerTest";
+
+    private static final String SETTINGS_NOTIFICATION_LISTENER_NAMESPACE = "secure";
+    private static final String SETTINGS_NOTIFICATION_LISTENER_NAME =
+            "enabled_notification_listeners";
+
+    // Keep the original notification listener list to clean up.
+    private Map<Integer, String> mNotificationListeners;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mNotificationListeners = new HashMap<>();
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        // Cleanup
+        for (int userId : mNotificationListeners.keySet()) {
+            String notificationListener = mNotificationListeners.get(userId);
+            putSettings(SETTINGS_NOTIFICATION_LISTENER_NAMESPACE,
+                    SETTINGS_NOTIFICATION_LISTENER_NAME, notificationListener, userId);
+        }
+        super.tearDown();
+    }
+
+    /**
+     * Tests {@link MediaSessionManager#getActiveSessions} with the multi-users environment.
+     */
+    @RequiresDevice
+    public void testGetActiveSessions() throws Exception {
+        // Ensure that the previously running media session test helper app doesn't exist.
+        getDevice().uninstallPackage(MEDIA_SESSION_TEST_HELPER_PKG);
+
+        int primaryUserId = getDevice().getPrimaryUserId();
+
+        allowGetActiveSessionForTest(primaryUserId);
+        installAppAsUser(DEVICE_SIDE_TEST_APK, primaryUserId);
+        runTest("testGetActiveSessions_noMediaSessionFromMediaSessionTestHelper");
+
+        installAppAsUser(MEDIA_SESSION_TEST_HELPER_APK, primaryUserId);
+        sendControlCommand(primaryUserId, FLAG_CREATE_MEDIA_SESSION);
+        runTest("testGetActiveSessions_noMediaSessionFromMediaSessionTestHelper");
+
+        sendControlCommand(primaryUserId, FLAG_SET_MEDIA_SESSION_ACTIVE);
+        runTest("testGetActiveSessions_hasMediaSessionFromMediaSessionTestHelper");
+
+        if (!canCreateAdditionalUsers(1)) {
+            CLog.w("Cannot create a new user. Skipping multi-user test cases.");
+            return;
+        }
+
+        // Test if another user can get the session.
+        int newUser = createAndStartUser();
+        installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
+        allowGetActiveSessionForTest(newUser);
+        runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
+        removeUser(newUser);
+
+        // Test if another managed profile can get the session.
+        // Remove the created user first not to exceed system's user number limit.
+        newUser = createAndStartManagedProfile(primaryUserId);
+        installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
+        allowGetActiveSessionForTest(newUser);
+        runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
+        removeUser(newUser);
+
+        // Test if another restricted profile can get the session.
+        // Remove the created user first not to exceed system's user number limit.
+        newUser = createAndStartRestrictedProfile(primaryUserId);
+        installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
+        allowGetActiveSessionForTest(newUser);
+        runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
+    }
+
+    private void runTest(String testMethodName) throws DeviceNotAvailableException {
+        runTestAsUser(testMethodName, getDevice().getPrimaryUserId());
+    }
+
+    private void runTestAsUser(String testMethodName, int userId)
+            throws DeviceNotAvailableException {
+        runDeviceTestsAsUser(DEVICE_SIDE_TEST_PKG, DEVICE_SIDE_TEST_CLASS,
+                testMethodName, userId);
+    }
+
+    /**
+     * Allows the {@link #DEVICE_SIDE_TEST_CLASS} to call
+     * {@link MediaSessionManager#getActiveSessions} for testing.
+     * <p>{@link MediaSessionManager#getActiveSessions} bypasses the permission check if the
+     * caller is the enabled notification listener. This method uses the behavior by making
+     * {@link #DEVICE_SIDE_TEST_CLASS} as the notification listener. So any change in this
+     * should be also applied to the class.
+     * <p>Note that the device-side test {@link android.media.cts.MediaSessionManagerTest} already
+     * covers the test for failing {@link MediaSessionManager#getActiveSessions} without the
+     * permission nor the notification listener.
+     */
+    private void allowGetActiveSessionForTest(int userId) throws Exception {
+        final String NOTIFICATION_LISTENER_DELIM = ":";
+        if (mNotificationListeners.get(userId) != null) {
+            // Already enabled.
+            return;
+        }
+        String list = getSettings(SETTINGS_NOTIFICATION_LISTENER_NAMESPACE,
+                SETTINGS_NOTIFICATION_LISTENER_NAME, userId);
+
+        String notificationListener = DEVICE_SIDE_TEST_PKG + "/" + DEVICE_SIDE_TEST_CLASS;
+        // Ensure that the list doesn't contain notificationListener already.
+        // This can happen if the test is killed while running.
+        StringTokenizer tokenizer = new StringTokenizer(list, NOTIFICATION_LISTENER_DELIM);
+        StringJoiner joiner = new StringJoiner(NOTIFICATION_LISTENER_DELIM);
+        while (tokenizer.hasMoreTokens()) {
+            String token = tokenizer.nextToken();
+            if (!token.isEmpty() && !token.equals(notificationListener)) {
+                joiner.add(token);
+            }
+        }
+        list = joiner.toString();
+        // Preserve the original list.
+        mNotificationListeners.put(userId, list);
+        // Allow get active sessions by setting notification listener.
+        joiner.add(notificationListener);
+        putSettings(SETTINGS_NOTIFICATION_LISTENER_NAMESPACE,
+                SETTINGS_NOTIFICATION_LISTENER_NAME, joiner.toString(), userId);
+    }
+
+    private void sendControlCommand(int userId, int flag) throws Exception {
+        executeShellCommand(MediaSessionTestHelperConstants.buildControlCommand(userId, flag));
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java
index 7b8a695..1a0a0ea 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java
@@ -27,12 +27,6 @@
 
 public abstract class AbstractLifecycleLogActivity extends Activity {
 
-    /**
-     * Used to check if we report same configurations in Activity#onMovedToDisplay and
-     * Activity#onConfigurationChanged.
-     */
-    private Configuration mConfigFromMoveToDisplay;
-
     @Override
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
@@ -49,23 +43,6 @@
     public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         Log.i(getTag(), "onConfigurationChanged");
-
-        // If there was a move to different display - check that we're reporting same config here.
-        if (mConfigFromMoveToDisplay != null) {
-            if (!mConfigFromMoveToDisplay.equals(newConfig)) {
-                throw new IllegalArgumentException(
-                        "Configuration reported in onConfigurationChanged() differs from one"
-                                + " reported in onMovedToDisplay()");
-            }
-            mConfigFromMoveToDisplay = null;
-        }
-    }
-
-    @Override
-    public void onMovedToDisplay(int displayId, Configuration config) {
-        super.onMovedToDisplay(displayId, config);
-        Log.i(getTag(), "onMovedToDisplay");
-        mConfigFromMoveToDisplay = config;
     }
 
     @Override
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/DismissKeyguardMethodActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/DismissKeyguardMethodActivity.java
index 18228e7..df78bb0 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/DismissKeyguardMethodActivity.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/DismissKeyguardMethodActivity.java
@@ -25,12 +25,10 @@
 
 public class DismissKeyguardMethodActivity extends Activity {
 
-    private final String TAG = "DismissKeyguardMethodActivity";
-
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        getSystemService(KeyguardManager.class).dismissKeyguard(this,
-                new KeyguardDismissLoggerCallback(), null);
+        getSystemService(KeyguardManager.class).requestDismissKeyguard(this,
+                new KeyguardDismissLoggerCallback());
     }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LifecycleLogView.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LifecycleLogView.java
index f06def5..66e0cf2 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LifecycleLogView.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LifecycleLogView.java
@@ -25,12 +25,6 @@
 public class LifecycleLogView extends View {
     private final String TAG = "LifecycleLogView";
 
-    /**
-     * Used to check if we report same configurations in View#onMovedToDisplay and
-     * View#onConfigurationChanged.
-     */
-    private Configuration mConfigFromMoveToDisplay;
-
     public LifecycleLogView(Context context) {
         super(context);
     }
@@ -52,22 +46,5 @@
     protected void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         Log.i(TAG, "onConfigurationChanged");
-
-        // If there was a move to different display - check that we're reporting same config here.
-        if (mConfigFromMoveToDisplay != null) {
-            if (!mConfigFromMoveToDisplay.equals(newConfig)) {
-                throw new IllegalArgumentException(
-                        "Configuration reported in onConfigurationChanged() differs from one"
-                                + " reported in onMovedToDisplay()");
-            }
-            mConfigFromMoveToDisplay = null;
-        }
-    }
-
-    @Override
-    public void onMovedToDisplay(int displayId, Configuration config) {
-        super.onMovedToDisplay(displayId, config);
-        Log.i(TAG, "onMovedToDisplay");
-        mConfigFromMoveToDisplay = config;
     }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/PipActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/PipActivity.java
index f60abfa..79d3c3f 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/PipActivity.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/PipActivity.java
@@ -21,8 +21,8 @@
 
 import android.app.Activity;
 import android.app.ActivityOptions;
+import android.app.PictureInPictureParams;
 import android.content.BroadcastReceiver;
-import android.app.PictureInPictureArgs;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -32,6 +32,7 @@
 import android.os.Handler;
 import android.os.SystemClock;
 import android.util.Log;
+import android.util.Rational;
 import android.view.WindowManager;
 
 public class PipActivity extends AbstractLifecycleLogActivity {
@@ -58,12 +59,23 @@
     // Calls enterPictureInPicture() on creation
     private static final String EXTRA_ENTER_PIP = "enter_pip";
     // Used with EXTRA_AUTO_ENTER_PIP, value specifies the aspect ratio to enter PIP with
-    private static final String EXTRA_ENTER_PIP_ASPECT_RATIO = "enter_pip_aspect_ratio";
+    private static final String EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR =
+            "enter_pip_aspect_ratio_numerator";
+    // Used with EXTRA_AUTO_ENTER_PIP, value specifies the aspect ratio to enter PIP with
+    private static final String EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR =
+            "enter_pip_aspect_ratio_denominator";
     // Calls setPictureInPictureAspectRatio with the aspect ratio specified in the value
-    private static final String EXTRA_SET_ASPECT_RATIO = "set_aspect_ratio";
+    private static final String EXTRA_SET_ASPECT_RATIO_NUMERATOR = "set_aspect_ratio_numerator";
+    // Calls setPictureInPictureAspectRatio with the aspect ratio specified in the value
+    private static final String EXTRA_SET_ASPECT_RATIO_DENOMINATOR = "set_aspect_ratio_denominator";
     // Calls setPictureInPictureAspectRatio with the aspect ratio specified in the value with a
     // fixed delay
-    private static final String EXTRA_SET_ASPECT_RATIO_WITH_DELAY = "set_aspect_ratio_with_delay";
+    private static final String EXTRA_SET_ASPECT_RATIO_WITH_DELAY_NUMERATOR =
+            "set_aspect_ratio_with_delay_numerator";
+    // Calls setPictureInPictureAspectRatio with the aspect ratio specified in the value with a
+    // fixed delay
+    private static final String EXTRA_SET_ASPECT_RATIO_WITH_DELAY_DENOMINATOR =
+            "set_aspect_ratio_with_delay_denominator";
     // Adds a click listener to finish this activity when it is clicked
     private static final String EXTRA_TAP_TO_FINISH = "tap_to_finish";
     // Calls requestAutoEnterPictureInPicture() with the value provided
@@ -102,14 +114,17 @@
                         startIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                         startActivity(startIntent);
 
-                        if (intent.hasExtra(EXTRA_SET_ASPECT_RATIO_WITH_DELAY)) {
+                        if (intent.hasExtra(EXTRA_SET_ASPECT_RATIO_WITH_DELAY_NUMERATOR)
+                                && intent.hasExtra(EXTRA_SET_ASPECT_RATIO_WITH_DELAY_DENOMINATOR)) {
                             // Ugly, but required to wait for the startActivity to actually start
                             // the activity...
                             mHandler.postDelayed(() -> {
-                                PictureInPictureArgs args = new PictureInPictureArgs();
-                                args.setAspectRatio(Float.valueOf(intent.getStringExtra(
-                                        EXTRA_SET_ASPECT_RATIO_WITH_DELAY)));
-                                setPictureInPictureArgs(args);
+                                final PictureInPictureParams.Builder builder =
+                                        new PictureInPictureParams.Builder();
+                                builder.setAspectRatio(getAspectRatio(intent,
+                                        EXTRA_SET_ASPECT_RATIO_WITH_DELAY_NUMERATOR,
+                                        EXTRA_SET_ASPECT_RATIO_WITH_DELAY_DENOMINATOR));
+                                setPictureInPictureParams(builder.build());
                             }, 100);
                         }
                         break;
@@ -142,26 +157,33 @@
 
         // Enter picture in picture with the given aspect ratio if provided
         if (getIntent().hasExtra(EXTRA_ENTER_PIP)) {
-            if (getIntent().hasExtra(EXTRA_ENTER_PIP_ASPECT_RATIO)) {
+            if (getIntent().hasExtra(EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR)
+                    && getIntent().hasExtra(EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR)) {
                 try {
-                    final float aspectRatio = Float.valueOf(getIntent().getStringExtra(
-                            EXTRA_ENTER_PIP_ASPECT_RATIO));
-                    enterPictureInPictureMode(new PictureInPictureArgs(aspectRatio, null));
+                    final PictureInPictureParams.Builder builder =
+                            new PictureInPictureParams.Builder();
+                    builder.setAspectRatio(getAspectRatio(getIntent(),
+                            EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR,
+                            EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR));
+                    enterPictureInPictureMode(builder.build());
                 } catch (Exception e) {
                     // This call can fail intentionally if the aspect ratio is too extreme
                 }
             } else {
-                enterPictureInPictureMode();
+                enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
             }
         }
 
         // We need to wait for either enterPictureInPicture() or requestAutoEnterPictureInPicture()
         // to be called before setting the aspect ratio
-        if (getIntent().hasExtra(EXTRA_SET_ASPECT_RATIO)) {
-            final float aspectRatio = Float.valueOf(getIntent().getStringExtra(
-                    EXTRA_SET_ASPECT_RATIO));
+        if (getIntent().hasExtra(EXTRA_SET_ASPECT_RATIO_NUMERATOR)
+                && getIntent().hasExtra(EXTRA_SET_ASPECT_RATIO_DENOMINATOR)) {
+            final PictureInPictureParams.Builder builder =
+                    new PictureInPictureParams.Builder();
+            builder.setAspectRatio(getAspectRatio(getIntent(),
+                    EXTRA_SET_ASPECT_RATIO_NUMERATOR, EXTRA_SET_ASPECT_RATIO_DENOMINATOR));
             try {
-                setPictureInPictureArgs(new PictureInPictureArgs(aspectRatio, null));
+                setPictureInPictureParams(builder.build());
             } catch (Exception e) {
                 // This call can fail intentionally if the aspect ratio is too extreme
             }
@@ -214,7 +236,7 @@
 
         // Enter PIP on move to background
         if (getIntent().hasExtra(EXTRA_ENTER_PIP_ON_PAUSE)) {
-            enterPictureInPictureMode();
+            enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
         }
     }
 
@@ -223,7 +245,7 @@
         super.onStop();
 
         if (getIntent().hasExtra(EXTRA_ASSERT_NO_ON_STOP_BEFORE_PIP) && !mEnteredPictureInPicture) {
-            Log.w("PipActivity", "Unexpected onStop() called before entering picture-in-picture");
+            Log.w(TAG, "Unexpected onStop() called before entering picture-in-picture");
             finish();
         }
     }
@@ -239,6 +261,13 @@
     public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
         super.onPictureInPictureModeChanged(isInPictureInPictureMode);
 
+        // Fail early if the activity state does not match the dispatched state
+        if (isInPictureInPictureMode() != isInPictureInPictureMode) {
+            Log.w(TAG, "Received onPictureInPictureModeChanged mode=" + isInPictureInPictureMode
+                    + " activityState=" + isInPictureInPictureMode());
+            finish();
+        }
+
         // Mark that we've entered picture-in-picture so that we can stop checking for
         // EXTRA_ASSERT_NO_ON_STOP_BEFORE_PIP
         if (isInPictureInPictureMode) {
@@ -250,7 +279,7 @@
             // checking that the stacks ever changed). Therefor, we need to delay here slightly to
             // allow the tests to verify that the stacks have changed before re-entering.
             mHandler.postDelayed(() -> {
-                enterPictureInPictureMode();
+                enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
             }, 1000);
         }
     }
@@ -284,4 +313,13 @@
     protected String getTag() {
         return TAG;
     }
+
+    /**
+     * @return a {@link Rational} aspect ratio from the given intent and extras.
+     */
+    private Rational getAspectRatio(Intent intent, String extraNum, String extraDenom) {
+        return new Rational(
+                Integer.valueOf(intent.getStringExtra(extraNum)),
+                Integer.valueOf(intent.getStringExtra(extraDenom)));
+    }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
index f40ea04..9ad9d29 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
@@ -1126,36 +1126,6 @@
     }
 
     /**
-     * Tests that when activities that handle configuration changes are moved between displays,
-     * they receive onMovedToDisplay and onConfigurationChanged callbacks.
-     */
-    @Presubmit
-    public void testOnMovedToDisplayCallback() throws Exception {
-        if (!supportsMultiDisplay()) { return; }
-
-        // Create new virtual display.
-        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
-        mAmWmState.assertVisibility(VIRTUAL_DISPLAY_ACTIVITY, true /* visible */);
-
-        // Launch activity on new secondary display.
-        launchActivityOnDisplay(RESIZEABLE_ACTIVITY_NAME, newDisplay.mDisplayId);
-        mAmWmState.assertFocusedActivity("Focus must be on secondary display",
-                RESIZEABLE_ACTIVITY_NAME);
-
-        final String logSeparator = clearLogcat();
-        moveActivityToStack(RESIZEABLE_ACTIVITY_NAME, FULLSCREEN_WORKSPACE_STACK_ID);
-        mAmWmState.waitForFocusedStack(mDevice, FULLSCREEN_WORKSPACE_STACK_ID);
-        mAmWmState.assertFocusedActivity("Focus must be on moved activity",
-                RESIZEABLE_ACTIVITY_NAME);
-        mAmWmState.assertFocusedStack("Focus must return to primary display",
-                FULLSCREEN_WORKSPACE_STACK_ID);
-
-        // Check if client received the callbacks.
-        assertMovedToDisplay(RESIZEABLE_ACTIVITY_NAME, logSeparator);
-        assertMovedToDisplay("LifecycleLogView", logSeparator);
-    }
-
-    /**
      * Tests that when an activity is launched with displayId specified and there is an existing
      * matching task on some other display - that task will moved to the target display.
      */
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java
index 038eb8d..65f507e 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java
@@ -49,9 +49,16 @@
 
     private static final String EXTRA_FIXED_ORIENTATION = "fixed_orientation";
     private static final String EXTRA_ENTER_PIP = "enter_pip";
-    private static final String EXTRA_ENTER_PIP_ASPECT_RATIO = "enter_pip_aspect_ratio";
-    private static final String EXTRA_SET_ASPECT_RATIO = "set_aspect_ratio";
-    private static final String EXTRA_SET_ASPECT_RATIO_WITH_DELAY = "set_aspect_ratio_with_delay";
+    private static final String EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR =
+            "enter_pip_aspect_ratio_numerator";
+    private static final String EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR =
+            "enter_pip_aspect_ratio_denominator";
+    private static final String EXTRA_SET_ASPECT_RATIO_NUMERATOR = "set_aspect_ratio_numerator";
+    private static final String EXTRA_SET_ASPECT_RATIO_DENOMINATOR = "set_aspect_ratio_denominator";
+    private static final String EXTRA_SET_ASPECT_RATIO_WITH_DELAY_NUMERATOR =
+            "set_aspect_ratio_with_delay_numerator";
+    private static final String EXTRA_SET_ASPECT_RATIO_WITH_DELAY_DENOMINATOR =
+            "set_aspect_ratio_with_delay_denominator";
     private static final String EXTRA_ENTER_PIP_ON_PAUSE = "enter_pip_on_pause";
     private static final String EXTRA_TAP_TO_FINISH = "tap_to_finish";
     private static final String EXTRA_START_ACTIVITY = "start_activity";
@@ -91,11 +98,13 @@
     private static final float FLOAT_COMPARE_EPSILON = 0.005f;
 
     // Corresponds to com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio
-    private static final float MIN_ASPECT_RATIO = 1f / 2.39f;
-    private static final float BELOW_MIN_ASPECT_RATIO = MIN_ASPECT_RATIO - FLOAT_COMPARE_EPSILON;
+    private static final int MIN_ASPECT_RATIO_NUMERATOR = 100;
+    private static final int MIN_ASPECT_RATIO_DENOMINATOR = 239;
+    private static final int BELOW_MIN_ASPECT_RATIO_DENOMINATOR = MIN_ASPECT_RATIO_DENOMINATOR + 1;
     // Corresponds to com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio
-    private static final float MAX_ASPECT_RATIO = 2.39f;
-    private static final float ABOVE_MAX_ASPECT_RATIO = MAX_ASPECT_RATIO + FLOAT_COMPARE_EPSILON;
+    private static final int MAX_ASPECT_RATIO_NUMERATOR = 239;
+    private static final int MAX_ASPECT_RATIO_DENOMINATOR = 100;
+    private static final int ABOVE_MAX_ASPECT_RATIO_NUMERATOR = MAX_ASPECT_RATIO_NUMERATOR + 1;
 
     public void testEnterPictureInPictureMode() throws Exception {
         pinnedStackTester(getAmStartCmd(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true"), PIP_ACTIVITY,
@@ -270,42 +279,44 @@
     }
 
     public void testEnterPipAspectRatioMin() throws Exception {
-        testEnterPipAspectRatio(MAX_ASPECT_RATIO);
+        testEnterPipAspectRatio(MIN_ASPECT_RATIO_NUMERATOR, MIN_ASPECT_RATIO_DENOMINATOR);
     }
 
     public void testEnterPipAspectRatioMax() throws Exception {
-        testEnterPipAspectRatio(MIN_ASPECT_RATIO);
+        testEnterPipAspectRatio(MAX_ASPECT_RATIO_NUMERATOR, MAX_ASPECT_RATIO_DENOMINATOR);
     }
 
-    private void testEnterPipAspectRatio(float aspectRatio) throws Exception {
+    private void testEnterPipAspectRatio(int num, int denom) throws Exception {
         if (!supportsPip()) return;
 
         launchActivity(PIP_ACTIVITY,
                 EXTRA_ENTER_PIP, "true",
-                EXTRA_ENTER_PIP_ASPECT_RATIO, Float.toString(aspectRatio));
+                EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR, Integer.toString(num),
+                EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR, Integer.toString(denom));
         assertPinnedStackExists();
 
         // Assert that we have entered PIP and that the aspect ratio is correct
         Rectangle pinnedStackBounds =
                 mAmWmState.getAmState().getStackById(PINNED_STACK_ID).getBounds();
         assertTrue(floatEquals((float) pinnedStackBounds.width / pinnedStackBounds.height,
-                aspectRatio));
+                (float) num / denom));
     }
 
     public void testResizePipAspectRatioMin() throws Exception {
-        testResizePipAspectRatio(MIN_ASPECT_RATIO);
+        testResizePipAspectRatio(MIN_ASPECT_RATIO_NUMERATOR, MIN_ASPECT_RATIO_DENOMINATOR);
     }
 
     public void testResizePipAspectRatioMax() throws Exception {
-        testResizePipAspectRatio(MAX_ASPECT_RATIO);
+        testResizePipAspectRatio(MAX_ASPECT_RATIO_NUMERATOR, MAX_ASPECT_RATIO_DENOMINATOR);
     }
 
-    private void testResizePipAspectRatio(float aspectRatio) throws Exception {
+    private void testResizePipAspectRatio(int num, int denom) throws Exception {
         if (!supportsPip()) return;
 
         launchActivity(PIP_ACTIVITY,
                 EXTRA_ENTER_PIP, "true",
-                EXTRA_SET_ASPECT_RATIO, Float.toString(aspectRatio));
+                EXTRA_SET_ASPECT_RATIO_NUMERATOR, Integer.toString(num),
+                EXTRA_SET_ASPECT_RATIO_DENOMINATOR, Integer.toString(denom));
         assertPinnedStackExists();
 
         // Hacky, but we need to wait for the enterPictureInPicture animation to complete and
@@ -314,7 +325,8 @@
         mAmWmState.waitForWithAmState(mDevice, (state) -> {
             Rectangle pinnedStackBounds = state.getStackById(PINNED_STACK_ID).getBounds();
             boolean isValidAspectRatio = floatEquals(
-                    (float) pinnedStackBounds.width / pinnedStackBounds.height, aspectRatio);
+                    (float) pinnedStackBounds.width / pinnedStackBounds.height,
+                    (float) num / denom);
             result[0] = isValidAspectRatio;
             return isValidAspectRatio;
         }, "Waiting for pinned stack to be resized");
@@ -322,45 +334,54 @@
     }
 
     public void testEnterPipExtremeAspectRatioMin() throws Exception {
-        testEnterPipExtremeAspectRatio(BELOW_MIN_ASPECT_RATIO);
+        testEnterPipExtremeAspectRatio(MIN_ASPECT_RATIO_NUMERATOR,
+                BELOW_MIN_ASPECT_RATIO_DENOMINATOR);
     }
 
     public void testEnterPipExtremeAspectRatioMax() throws Exception {
-        testEnterPipExtremeAspectRatio(ABOVE_MAX_ASPECT_RATIO);
+        testEnterPipExtremeAspectRatio(ABOVE_MAX_ASPECT_RATIO_NUMERATOR,
+                MAX_ASPECT_RATIO_DENOMINATOR);
     }
 
-    private void testEnterPipExtremeAspectRatio(float aspectRatio) throws Exception {
+    private void testEnterPipExtremeAspectRatio(int num, int denom) throws Exception {
         if (!supportsPip()) return;
 
         // Assert that we could not create a pinned stack with an extreme aspect ratio
         launchActivity(PIP_ACTIVITY,
                 EXTRA_ENTER_PIP, "true",
-                EXTRA_ENTER_PIP_ASPECT_RATIO, Float.toString(aspectRatio));
+                EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR, Integer.toString(num),
+                EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR, Integer.toString(denom));
         assertPinnedStackDoesNotExist();
     }
 
     public void testSetPipExtremeAspectRatioMin() throws Exception {
-        testSetPipExtremeAspectRatio(BELOW_MIN_ASPECT_RATIO);
+        testSetPipExtremeAspectRatio(MIN_ASPECT_RATIO_NUMERATOR,
+                BELOW_MIN_ASPECT_RATIO_DENOMINATOR);
     }
 
     public void testSetPipExtremeAspectRatioMax() throws Exception {
-        testSetPipExtremeAspectRatio(ABOVE_MAX_ASPECT_RATIO);
+        testSetPipExtremeAspectRatio(ABOVE_MAX_ASPECT_RATIO_NUMERATOR,
+                MAX_ASPECT_RATIO_DENOMINATOR);
     }
 
-    private void testSetPipExtremeAspectRatio(float aspectRatio) throws Exception {
+    private void testSetPipExtremeAspectRatio(int num, int denom) throws Exception {
         if (!supportsPip()) return;
 
         // Try to resize the a normal pinned stack to an extreme aspect ratio and ensure that
         // fails (the aspect ratio remains the same)
         launchActivity(PIP_ACTIVITY,
                 EXTRA_ENTER_PIP, "true",
-                EXTRA_ENTER_PIP_ASPECT_RATIO, Float.toString(MAX_ASPECT_RATIO),
-                EXTRA_SET_ASPECT_RATIO, Float.toString(aspectRatio));
+                EXTRA_ENTER_PIP_ASPECT_RATIO_NUMERATOR,
+                        Integer.toString(MAX_ASPECT_RATIO_NUMERATOR),
+                EXTRA_ENTER_PIP_ASPECT_RATIO_DENOMINATOR,
+                        Integer.toString(MAX_ASPECT_RATIO_DENOMINATOR),
+                EXTRA_SET_ASPECT_RATIO_NUMERATOR, Integer.toString(num),
+                EXTRA_SET_ASPECT_RATIO_DENOMINATOR, Integer.toString(denom));
         assertPinnedStackExists();
         Rectangle pinnedStackBounds =
                 mAmWmState.getAmState().getStackById(PINNED_STACK_ID).getBounds();
         assertTrue(floatEquals((float) pinnedStackBounds.width / pinnedStackBounds.height,
-                MAX_ASPECT_RATIO));
+                (float) MAX_ASPECT_RATIO_NUMERATOR / MAX_ASPECT_RATIO_DENOMINATOR));
     }
 
     public void testDisallowPipLaunchFromStoppedActivity() throws Exception {
@@ -434,7 +455,8 @@
         // Launch the PIP activity on pause, and set the aspect ratio
         launchActivity(PIP_ACTIVITY,
                 EXTRA_ENTER_PIP_ON_PAUSE, "true",
-                EXTRA_SET_ASPECT_RATIO, Float.toString(MAX_ASPECT_RATIO));
+                EXTRA_SET_ASPECT_RATIO_NUMERATOR, Integer.toString(MAX_ASPECT_RATIO_NUMERATOR),
+                EXTRA_SET_ASPECT_RATIO_DENOMINATOR, Integer.toString(MAX_ASPECT_RATIO_DENOMINATOR));
 
         // Go home while the pip activity is open to trigger auto-PIP
         launchHomeActivity();
@@ -446,7 +468,8 @@
         mAmWmState.waitForWithAmState(mDevice, (state) -> {
             Rectangle pinnedStackBounds = state.getStackById(PINNED_STACK_ID).getBounds();
             boolean isValidAspectRatio = floatEquals(
-                    (float) pinnedStackBounds.width / pinnedStackBounds.height, MAX_ASPECT_RATIO);
+                    (float) pinnedStackBounds.width / pinnedStackBounds.height,
+                    (float) MAX_ASPECT_RATIO_NUMERATOR / MAX_ASPECT_RATIO_DENOMINATOR);
             result[0] = isValidAspectRatio;
             return isValidAspectRatio;
         }, "Waiting for pinned stack to be resized");
@@ -806,8 +829,9 @@
 
         // Trigger it to go back to fullscreen and try to set the aspect ratio, and ensure that the
         // call to set the aspect ratio did not prevent the PiP from returning to fullscreen
-        executeShellCommand("am broadcast -a " + PIP_ACTIVITY_ACTION_EXPAND_PIP + " -e "
-                + EXTRA_SET_ASPECT_RATIO_WITH_DELAY + " 1.23456789");
+        executeShellCommand("am broadcast -a " + PIP_ACTIVITY_ACTION_EXPAND_PIP
+                + " -e " + EXTRA_SET_ASPECT_RATIO_WITH_DELAY_NUMERATOR + " 123456789"
+                + " -e " + EXTRA_SET_ASPECT_RATIO_WITH_DELAY_DENOMINATOR + " 100000000");
         mAmWmState.waitForValidState(mDevice, PIP_ACTIVITY, FULLSCREEN_WORKSPACE_STACK_ID);
         assertPinnedStackDoesNotExist();
     }
@@ -851,6 +875,9 @@
         assertPinnedStackExists();
         int taskId = mAmWmState.getAmState().getStackById(PINNED_STACK_ID).getTopTask().mTaskId;
 
+        // Ensure that we don't any any other overlays as a result of launching into PIP
+        launchHomeActivity();
+
         // Launch task overlay activity into PiP activity task
         launchActivityAsTaskOverlay(TRANSLUCENT_TEST_ACTIVITY, taskId, PINNED_STACK_ID);
 
@@ -858,10 +885,7 @@
         executeShellCommand("am broadcast -a " + PIP_ACTIVITY_ACTION_FINISH);
         mAmWmState.waitForWithAmState(mDevice, (amState) -> {
             ActivityStack stack = amState.getStackById(PINNED_STACK_ID);
-            if (stack != null) {
-                return false;
-            }
-            return true;
+            return stack == null;
         }, "Waiting for pinned stack to be removed...");
         assertPinnedStackDoesNotExist();
     }
@@ -908,15 +932,13 @@
         if (expectTopTaskHasActivity) {
             ActivityTask topTask = mAmWmState.getAmState().getStackById(
                     FULLSCREEN_WORKSPACE_STACK_ID).getTopTask();
-            Activity topActivity = topTask.mActivities.get(0);
-            assertTrue(topActivity.name.equals(ActivityManagerTestBase.getActivityComponentName(
+            assertTrue(topTask.containsActivity(ActivityManagerTestBase.getActivityComponentName(
                     activityName)));
         }
         if (expectBottomTaskHasActivity) {
             ActivityTask bottomTask = mAmWmState.getAmState().getStackById(
                     FULLSCREEN_WORKSPACE_STACK_ID).getBottomTask();
-            Activity bottomActivity = bottomTask.mActivities.get(0);
-            assertTrue(bottomActivity.name.equals(ActivityManagerTestBase.getActivityComponentName(
+            assertTrue(bottomTask.containsActivity(ActivityManagerTestBase.getActivityComponentName(
                     activityName)));
         }
     }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java
index 877369a..a6a7cd8 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java
@@ -17,6 +17,7 @@
 package android.server.cts;
 
 import android.server.cts.WindowManagerState.WindowState;
+import android.server.cts.ActivityManagerState.ActivityStack;
 
 /**
  * Build: mmma -j32 cts/hostsidetests/services
@@ -154,6 +155,26 @@
     }
 
     /**
+     * Test that showWhenLocked activity is fullscreen when shown over keyguard
+     */
+    public void testShowWhenLockedActivityWhileSplit() throws Exception {
+        if (!isHandheld() || !supportsSplitScreenMultiWindow()) {
+            return;
+        }
+        launchActivityInDockStack(LAUNCHING_ACTIVITY);
+        launchActivityToSide(true, false, "ShowWhenLockedActivity");
+        mAmWmState.assertVisibility("ShowWhenLockedActivity", true);
+        gotoKeyguard();
+        mAmWmState.computeState(mDevice, new String[] { "ShowWhenLockedActivity" });
+        mAmWmState.assertVisibility("ShowWhenLockedActivity", true);
+        assertShowingAndOccluded();
+        mAmWmState.assertDoesNotContainStack("Activity must be full screen.",
+                ActivityManagerTestBase.DOCKED_STACK_ID);
+        pressHomeButton();
+        unlockDevice();
+    }
+
+    /**
      * Tests whether a FLAG_DISMISS_KEYGUARD activity occludes Keyguard.
      */
     public void testDismissKeyguardActivity() throws Exception {
diff --git a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java
index 6565215..56fed31 100644
--- a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java
+++ b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java
@@ -607,6 +607,18 @@
         public String getResizeMode() {
             return mResizeMode;
         }
+
+        /**
+         * @return whether this task contains the given activity.
+         */
+        public boolean containsActivity(String activityName) {
+            for (Activity activity : mActivities) {
+                if (activity.name.equals(activityName)) {
+                    return true;
+                }
+            }
+            return false;
+        }
     }
 
     static class Activity {
diff --git a/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/app/src/android/app/cts/ActivityManagerTest.java
index f29ae1e..045301d 100644
--- a/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -329,12 +329,18 @@
         for (RunningAppProcessInfo ra : list) {
             if (ra.processName.equals(SYSTEM_PROCESS)) {
                 hasSystemProcess = true;
+
+                // Make sure the importance is a sane value.
+                assertTrue(ra.importance >= RunningAppProcessInfo.IMPORTANCE_FOREGROUND);
+                assertTrue(ra.importance < RunningAppProcessInfo.IMPORTANCE_GONE);
             } else if (ra.processName.equals(TEST_PROCESS)) {
                 hasTestProcess = true;
             }
         }
+
         // For security reasons the system process is not exposed.
-        assertTrue(!hasSystemProcess && hasTestProcess);
+        assertFalse(hasSystemProcess);
+        assertTrue(hasTestProcess);
 
         for (RunningAppProcessInfo ra : list) {
             if (ra.processName.equals("android.app.stubs:remote")) {
@@ -359,6 +365,17 @@
         fail("android.app.stubs:remote process should be available");
     }
 
+    public void testGetMyMemoryState() {
+        final RunningAppProcessInfo ra = new RunningAppProcessInfo();
+        ActivityManager.getMyMemoryState(ra);
+
+        assertEquals(mContext.getApplicationInfo().processName, ra.processName);
+        assertEquals(android.os.Process.myUid(), ra.uid);
+
+        // When an instrumentation test is running, the importance is high.
+        assertEquals(RunningAppProcessInfo.IMPORTANCE_FOREGROUND, ra.importance);
+    }
+
     public void testGetProcessInErrorState() throws Exception {
         List<ActivityManager.ProcessErrorStateInfo> errList = null;
         errList = mActivityManager.getProcessesInErrorState();
diff --git a/tests/app/src/android/app/cts/AlertWindowsTests.java b/tests/app/src/android/app/cts/AlertWindowsTests.java
index f7c8ff8..bd97727 100644
--- a/tests/app/src/android/app/cts/AlertWindowsTests.java
+++ b/tests/app/src/android/app/cts/AlertWindowsTests.java
@@ -17,7 +17,7 @@
 package android.app.cts;
 
 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
-import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE_DEPRECATED;
+import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE_PRE_26;
 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
 import static android.content.Context.BIND_ALLOW_OOM_MANAGEMENT;
 import static android.content.Context.BIND_AUTO_CREATE;
@@ -31,8 +31,10 @@
 import static com.android.app2.AlertWindowService.NOTIFICATION_MESSENGER_EXTRA;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
 
 import android.app.ActivityManager;
+import android.app.ActivityManager.RunningAppProcessInfo;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -44,6 +46,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.Messenger;
+import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.runner.AndroidJUnit4;
@@ -57,6 +60,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
 
 /**
@@ -127,34 +131,38 @@
     public void testAlertWindowOomAdj() throws Exception {
         setAlertWindowPermission(true /* allow */);
 
-        assertPackageImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_DEPRECATED);
-        assertUidImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_DEPRECATED);
+        assertPackageImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_PRE_26);
+        assertUidImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_PRE_26);
 
         addAlertWindow();
         // Process importance should be increased to visible when the service has an alert window.
         assertPackageImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
-
-        // TODO: Somehow getUidImportance still returns 230 (IMPORTANCE_PERCEPTIBLE) instead of
-        // IMPORTANCE_VISIBLE(200)
-        // assertUidImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
+        assertUidImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
 
         addAlertWindow();
         assertPackageImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
+        assertUidImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
 
         setAlertWindowPermission(false /* allow */);
         // Process importance should no longer be visible since its alert windows are not allowed to
         // be visible.
-        assertPackageImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_DEPRECATED);
+        assertPackageImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_PRE_26);
+        assertUidImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_PRE_26);
+
         setAlertWindowPermission(true /* allow */);
         // They can show again so importance should be visible again.
         assertPackageImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
+        assertUidImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
 
         removeAlertWindow();
         assertPackageImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
+        assertUidImportance(IMPORTANCE_VISIBLE, IMPORTANCE_VISIBLE);
+
         removeAlertWindow();
         // Process importance should no longer be visible when the service no longer as alert
         // windows.
-        assertPackageImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_DEPRECATED);
+        assertPackageImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_PRE_26);
+        assertUidImportance(IMPORTANCE_PERCEPTIBLE, IMPORTANCE_PERCEPTIBLE_PRE_26);
     }
 
     private void addAlertWindow() throws Exception {
@@ -181,7 +189,7 @@
 
     private void assertImportance(Function<ActivityManager, Integer> apiCaller,
             int expectedForO, int expectedForPreO) throws Exception {
-        int retry = 3;
+        final long TIMEOUT = SystemClock.uptimeMillis() + TimeUnit.SECONDS.toMillis(30);
         int actual;
 
         do {
@@ -190,7 +198,7 @@
             // doesn't really work for this use case right now...
             Thread.sleep(500);
             actual = apiCaller.apply(mAm);
-        } while (actual != expectedForO && --retry > 0);
+        } while (actual != expectedForO && (SystemClock.uptimeMillis() < TIMEOUT));
 
         assertEquals(expectedForO, actual);
 
diff --git a/tests/app/src/android/app/cts/Instrumentation_ActivityMonitorTest.java b/tests/app/src/android/app/cts/Instrumentation_ActivityMonitorTest.java
index 8ffb136..a8d16b7 100644
--- a/tests/app/src/android/app/cts/Instrumentation_ActivityMonitorTest.java
+++ b/tests/app/src/android/app/cts/Instrumentation_ActivityMonitorTest.java
@@ -86,17 +86,17 @@
 
     /**
      * Verifies that
-     *   - when ActivityMonitor.onMatchIntent returs non-null, then there is monitor hit.
-     *   - when ActivityMonitor.onMatchIntent returns null, then the activity start is not blocked.
+     *   - when ActivityMonitor.onStartActivity returs non-null, then there is monitor hit.
+     *   - when ActivityMonitor.onStartActivity returns null, then the activity start is not blocked.
      */
-    public void testActivityMonitor_onMatchIntent() throws Exception {
+    public void testActivityMonitor_onStartActivity() throws Exception {
         final ActivityResult result = new ActivityResult(Activity.RESULT_OK, new Intent());
         final Instrumentation instrumentation = getInstrumentation();
         final Context context = instrumentation.getTargetContext();
         final Intent intent = new Intent(context, InstrumentationTestActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 
-        // Verify when ActivityMonitor.onMatchIntent returns non-null, then there is a monitor hit.
+        // Verify when ActivityMonitor.onStartActivity returns non-null, then there is a monitor hit.
         final CustomActivityMonitor cam1 = new CustomActivityMonitor(result);
         instrumentation.addMonitor(cam1);
         context.startActivity(intent);
@@ -109,7 +109,7 @@
             instrumentation.removeMonitor(cam1);
         }
 
-        // Verify when ActivityMonitor.onMatchIntent returns null, then activity start is not
+        // Verify when ActivityMonitor.onStartActivity returns null, then activity start is not
         // blocked and there is no monitor hit.
         final CustomActivityMonitor cam2 = new CustomActivityMonitor(null);
         instrumentation.addMonitor(cam2);
@@ -128,9 +128,9 @@
     }
 
     /**
-     * Verifies that when ActivityMonitor.onMatchIntent returns non-null, activity start is blocked.
+     * Verifies that when ActivityMonitor.onStartActivity returns non-null, activity start is blocked.
      */
-    public void testActivityMonitor_onMatchIntentBlocks() throws Exception {
+    public void testActivityMonitor_onStartActivityBlocks() throws Exception {
         final Instrumentation instrumentation = getInstrumentation();
         final Context context = instrumentation.getTargetContext();
 
@@ -141,13 +141,13 @@
 
         // Initialize and set activity monitor.
         final int expectedResultCode = 1111;
-        final String expectedAction = "matched_using_onMatchIntent";
+        final String expectedAction = "matched_using_onStartActivity";
         final CustomActivityMonitor cam = new CustomActivityMonitor(
                 new ActivityResult(expectedResultCode, new Intent(expectedAction)));
         instrumentation.addMonitor(cam);
 
         // Start InstrumentationTestActivity from ActivityMonitorTestActivity and verify
-        // it is intercepted using onMatchIntent as expected.
+        // it is intercepted using onStartActivity as expected.
         try {
             final CountDownLatch latch = new CountDownLatch(1);
             amTestActivity.setOnActivityResultListener(
@@ -176,9 +176,9 @@
 
     /**
      * Verifies that when the activity monitor is created using by passing IntentFilter,
-     * then onMatchIntent return value is ignored.
+     * then onStartActivity return value is ignored.
      */
-    public void testActivityMonitor_onMatchIntentAndIntentFilter() throws Exception {
+    public void testActivityMonitor_onStartActivityAndIntentFilter() throws Exception {
         final Instrumentation instrumentation = getInstrumentation();
         final Context context = instrumentation.getTargetContext();
 
@@ -194,7 +194,7 @@
                 new IntentFilter(InstrumentationTestActivity.START_INTENT),
                 new ActivityResult(expectedResultCode, new Intent(expectedAction)),
                 true);
-        cam.setResultToReturn(new ActivityResult(1111, new Intent("matched_using_onMatchIntent")));
+        cam.setResultToReturn(new ActivityResult(1111, new Intent("matched_using_onStartActivity")));
         instrumentation.addMonitor(cam);
 
         // Start explicit InstrumentationTestActivity from ActivityMonitorTestActivity and verify
@@ -227,9 +227,9 @@
 
     /**
      * Verifies that when the activity monitor is created using by passing activity class,
-     * then onMatchIntent return value is ignored.
+     * then onStartActivity return value is ignored.
      */
-    public void testActivityMonitor_onMatchIntentAndActivityClass() throws Exception {
+    public void testActivityMonitor_onStartActivityAndActivityClass() throws Exception {
         final Instrumentation instrumentation = getInstrumentation();
         final Context context = instrumentation.getTargetContext();
 
@@ -245,7 +245,7 @@
                 InstrumentationTestActivity.class.getName(),
                 new ActivityResult(expectedResultCode, new Intent(expectedAction)),
                 true);
-        cam.setResultToReturn(new ActivityResult(2222, new Intent("matched_using_onMatchIntent")));
+        cam.setResultToReturn(new ActivityResult(2222, new Intent("matched_using_onStartActivity")));
         instrumentation.addMonitor(cam);
 
         // Start implicit InstrumentationTestActivity from ActivityMonitorTestActivity and verify
@@ -299,7 +299,7 @@
         }
 
         @Override
-        public ActivityResult onMatchIntent(Intent intent) {
+        public ActivityResult onStartActivity(Intent intent) {
             final boolean implicitInstrumentationTestActivity = intent.getAction() != null &&
                     InstrumentationTestActivity.START_INTENT.equals(intent.getAction());
             final boolean explicitInstrumentationTestActivity = intent.getComponent() != null &&
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 521d5a3..3200409 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -359,7 +359,7 @@
                         .setSmallIcon(R.drawable.black)
                         .setContentTitle("notify#" + id)
                         .setContentText("This is #" + id + "notification  ")
-                        .setTimeout(timeout)
+                        .setTimeoutAfter(timeout)
                         .build();
         mNotificationManager.notify(id, notification);
 
diff --git a/tests/app/src/android/app/cts/NotificationTest.java b/tests/app/src/android/app/cts/NotificationTest.java
index 75f75b2..25c25e3 100644
--- a/tests/app/src/android/app/cts/NotificationTest.java
+++ b/tests/app/src/android/app/cts/NotificationTest.java
@@ -71,16 +71,16 @@
         assertEquals(notificationTime, mNotification.when);
         assertEquals(0, mNotification.icon);
         assertEquals(TICKER_TEXT, mNotification.tickerText);
-        assertEquals(1, mNotification.number);
+        assertEquals(0, mNotification.number);
     }
 
     public void testBuilderConstructor() {
         mNotification = new Notification.Builder(mContext, CHANNEL.getId()).build();
-        assertEquals(CHANNEL.getId(), mNotification.getChannel());
+        assertEquals(CHANNEL.getId(), mNotification.getChannelId());
         assertEquals(Notification.BADGE_ICON_NONE, mNotification.getBadgeIconType());
         assertNull(mNotification.getShortcutId());
         assertEquals(Notification.GROUP_ALERT_ALL, mNotification.getGroupAlertBehavior());
-        assertEquals((long) 0, mNotification.getTimeout());
+        assertEquals((long) 0, mNotification.getTimeoutAfter());
     }
 
     public void testDescribeContents() {
@@ -94,7 +94,7 @@
         mNotification = new Notification.Builder(mContext, CHANNEL.getId())
                 .setBadgeIconType(Notification.BADGE_ICON_SMALL)
                 .setShortcutId(SHORTCUT_ID)
-                .setTimeout(TIMEOUT)
+                .setTimeoutAfter(TIMEOUT)
                 .setSettingsText(SETTING_TEXT)
                 .setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN)
                 .build();
@@ -149,8 +149,8 @@
         assertEquals(mNotification.iconLevel, result.iconLevel);
         assertEquals(mNotification.getShortcutId(), result.getShortcutId());
         assertEquals(mNotification.getBadgeIconType(), result.getBadgeIconType());
-        assertEquals(mNotification.getTimeout(), result.getTimeout());
-        assertEquals(mNotification.getChannel(), result.getChannel());
+        assertEquals(mNotification.getTimeoutAfter(), result.getTimeoutAfter());
+        assertEquals(mNotification.getChannelId(), result.getChannelId());
         assertEquals(mNotification.getSettingsText(), result.getSettingsText());
         assertEquals(mNotification.getGroupAlertBehavior(), result.getGroupAlertBehavior());
 
@@ -210,7 +210,7 @@
                 .setContentIntent(contentIntent)
                 .setBadgeIconType(Notification.BADGE_ICON_SMALL)
                 .setShortcutId(SHORTCUT_ID)
-                .setTimeout(TIMEOUT)
+                .setTimeoutAfter(TIMEOUT)
                 .setSettingsText(SETTING_TEXT)
                 .setGroupAlertBehavior(Notification.GROUP_ALERT_SUMMARY)
                 .build();
@@ -218,10 +218,10 @@
         assertEquals(CONTENT_TITLE, mNotification.extras.getString(Notification.EXTRA_TITLE));
         assertEquals(1, mNotification.icon);
         assertEquals(contentIntent, mNotification.contentIntent);
-        assertEquals(CHANNEL.getId(), mNotification.getChannel());
+        assertEquals(CHANNEL.getId(), mNotification.getChannelId());
         assertEquals(Notification.BADGE_ICON_SMALL, mNotification.getBadgeIconType());
         assertEquals(SHORTCUT_ID, mNotification.getShortcutId());
-        assertEquals(TIMEOUT, mNotification.getTimeout());
+        assertEquals(TIMEOUT, mNotification.getTimeoutAfter());
         assertEquals(SETTING_TEXT, mNotification.getSettingsText());
         assertEquals(Notification.GROUP_ALERT_SUMMARY, mNotification.getGroupAlertBehavior());
     }
diff --git a/tests/autofillservice/res/layout/fat_activity.xml b/tests/autofillservice/res/layout/fat_activity.xml
index c7853c1..6d43320 100644
--- a/tests/autofillservice/res/layout/fat_activity.xml
+++ b/tests/autofillservice/res/layout/fat_activity.xml
@@ -66,4 +66,74 @@
         android:importantForAutofill="yes"
         android:src="@drawable/android" />
 
-</LinearLayout>
\ No newline at end of file
+    <LinearLayout
+         android:id="@+id/not_important_container_excluding_descendants"
+         android:layout_width="wrap_content"
+         android:layout_height="wrap_content"
+         android:importantForAutofill="noExcludeDescendants">
+
+        <FrameLayout
+            android:id="@+id/not_important_container_excluding_descendants_child"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:importantForAutofill="yes">
+
+            <View
+                android:id="@+id/not_important_container_excluding_descendants_grand_child"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:src="@drawable/android">
+            </View>
+
+        </FrameLayout>
+
+    </LinearLayout>
+
+    <LinearLayout
+        android:id="@+id/important_container_excluding_descendants"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:importantForAutofill="yesExcludeDescendants">
+
+        <FrameLayout
+            android:id="@+id/important_container_excluding_descendants_child"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:importantForAutofill="yes">
+
+            <View
+                android:id="@+id/important_container_excluding_descendants_grand_child"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:src="@drawable/android">
+            </View>
+
+        </FrameLayout>
+
+    </LinearLayout>
+
+    <LinearLayout
+        android:id="@+id/not_important_container_mixed_descendants"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:importantForAutofill="no">
+
+        <FrameLayout
+            android:id="@+id/not_important_container_mixed_descendants_child"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:importantForAutofill="yes">
+
+            <ImageView
+                android:id="@+id/not_important_container_mixed_descendants_grand_child"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:src="@drawable/android"
+                android:importantForAutofill="no">
+            </ImageView>
+
+        </FrameLayout>
+
+    </LinearLayout>
+
+</LinearLayout>
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java b/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java
index 786ff40..430c612 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java
@@ -62,9 +62,9 @@
 
         final Parcelable result;
         if (sResponse != null) {
-            result = sResponse.asFillResponse(structure);
+            result = sResponse.asFillResponse((id) -> Helper.findNodeByResourceId(structure, id));
         } else if (sDataset != null) {
-            result = sDataset.asDataset(structure);
+            result = sDataset.asDataset((id) -> Helper.findNodeByResourceId(structure, id));
         } else {
             throw new IllegalStateException("no dataset or response");
         }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java b/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java
index b456dd7..9f5368f 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java
@@ -22,11 +22,11 @@
 import static android.autofillservice.cts.Helper.getAutofillIds;
 import android.app.assist.AssistStructure;
 import android.app.assist.AssistStructure.ViewNode;
-import android.autofillservice.cts.CannedFillResponse.Builder;
 import android.content.IntentSender;
 import android.os.Bundle;
 import android.service.autofill.Dataset;
 import android.service.autofill.FillCallback;
+import android.service.autofill.FillContext;
 import android.service.autofill.FillResponse;
 import android.service.autofill.SaveInfo;
 import android.view.autofill.AutofillId;
@@ -38,6 +38,7 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 
 /**
  * Helper class used to produce a {@link FillResponse} based on expected fields that should be
@@ -66,7 +67,7 @@
     private final IntentSender mAuthentication;
     private final String[] mAuthenticationIds;
     private final String[] mIgnoredIds;
-    private final CharSequence mNegativeActionLabel;
+    private final int mNegativeActionStyle;
     private final IntentSender mNegativeActionListener;
     private final int mFlags;
 
@@ -81,7 +82,7 @@
         mAuthentication = builder.mAuthentication;
         mAuthenticationIds = builder.mAuthenticationIds;
         mIgnoredIds = builder.mIgnoredIds;
-        mNegativeActionLabel = builder.mNegativeActionLabel;
+        mNegativeActionStyle = builder.mNegativeActionStyle;
         mNegativeActionListener = builder.mNegativeActionListener;
         mFlags = builder.mFlags;
     }
@@ -96,45 +97,37 @@
      * Creates a new response, replacing the dataset field ids by the real ids from the assist
      * structure.
      */
-    FillResponse asFillResponse(AssistStructure structure) {
+    FillResponse asFillResponse(Function<String, ViewNode> nodeResolver) {
         final FillResponse.Builder builder = new FillResponse.Builder();
         if (mDatasets != null) {
             for (CannedDataset cannedDataset : mDatasets) {
-                final Dataset dataset = cannedDataset.asDataset(structure);
+                final Dataset dataset = cannedDataset.asDataset(nodeResolver);
                 assertWithMessage("Cannot create datase").that(dataset).isNotNull();
                 builder.addDataset(dataset);
             }
         }
         if (mRequiredSavableIds != null) {
-            final SaveInfo.Builder saveInfo;
-
-            if (mRequiredSavableIds == null) {
-                saveInfo = new SaveInfo.Builder(mSaveType, null);
-            } else {
-                saveInfo = new SaveInfo.Builder(mSaveType,
-                        getAutofillIds(structure, mRequiredSavableIds));
-            }
+            final SaveInfo.Builder saveInfo = new SaveInfo.Builder(mSaveType,
+                    getAutofillIds(nodeResolver, mRequiredSavableIds));
 
             saveInfo.setFlags(mFlags);
 
             if (mOptionalSavableIds != null) {
-                saveInfo.setOptionalIds(getAutofillIds(structure, mOptionalSavableIds));
+                saveInfo.setOptionalIds(getAutofillIds(nodeResolver, mOptionalSavableIds));
             }
             if (mSaveDescription != null) {
                 saveInfo.setDescription(mSaveDescription);
             }
-            if (mNegativeActionLabel != null) {
-                saveInfo.setNegativeAction(mNegativeActionLabel, mNegativeActionListener);
-            }
+            saveInfo.setNegativeAction(mNegativeActionStyle, mNegativeActionListener);
             builder.setSaveInfo(saveInfo.build());
         }
         if (mIgnoredIds != null) {
-            builder.setIgnoredIds(getAutofillIds(structure, mIgnoredIds));
+            builder.setIgnoredIds(getAutofillIds(nodeResolver, mIgnoredIds));
         }
         return builder
                 .setClientState(mExtras)
-                .setAuthentication(getAutofillIds(structure, mAuthenticationIds), mAuthentication,
-                        mPresentation)
+                .setAuthentication(getAutofillIds(nodeResolver, mAuthenticationIds),
+                        mAuthentication, mPresentation)
                 .build();
     }
 
@@ -163,7 +156,7 @@
         private IntentSender mAuthentication;
         private String[] mAuthenticationIds;
         private String[] mIgnoredIds;
-        private CharSequence mNegativeActionLabel;
+        private int mNegativeActionStyle;
         private IntentSender mNegativeActionListener;
         private int mFlags;
 
@@ -246,9 +239,9 @@
         /**
          * Sets the negative action spec.
          */
-        public Builder setNegativeAction(CharSequence label,
+        public Builder setNegativeAction(int style,
                 IntentSender listener) {
-            mNegativeActionLabel = label;
+            mNegativeActionStyle = style;
             mNegativeActionListener = listener;
             return this;
         }
@@ -291,7 +284,7 @@
         /**
          * Creates a new dataset, replacing the field ids by the real ids from the assist structure.
          */
-        Dataset asDataset(AssistStructure structure) {
+        Dataset asDataset(Function<String, ViewNode> nodeResolver) {
             final Dataset.Builder builder = (mPresentation == null)
                     ? new Dataset.Builder()
                     : new Dataset.Builder(mPresentation);
@@ -299,9 +292,8 @@
             if (mFieldValues != null) {
                 for (Map.Entry<String, AutofillValue> entry : mFieldValues.entrySet()) {
                     final String resourceId = entry.getKey();
-                    final ViewNode node = findNodeByResourceId(structure, resourceId);
+                    final ViewNode node = nodeResolver.apply(resourceId);
                     if (node == null) {
-                        dumpStructure("asDataset()", structure);
                         throw new AssertionError("No node with resource id " + resourceId);
                     }
                     final AutofillId id = node.getAutofillId();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java b/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java
index 7e23e57..cf6471b 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java
@@ -18,11 +18,14 @@
 
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_AUTO;
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_NO;
+import static android.view.View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS;
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_YES;
 
+import static android.view.View.IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS;
 import static com.google.common.truth.Truth.assertThat;
 
 import android.os.Bundle;
+import android.view.View;
 import android.widget.EditText;
 import android.widget.ImageView;
 
@@ -38,21 +41,75 @@
     static final String ID_IMAGE = "image";
     static final String ID_IMPORTANT_IMAGE = "important_image";
 
+    static final String ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS =
+            "not_important_container_excluding_descendants";
+    static final String ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_CHILD =
+            "not_important_container_excluding_descendants_child";
+    static final String ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_GRAND_CHILD =
+            "not_important_container_excluding_descendants_grand_child";
+
+    static final String ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS =
+            "important_container_excluding_descendants";
+    static final String ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_CHILD =
+            "important_container_excluding_descendants_child";
+    static final String ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_GRAND_CHILD =
+            "important_container_excluding_descendants_grand_child";
+
+    static final String ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS =
+            "not_important_container_mixed_descendants";
+    static final String ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS_CHILD =
+            "not_important_container_mixed_descendants_child";
+    static final String ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS_GRAND_CHILD =
+            "not_important_container_mixed_descendants_grand_child";
+
     private EditText mCaptcha;
     private EditText mInput;
     private ImageView mImage;
     private ImageView mImportantImage;
 
+    private View mNotImportantContainerExcludingDescendants;
+    private View mNotImportantContainerExcludingDescendantsChild;
+    private View mNotImportantContainerExcludingDescendantsGrandChild;
+
+    private View mImportantContainerExcludingDescendants;
+    private View mImportantContainerExcludingDescendantsChild;
+    private View mImportantContainerExcludingDescendantsGrandChild;
+
+    private View mNotImportantContainerMixedDescendants;
+    private View mNotImportantContainerMixedDescendantsChild;
+    private View mNotImportantContainerMixedDescendantsGrandChild;
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
         setContentView(R.layout.fat_activity);
 
-        mCaptcha = (EditText) findViewById(R.id.captcha);
-        mInput = (EditText) findViewById(R.id.input);
-        mImage = (ImageView) findViewById(R.id.image);
-        mImportantImage = (ImageView) findViewById(R.id.important_image);
+        mCaptcha = findViewById(R.id.captcha);
+        mInput = findViewById(R.id.input);
+        mImage = findViewById(R.id.image);
+        mImportantImage = findViewById(R.id.important_image);
+
+        mNotImportantContainerExcludingDescendants = findViewById(
+                R.id.not_important_container_excluding_descendants);
+        mNotImportantContainerExcludingDescendantsChild = findViewById(
+                R.id.not_important_container_excluding_descendants_child);
+        mNotImportantContainerExcludingDescendantsGrandChild = findViewById(
+                R.id.not_important_container_excluding_descendants_grand_child);
+
+        mImportantContainerExcludingDescendants = findViewById(
+                R.id.important_container_excluding_descendants);
+        mImportantContainerExcludingDescendantsChild = findViewById(
+                R.id.important_container_excluding_descendants_child);
+        mImportantContainerExcludingDescendantsGrandChild = findViewById(
+                R.id.important_container_excluding_descendants_grand_child);
+
+        mNotImportantContainerMixedDescendants = findViewById(
+                R.id.not_important_container_mixed_descendants);
+        mNotImportantContainerMixedDescendantsChild = findViewById(
+                R.id.not_important_container_mixed_descendants_child);
+        mNotImportantContainerMixedDescendantsGrandChild = findViewById(
+                R.id.not_important_container_mixed_descendants_grand_child);
 
         // Sanity check for importantForAutofill modes
         assertThat(mInput.getImportantForAutofill()).isEqualTo(IMPORTANT_FOR_AUTOFILL_YES);
@@ -60,6 +117,26 @@
         assertThat(mImage.getImportantForAutofill()).isEqualTo(IMPORTANT_FOR_AUTOFILL_NO);
         assertThat(mImportantImage.getImportantForAutofill()).isEqualTo(IMPORTANT_FOR_AUTOFILL_YES);
 
+        assertThat(mNotImportantContainerExcludingDescendants.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
+        assertThat(mNotImportantContainerExcludingDescendantsChild.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_YES);
+        assertThat(mNotImportantContainerExcludingDescendantsGrandChild.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_AUTO);
+
+        assertThat(mImportantContainerExcludingDescendants.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS);
+        assertThat(mImportantContainerExcludingDescendantsChild.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_YES);
+        assertThat(mImportantContainerExcludingDescendantsGrandChild.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_AUTO);
+
+        assertThat(mNotImportantContainerMixedDescendants.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_NO);
+        assertThat(mNotImportantContainerMixedDescendantsChild.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_YES);
+        assertThat(mNotImportantContainerMixedDescendantsGrandChild.getImportantForAutofill())
+                .isEqualTo(IMPORTANT_FOR_AUTOFILL_NO);
     }
 
     /**
diff --git a/tests/autofillservice/src/android/autofillservice/cts/FatActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/FatActivityTest.java
index cf3dc0c..a2edf4d 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/FatActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/FatActivityTest.java
@@ -21,6 +21,15 @@
 import static android.autofillservice.cts.FatActivity.ID_IMPORTANT_IMAGE;
 import static android.autofillservice.cts.FatActivity.ID_INPUT;
 import static android.autofillservice.cts.FatActivity.ID_INPUT_CONTAINER;
+import static android.autofillservice.cts.FatActivity.ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS;
+import static android.autofillservice.cts.FatActivity.ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_CHILD;
+import static android.autofillservice.cts.FatActivity.ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_GRAND_CHILD;
+import static android.autofillservice.cts.FatActivity.ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS;
+import static android.autofillservice.cts.FatActivity.ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS_CHILD;
+import static android.autofillservice.cts.FatActivity.ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS_GRAND_CHILD;
+import static android.autofillservice.cts.FatActivity.ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS;
+import static android.autofillservice.cts.FatActivity.ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_CHILD;
+import static android.autofillservice.cts.FatActivity.ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_GRAND_CHILD;
 import static android.autofillservice.cts.Helper.assertNumberOfChildren;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
 import static android.autofillservice.cts.Helper.findNodeByText;
@@ -67,7 +76,7 @@
         // TODO: should only have 5 children, but there is an extra
         // TextView that's probably coming from the title. For now we're just ignoring it, but
         // ideally we should change the .xml to exclude it.
-        assertNumberOfChildren(fillRequest.structure, 6);
+        assertNumberOfChildren(fillRequest.structure, 8);
 
         // Should not have ImageView...
         assertThat(findNodeByResourceId(fillRequest.structure, ID_IMAGE)).isNull();
@@ -88,5 +97,29 @@
         assertThat(inputContainer.getChildCount()).isEqualTo(1);
         final ViewNode input = inputContainer.getChildAt(0);
         assertThat(input.getIdEntry()).isEqualTo(ID_INPUT);
+
+        // Make sure a non-important container can exclude descendants
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS)).isNull();
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_CHILD)).isNull();
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_NOT_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_GRAND_CHILD)).isNull();
+
+        // Make sure an important container can exclude descendants
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS)).isNotNull();
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_CHILD)).isNull();
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_IMPORTANT_CONTAINER_EXCLUDING_DESCENDANTS_GRAND_CHILD)).isNull();
+
+        // Make sure an intermediary descendant can be excluded
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS)).isNull();
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS_CHILD)).isNotNull();
+        assertThat(findNodeByResourceId(fillRequest.structure,
+                ID_NOT_IMPORTANT_CONTAINER_MIXED_DESCENDANTS_GRAND_CHILD)).isNull();
     }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java b/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java
index c9b6d30..d0b6730 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java
@@ -108,6 +108,18 @@
         onCell(row, column, (c) -> c.setText(text));
     }
 
+    public void forceAutofill(int row, int column) {
+        onCell(row, column, (c) -> getAutofillManager().requestAutofill(c));
+    }
+
+    public void triggerAutofill(boolean manually, int row, int column) {
+        if (manually) {
+            forceAutofill(row, column);
+        } else {
+            focusCell(row, column);
+        }
+    }
+
     public String getText(int row, int column) throws InterruptedException {
         final BlockingQueue<String> queue = new LinkedBlockingQueue<>(1);
         onCell(row, column, (c) -> queue.offer(c.getText().toString()));
diff --git a/tests/autofillservice/src/android/autofillservice/cts/Helper.java b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
index e19fa0c..f1491b4 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/Helper.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
@@ -27,6 +27,7 @@
 import android.os.Bundle;
 import android.os.UserManager;
 import android.service.autofill.Dataset;
+import android.service.autofill.FillContext;
 import android.service.autofill.FillResponse;
 import android.support.annotation.NonNull;
 import android.support.test.InstrumentationRegistry;
@@ -40,8 +41,10 @@
 
 import com.android.compatibility.common.util.SystemUtil;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 
 /**
  * Helper for common funcionalities.
@@ -163,6 +166,15 @@
     }
 
     /**
+     * Dump the contexts on logcat.
+     */
+    static void dumpStructure(String message, List<FillContext> contexts) {
+        for (FillContext context : contexts) {
+            dumpStructure(message, context.getStructure());
+        }
+    }
+
+    /**
      * Dumps the state of the autofill service on logcat.
      */
     static void dumpAutofillService() {
@@ -227,6 +239,19 @@
     /**
      * Gets a node given its Android resource id, or {@code null} if not found.
      */
+    static ViewNode findNodeByResourceId(ArrayList<FillContext> contexts, String resourceId) {
+        for (FillContext context : contexts) {
+            ViewNode node = findNodeByResourceId(context.getStructure(), resourceId);
+            if (node != null) {
+                return node;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Gets a node given its Android resource id, or {@code null} if not found.
+     */
     static ViewNode findNodeByResourceId(ViewNode node, String resourceId) {
         if (resourceId.equals(node.getIdEntry())) {
             return node;
@@ -530,15 +555,15 @@
      * Creates an array of {@link AutofillId} mapped from the {@code structure} nodes with the given
      * {@code resourceIds}.
      */
-    static AutofillId[] getAutofillIds(AssistStructure structure, String[] resourceIds) {
+    static AutofillId[] getAutofillIds(Function<String, ViewNode> nodeResolver,
+            String[] resourceIds) {
         if (resourceIds == null) return null;
 
         final AutofillId[] requiredIds = new AutofillId[resourceIds.length];
         for (int i = 0; i < resourceIds.length; i++) {
             final String resourceId = resourceIds[i];
-            final ViewNode node = findNodeByResourceId(structure, resourceId);
+            final ViewNode node = nodeResolver.apply(resourceId);
             if (node == null) {
-                dumpStructure("getAutofillIds()", structure);
                 throw new AssertionError("No node with savable resourceId " + resourceId);
             }
             requiredIds[i] = node.getAutofillId();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java b/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
index 44ca039..61b47af 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
@@ -38,6 +38,7 @@
 import android.service.autofill.SaveCallback;
 import android.util.Log;
 
+import java.util.ArrayList;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
@@ -85,21 +86,17 @@
     @Override
     public void onFillRequest(android.service.autofill.FillRequest request,
             CancellationSignal cancellationSignal, FillCallback callback) {
-        final AssistStructure structure = request.getStructure();
-        if (DUMP_FILL_REQUESTS) dumpStructure("onFillRequest()", structure);
+        if (DUMP_FILL_REQUESTS) dumpStructure("onFillRequest()", request.getFillContexts());
 
-        sReplier.onFillRequest(structure, request.getClientState(), cancellationSignal, callback,
-                request.getFlags());
+        sReplier.onFillRequest(request.getFillContexts(), request.getClientState(),
+                cancellationSignal, callback, request.getFlags());
     }
 
     @Override
     public void onSaveRequest(android.service.autofill.SaveRequest request,
             SaveCallback callback) {
-        final List<FillContext> contexts = request.getFillContexts();
-        final AssistStructure structure = contexts.get(contexts.size() - 1).getStructure();
-
-        if (DUMP_SAVE_REQUESTS) dumpStructure("onSaveRequest()", structure);
-        sReplier.onSaveRequest(structure, request.getClientState(), callback);
+        if (DUMP_SAVE_REQUESTS) dumpStructure("onSaveRequest()", request.getFillContexts());
+        sReplier.onSaveRequest(request.getFillContexts(), request.getClientState(), callback);
     }
 
     /**
@@ -152,18 +149,20 @@
      */
     static final class FillRequest {
         final AssistStructure structure;
+        final ArrayList<FillContext> contexts;
         final Bundle data;
         final CancellationSignal cancellationSignal;
         final FillCallback callback;
         final int flags;
 
-        private FillRequest(AssistStructure structure, Bundle data,
+        private FillRequest(ArrayList<FillContext> contexts, Bundle data,
                 CancellationSignal cancellationSignal, FillCallback callback, int flags) {
-            this.structure = structure;
+            this.contexts = contexts;
             this.data = data;
             this.cancellationSignal = cancellationSignal;
             this.callback = callback;
             this.flags = flags;
+            structure = contexts.get(contexts.size() - 1).getStructure();
         }
     }
 
@@ -173,12 +172,18 @@
      * that can be asserted at the end of a test case.
      */
     static final class SaveRequest {
+        final List<FillContext> contexts;
         final AssistStructure structure;
         final Bundle data;
         final SaveCallback callback;
 
-        private SaveRequest(AssistStructure structure, Bundle data, SaveCallback callback) {
-            this.structure = structure;
+        private SaveRequest(List<FillContext> contexts, Bundle data, SaveCallback callback) {
+            if (contexts != null && contexts.size() > 0) {
+                structure = contexts.get(contexts.size() - 1).getStructure();
+            } else {
+                structure = null;
+            }
+            this.contexts = contexts;
             this.data = data;
             this.callback = callback;
         }
@@ -277,7 +282,7 @@
             mSaveRequests.clear();
         }
 
-        private void onFillRequest(AssistStructure structure, Bundle data,
+        private void onFillRequest(ArrayList<FillContext> contexts, Bundle data,
                 CancellationSignal cancellationSignal, FillCallback callback, int flags) {
             try {
                 CannedFillResponse response = null;
@@ -288,7 +293,7 @@
                     Thread.currentThread().interrupt();
                 }
                 if (response == null) {
-                    dumpStructure("onFillRequest() without response", structure);
+                    dumpStructure("onFillRequest() without response", contexts);
                     throw new IllegalStateException("No CannedResponse");
                 }
                 if (response == NO_RESPONSE) {
@@ -296,19 +301,20 @@
                     return;
                 }
 
-                final FillResponse fillResponse = response.asFillResponse(structure);
+                final FillResponse fillResponse = response.asFillResponse(
+                        (id) -> Helper.findNodeByResourceId(contexts, id));
 
                 Log.v(TAG, "onFillRequest(): fillResponse = " + fillResponse);
                 callback.onSuccess(fillResponse);
             } finally {
-                mFillRequests.offer(new FillRequest(structure, data, cancellationSignal, callback,
+                mFillRequests.offer(new FillRequest(contexts, data, cancellationSignal, callback,
                         flags));
             }
         }
 
-        private void onSaveRequest(AssistStructure structure, Bundle data, SaveCallback callback) {
+        private void onSaveRequest(List<FillContext> contexts, Bundle data, SaveCallback callback) {
             Log.d(TAG, "onSaveRequest()");
-            mSaveRequests.offer(new SaveRequest(structure, data, callback));
+            mSaveRequests.offer(new SaveRequest(contexts, data, callback));
             callback.onSuccess();
         }
     }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
index 30cfde7..51f8e12 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
@@ -61,7 +61,9 @@
 import android.content.IntentFilter;
 import android.content.IntentSender;
 import android.os.Bundle;
+import android.platform.test.annotations.Presubmit;
 import android.service.autofill.FillEventHistory;
+import android.service.autofill.SaveInfo;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.uiautomator.UiObject2;
 import android.view.View;
@@ -334,6 +336,7 @@
     }
 
     @Test
+    @Presubmit
     public void testAutoFillOneDatasetAndSave() throws Exception {
         // Set service.
         enableService();
@@ -1146,7 +1149,7 @@
     }
 
     @Test
-    public void testCustomNegativeSaveButton() throws Exception {
+    public void testRejectStyleNegativeSaveButton() throws Exception {
         enableService();
 
         // Set service behavior.
@@ -1159,7 +1162,7 @@
 
         sReplier.addResponse(new CannedFillResponse.Builder()
                 .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
-                .setNegativeAction("Foo", listener)
+                .setNegativeAction(SaveInfo.NEGATIVE_BUTTON_STYLE_REJECT, listener)
                 .build());
 
         // Trigger auto-fill.
@@ -1185,7 +1188,8 @@
         }, intentFilter);
 
         // Trigger the negative button.
-        sUiBot.saveForAutofill(false, SAVE_DATA_TYPE_PASSWORD);
+        sUiBot.saveForAutofill(SaveInfo.NEGATIVE_BUTTON_STYLE_REJECT,
+                false, SAVE_DATA_TYPE_PASSWORD);
 
         // Wait for the custom action.
         assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
@@ -1194,6 +1198,55 @@
     }
 
     @Test
+    public void testCancelStyleNegativeSaveButton() throws Exception {
+        enableService();
+
+        // Set service behavior.
+
+        final String intentAction = "android.autofillservice.cts.CUSTOM_ACTION";
+
+        // Configure the save UI.
+        final IntentSender listener = PendingIntent.getBroadcast(
+                getContext(), 0, new Intent(intentAction), 0).getIntentSender();
+
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
+                .setNegativeAction(SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL, listener)
+                .build());
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+
+        // Trigger save.
+        mActivity.onUsername((v) -> v.setText("foo"));
+        mActivity.onPassword((v) -> v.setText("foo"));
+        mActivity.tapLogin();
+
+        // Start watching for the negative intent
+        final CountDownLatch latch = new CountDownLatch(1);
+        final IntentFilter intentFilter = new IntentFilter(intentAction);
+        getContext().registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                getContext().unregisterReceiver(this);
+                latch.countDown();
+            }
+        }, intentFilter);
+
+        // Trigger the negative button.
+        sUiBot.saveForAutofill(SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,
+                false, SAVE_DATA_TYPE_PASSWORD);
+
+        // Wait for the custom action.
+        assertThat(latch.await(500, TimeUnit.SECONDS)).isTrue();
+
+        assertNoDanglingSessions();
+    }
+
+    @Test
     public void testGetTextInputType() throws Exception {
         // Set service.
         enableService();
@@ -1253,13 +1306,17 @@
         assertThat(usernameContainer.getChildCount()).isEqualTo(2);
     }
 
+    private static final boolean BUG_36171235_FIXED = false;
+
+    @Test
     public void testAutofillManuallyOneDataset() throws Exception {
         // Set service.
         enableService();
 
+        if (BUG_36171235_FIXED)
         // And activity.
         mActivity.onUsername((v) -> {
-            // v.setAutofillMode(AUTOFILL_MODE_MANUAL);
+            v.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
             // TODO: setting an empty text, otherwise longPress() does not
             // display the AUTOFILL context menu. Need to fix it, but it's a test case issue...
             v.setText("");
@@ -1274,7 +1331,11 @@
         mActivity.expectAutoFill("dude", "sweet");
 
         // Long-press field to trigger AUTOFILL menu.
-        sUiBot.getAutofillMenuOption(ID_USERNAME).click();
+        if (BUG_36171235_FIXED) {
+            sUiBot.getAutofillMenuOption(ID_USERNAME).click();
+        } else {
+            mActivity.onUsername((v) -> mActivity.getAutofillManager().requestAutofill(v));
+        }
 
         final FillRequest fillRequest = sReplier.getNextFillRequest();
         assertThat(fillRequest.flags).isEqualTo(FLAG_MANUAL_REQUEST);
@@ -1286,10 +1347,12 @@
         mActivity.assertAutoFilled();
     }
 
+    @Test
     public void testAutofillManuallyTwoDatasetsPickFirst() throws Exception {
         autofillManuallyTwoDatasets(true);
     }
 
+    @Test
     public void testAutofillManuallyTwoDatasetsPickSecond() throws Exception {
         autofillManuallyTwoDatasets(false);
     }
@@ -1298,9 +1361,10 @@
         // Set service.
         enableService();
 
+        if (BUG_36171235_FIXED)
         // And activity.
         mActivity.onUsername((v) -> {
-            // v.setAutofillMode(AUTOFILL_MODE_MANUAL);
+            v.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
             // TODO: setting an empty text, otherwise longPress() does not display the AUTOFILL
             // context menu. Need to fix it, but it's a test case issue...
             v.setText("");
@@ -1327,7 +1391,11 @@
         }
 
         // Long-press field to trigger AUTOFILL menu.
-        sUiBot.getAutofillMenuOption(ID_USERNAME).click();
+        if (BUG_36171235_FIXED) {
+            sUiBot.getAutofillMenuOption(ID_USERNAME).click();
+        } else {
+            mActivity.onUsername((v) -> mActivity.getAutofillManager().requestAutofill(v));
+        }
 
         final FillRequest fillRequest = sReplier.getNextFillRequest();
         assertThat(fillRequest.flags).isEqualTo(FLAG_MANUAL_REQUEST);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java b/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java
index 32844d4..026cf08 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java
@@ -54,9 +54,11 @@
             if (structure != null) {
                 Parcelable result;
                 if (sResponse != null) {
-                    result = sResponse.asFillResponse(structure);
+                    result = sResponse.asFillResponse(
+                            (id) -> Helper.findNodeByResourceId(structure, id));
                 } else if (sDataset != null) {
-                    result = sDataset.asDataset(structure);
+                    result = sDataset.asDataset(
+                            (id) -> Helper.findNodeByResourceId(structure, id));
                 } else {
                     throw new IllegalStateException("no dataset or response");
                 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MultipleFragmentLoginTest.java b/tests/autofillservice/src/android/autofillservice/cts/MultipleFragmentLoginTest.java
index 76c8c70..d474dc8 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MultipleFragmentLoginTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MultipleFragmentLoginTest.java
@@ -24,8 +24,12 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.app.assist.AssistStructure;
+import android.app.assist.AssistStructure.ViewNode;
+import android.os.Bundle;
 import android.support.test.rule.ActivityTestRule;
 import android.util.Log;
+import android.view.autofill.AutofillValue;
 import android.widget.EditText;
 
 import org.junit.Before;
@@ -52,11 +56,17 @@
     public void loginOnTwoFragments() throws Exception {
         enableService();
         try {
-            // Set expectations.
+            Bundle clientState = new Bundle();
+            clientState.putString("key", "value1");
             sReplier.addResponse(new CannedFillResponse.Builder()
-                    .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, "editText1").build());
+                    .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                            .setField("editText1", "editText1-autofilled")
+                            .setPresentation(createPresentation("dataset1"))
+                            .build())
+                    .setExtras(clientState)
+                    .build());
 
-            final InstrumentedAutoFillService.FillRequest[] request =
+            final InstrumentedAutoFillService.FillRequest[] fillRequest =
                     new InstrumentedAutoFillService.FillRequest[1];
 
             // Trigger autofill
@@ -67,37 +77,123 @@
                 });
 
                 try {
-                    request[0] = sReplier.getNextFillRequest();
+                    fillRequest[0] = sReplier.getNextFillRequest();
                 } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                 }
             }, (int) (FILL_TIMEOUT_MS * 2));
 
-            assertThat(findNodeByResourceId(request[0].structure, "editText1")).isNotNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText2")).isNotNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText3")).isNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText4")).isNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText5")).isNull();
+            assertThat(fillRequest[0].data).isNull();
 
-            Log.i(LOG_TAG, "Switching Fragments");
+            AssistStructure structure = fillRequest[0].contexts.get(0).getStructure();
+            assertThat(fillRequest[0].contexts.size()).isEqualTo(1);
+            assertThat(findNodeByResourceId(structure, "editText1")).isNotNull();
+            assertThat(findNodeByResourceId(structure, "editText2")).isNotNull();
+            assertThat(findNodeByResourceId(structure, "editText3")).isNull();
+            assertThat(findNodeByResourceId(structure, "editText4")).isNull();
+            assertThat(findNodeByResourceId(structure, "editText5")).isNull();
+
+            // Wait until autofill has been applied
+            sUiBot.selectDataset("dataset1");
+            sUiBot.assertShownByText("editText1-autofilled");
+
+            // Manually fill view
+            mActivity.syncRunOnUiThread(() -> mEditText2.setText("editText2-manually-filled"));
 
             // Replacing the fragment focused a previously unknown view which triggers a new
             // partition
+            clientState.putString("key", "value2");
             sReplier.addResponse(new CannedFillResponse.Builder()
-                    .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, "editText3").build());
+                    .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                            .setField("editText3", "editText3-autofilled")
+                            .setField("editText4", "editText4-autofilled")
+                            .setPresentation(createPresentation("dataset2"))
+                            .build())
+                    .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, "editText2", "editText5")
+                    .setExtras(clientState)
+                    .build());
 
+            Log.i(LOG_TAG, "Switching Fragments");
             mActivity.syncRunOnUiThread(
                     () -> mActivity.getFragmentManager().beginTransaction().replace(
                             R.id.rootContainer, new FragmentWithMoreEditTexts(),
                             FRAGMENT_TAG).commitNow());
+            EditText mEditText5 = mActivity.findViewById(R.id.editText5);
 
-            request[0] = sReplier.getNextFillRequest();
+            fillRequest[0] = sReplier.getNextFillRequest();
 
-            assertThat(findNodeByResourceId(request[0].structure, "editText1")).isNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText2")).isNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText3")).isNotNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText4")).isNotNull();
-            assertThat(findNodeByResourceId(request[0].structure, "editText5")).isNotNull();
+            // The fillRequest should have a fillContext for each partition. The first partition
+            // should be filled in
+            assertThat(fillRequest[0].contexts.size()).isEqualTo(2);
+
+            assertThat(fillRequest[0].data.getString("key")).isEqualTo("value1");
+
+            AssistStructure structure1 = fillRequest[0].contexts.get(0).getStructure();
+            ViewNode editText1Node = findNodeByResourceId(structure1, "editText1");
+            // The actual value in the structure is not updated in FillRequest-contexts, but the
+            // autofill value is. For text views in SaveRequest both are updated, but this is the
+            // only exception.
+            assertThat(editText1Node.getAutofillValue()).isEqualTo(
+                    AutofillValue.forText("editText1-autofilled"));
+
+            ViewNode editText2Node = findNodeByResourceId(structure1, "editText2");
+            // Manually filled fields are not send to onFill. They appear in onSave if they are set
+            // as saveable fields.
+            assertThat(editText2Node.getText().toString()).isEqualTo("");
+
+            assertThat(findNodeByResourceId(structure1, "editText3")).isNull();
+            assertThat(findNodeByResourceId(structure1, "editText4")).isNull();
+            assertThat(findNodeByResourceId(structure1, "editText5")).isNull();
+
+            AssistStructure structure2 = fillRequest[0].contexts.get(1).getStructure();
+
+            assertThat(findNodeByResourceId(structure2, "editText1")).isNull();
+            assertThat(findNodeByResourceId(structure2, "editText2")).isNull();
+            assertThat(findNodeByResourceId(structure2, "editText3")).isNotNull();
+            assertThat(findNodeByResourceId(structure2, "editText4")).isNotNull();
+            assertThat(findNodeByResourceId(structure2, "editText5")).isNotNull();
+
+            // Wait until autofill has been applied
+            sUiBot.selectDataset("dataset2");
+            sUiBot.assertShownByText("editText3-autofilled");
+            sUiBot.assertShownByText("editText4-autofilled");
+
+            // Manually fill view
+            mActivity.syncRunOnUiThread(() -> mEditText5.setText("editText5-manually-filled"));
+
+            // Finish activity and save data
+            mActivity.finish();
+            sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_GENERIC);
+
+            // The saveRequest should have a fillContext for each partition with all the data
+            InstrumentedAutoFillService.SaveRequest saveRequest = sReplier.getNextSaveRequest();
+            assertThat(saveRequest.contexts.size()).isEqualTo(2);
+
+            assertThat(saveRequest.data.getString("key")).isEqualTo("value2");
+
+            structure1 = saveRequest.contexts.get(0).getStructure();
+            editText1Node = findNodeByResourceId(structure1, "editText1");
+            assertThat(editText1Node.getText().toString()).isEqualTo("editText1-autofilled");
+
+            editText2Node = findNodeByResourceId(structure1, "editText2");
+            assertThat(editText2Node.getText().toString()).isEqualTo("editText2-manually-filled");
+
+            assertThat(findNodeByResourceId(structure1, "editText3")).isNull();
+            assertThat(findNodeByResourceId(structure1, "editText4")).isNull();
+            assertThat(findNodeByResourceId(structure1, "editText5")).isNull();
+
+            structure2 = saveRequest.contexts.get(1).getStructure();
+            assertThat(findNodeByResourceId(structure2, "editText1")).isNull();
+            assertThat(findNodeByResourceId(structure2, "editText2")).isNull();
+
+            ViewNode editText3Node = findNodeByResourceId(structure2, "editText3");
+            assertThat(editText3Node.getText().toString()).isEqualTo("editText3-autofilled");
+
+            ViewNode editText4Node = findNodeByResourceId(structure2, "editText4");
+            assertThat(editText4Node.getText().toString()).isEqualTo("editText4-autofilled");
+
+            ViewNode editText5Node = findNodeByResourceId(structure2, "editText5");
+            assertThat(editText5Node.getText().toString()).isEqualTo("editText5-manually-filled");
         } finally {
             disableService();
         }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/PartitionedActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/PartitionedActivityTest.java
index 666a63e..19f6b80 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/PartitionedActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/PartitionedActivityTest.java
@@ -25,6 +25,7 @@
 import static android.autofillservice.cts.GridActivity.ID_L4C2;
 import static android.autofillservice.cts.Helper.assertTextIsSanitized;
 import static android.autofillservice.cts.Helper.assertValue;
+import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_ADDRESS;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_CREDIT_CARD;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
@@ -79,6 +80,7 @@
         // Trigger auto-fill on 1st partition.
         mActivity.focusCell(1, 1);
         final FillRequest fillRequest1 = sReplier.getNextFillRequest();
+        assertThat(fillRequest1.flags).isEqualTo(0);
         final ViewNode p1l1c1 = assertTextIsSanitized(fillRequest1.structure, ID_L1C1);
         final ViewNode p1l1c2 = assertTextIsSanitized(fillRequest1.structure, ID_L1C2);
         assertWithMessage("Focus on p1l1c1").that(p1l1c1.isFocused()).isTrue();
@@ -101,6 +103,7 @@
         // Trigger auto-fill on 2nd partition.
         mActivity.focusCell(2, 1);
         final FillRequest fillRequest2 = sReplier.getNextFillRequest();
+        assertThat(fillRequest2.flags).isEqualTo(0);
         final ViewNode p2l1c1 = assertTextIsSanitized(fillRequest2.structure, ID_L1C1);
         final ViewNode p2l1c2 = assertTextIsSanitized(fillRequest2.structure, ID_L1C2);
         final ViewNode p2l2c1 = assertTextIsSanitized(fillRequest2.structure, ID_L2C1);
@@ -160,6 +163,7 @@
         // Trigger auto-fill.
         mActivity.focusCell(1, 1);
         final FillRequest fillRequest1 = sReplier.getNextFillRequest();
+        assertThat(fillRequest1.flags).isEqualTo(0);
 
         assertTextIsSanitized(fillRequest1.structure, ID_L1C1);
         assertTextIsSanitized(fillRequest1.structure, ID_L1C2);
@@ -187,6 +191,7 @@
         // Trigger auto-fill.
         mActivity.focusCell(2, 1);
         final FillRequest fillRequest2 = sReplier.getNextFillRequest();
+        assertThat(fillRequest2.flags).isEqualTo(0);
 
         assertValue(fillRequest2.structure, ID_L1C1, "l1c1");
         assertValue(fillRequest2.structure, ID_L1C2, "l1c2");
@@ -201,6 +206,279 @@
     }
 
     @Test
+    public void testAutofill4PartitionsAutomatically() throws Exception {
+        autofill4PartitionsTest(false);
+    }
+
+    @Test
+    public void testAutofill4PartitionsManually() throws Exception {
+        autofill4PartitionsTest(true);
+    }
+
+    private void autofill4PartitionsTest(boolean manually) throws Exception {
+        final int expectedFlag = manually ? FLAG_MANUAL_REQUEST : 0;
+
+        // Set service.
+        enableService();
+
+        // 1st partition
+        // Prepare.
+        final CannedFillResponse response1 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 1"))
+                        .setField(ID_L1C1, "l1c1")
+                        .setField(ID_L1C2, "l1c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response1);
+        final FillExpectation expectation1 = mActivity.expectAutofill()
+                .onCell(1, 1, "l1c1")
+                .onCell(1, 2, "l1c2");
+
+        // Trigger auto-fill.
+        mActivity.triggerAutofill(manually, 1, 1);
+        final FillRequest fillRequest1 = sReplier.getNextFillRequest();
+        assertThat(fillRequest1.flags).isEqualTo(expectedFlag);
+
+        assertTextIsSanitized(fillRequest1.structure, ID_L1C1);
+        assertTextIsSanitized(fillRequest1.structure, ID_L1C2);
+
+        // Auto-fill it.
+        if (!manually) {
+            sUiBot.selectDataset("Partition 1");
+        }
+
+        // Check the results.
+        expectation1.assertAutoFilled();
+
+        // 2nd partition
+        // Prepare.
+        final CannedFillResponse response2 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 2"))
+                        .setField(ID_L2C1, "l2c1")
+                        .setField(ID_L2C2, "l2c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response2);
+        final FillExpectation expectation2 = mActivity.expectAutofill()
+                .onCell(2, 1, "l2c1")
+                .onCell(2, 2, "l2c2");
+
+        // Trigger auto-fill.
+        mActivity.triggerAutofill(manually, 2, 1);
+        final FillRequest fillRequest2 = sReplier.getNextFillRequest();
+        assertThat(fillRequest2.flags).isEqualTo(expectedFlag);
+
+        assertValue(fillRequest2.structure, ID_L1C1, "l1c1");
+        assertValue(fillRequest2.structure, ID_L1C2, "l1c2");
+        assertTextIsSanitized(fillRequest2.structure, ID_L2C1);
+        assertTextIsSanitized(fillRequest2.structure, ID_L2C2);
+
+        // Auto-fill it.
+        if (!manually) {
+            sUiBot.selectDataset("Partition 2");
+        }
+
+        // Check the results.
+        expectation2.assertAutoFilled();
+
+        // 3rd partition
+        // Prepare.
+        final CannedFillResponse response3 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 3"))
+                        .setField(ID_L3C1, "l3c1")
+                        .setField(ID_L3C2, "l3c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response3);
+        final FillExpectation expectation3 = mActivity.expectAutofill()
+                .onCell(3, 1, "l3c1")
+                .onCell(3, 2, "l3c2");
+
+        // Trigger auto-fill.
+        mActivity.triggerAutofill(manually, 3, 1);
+        final FillRequest fillRequest3 = sReplier.getNextFillRequest();
+        assertThat(fillRequest3.flags).isEqualTo(expectedFlag);
+
+        assertValue(fillRequest3.structure, ID_L1C1, "l1c1");
+        assertValue(fillRequest3.structure, ID_L1C2, "l1c2");
+        assertValue(fillRequest3.structure, ID_L2C1, "l2c1");
+        assertValue(fillRequest3.structure, ID_L2C2, "l2c2");
+        assertTextIsSanitized(fillRequest3.structure, ID_L3C1);
+        assertTextIsSanitized(fillRequest3.structure, ID_L3C2);
+
+        // Auto-fill it.
+        if (!manually) {
+            sUiBot.selectDataset("Partition 3");
+        }
+
+        // Check the results.
+        expectation3.assertAutoFilled();
+
+        // 4th partition
+        // Prepare.
+        final CannedFillResponse response4 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 4"))
+                        .setField(ID_L4C1, "l4c1")
+                        .setField(ID_L4C2, "l4c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response4);
+        final FillExpectation expectation4 = mActivity.expectAutofill()
+                .onCell(4, 1, "l4c1")
+                .onCell(4, 2, "l4c2");
+
+        // Trigger auto-fill.
+        mActivity.triggerAutofill(manually, 4, 1);
+        final FillRequest fillRequest4 = sReplier.getNextFillRequest();
+        assertThat(fillRequest4.flags).isEqualTo(expectedFlag);
+
+        assertValue(fillRequest4.structure, ID_L1C1, "l1c1");
+        assertValue(fillRequest4.structure, ID_L1C2, "l1c2");
+        assertValue(fillRequest4.structure, ID_L2C1, "l2c1");
+        assertValue(fillRequest4.structure, ID_L2C2, "l2c2");
+        assertValue(fillRequest4.structure, ID_L3C1, "l3c1");
+        assertValue(fillRequest4.structure, ID_L3C2, "l3c2");
+        assertTextIsSanitized(fillRequest4.structure, ID_L4C1);
+        assertTextIsSanitized(fillRequest4.structure, ID_L4C2);
+
+        // Auto-fill it.
+        if (!manually) {
+            sUiBot.selectDataset("Partition 4");
+        }
+
+        // Check the results.
+        expectation4.assertAutoFilled();
+    }
+
+    @Test
+    public void testAutofill4PartitionsMixManualAndAuto() throws Exception {
+        // Set service.
+        enableService();
+
+        // 1st partition - auto
+        // Prepare.
+        final CannedFillResponse response1 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 1"))
+                        .setField(ID_L1C1, "l1c1")
+                        .setField(ID_L1C2, "l1c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response1);
+        final FillExpectation expectation1 = mActivity.expectAutofill()
+                .onCell(1, 1, "l1c1")
+                .onCell(1, 2, "l1c2");
+
+        // Trigger auto-fill.
+        mActivity.focusCell(1, 1);
+        final FillRequest fillRequest1 = sReplier.getNextFillRequest();
+        assertThat(fillRequest1.flags).isEqualTo(0);
+
+        assertTextIsSanitized(fillRequest1.structure, ID_L1C1);
+        assertTextIsSanitized(fillRequest1.structure, ID_L1C2);
+
+        // Auto-fill it.
+        sUiBot.selectDataset("Partition 1");
+
+        // Check the results.
+        expectation1.assertAutoFilled();
+
+        // 2nd partition - manual
+        // Prepare.
+        final CannedFillResponse response2 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 2"))
+                        .setField(ID_L2C1, "l2c1")
+                        .setField(ID_L2C2, "l2c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response2);
+        final FillExpectation expectation2 = mActivity.expectAutofill()
+                .onCell(2, 1, "l2c1")
+                .onCell(2, 2, "l2c2");
+
+        // Trigger auto-fill.
+        mActivity.forceAutofill(2, 1);
+        final FillRequest fillRequest2 = sReplier.getNextFillRequest();
+        assertThat(fillRequest2.flags).isEqualTo(FLAG_MANUAL_REQUEST);
+
+        assertValue(fillRequest2.structure, ID_L1C1, "l1c1");
+        assertValue(fillRequest2.structure, ID_L1C2, "l1c2");
+        assertTextIsSanitized(fillRequest2.structure, ID_L2C1);
+        assertTextIsSanitized(fillRequest2.structure, ID_L2C2);
+
+        // Check the results.
+        expectation2.assertAutoFilled();
+
+        // 3rd partition - auto
+        // Prepare.
+        final CannedFillResponse response3 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 3"))
+                        .setField(ID_L3C1, "l3c1")
+                        .setField(ID_L3C2, "l3c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response3);
+        final FillExpectation expectation3 = mActivity.expectAutofill()
+                .onCell(3, 1, "l3c1")
+                .onCell(3, 2, "l3c2");
+
+        // Trigger auto-fill.
+        mActivity.focusCell(3, 1);
+        final FillRequest fillRequest3 = sReplier.getNextFillRequest();
+        assertThat(fillRequest3.flags).isEqualTo(0);
+
+        assertValue(fillRequest3.structure, ID_L1C1, "l1c1");
+        assertValue(fillRequest3.structure, ID_L1C2, "l1c2");
+        assertValue(fillRequest3.structure, ID_L2C1, "l2c1");
+        assertValue(fillRequest3.structure, ID_L2C2, "l2c2");
+        assertTextIsSanitized(fillRequest3.structure, ID_L3C1);
+        assertTextIsSanitized(fillRequest3.structure, ID_L3C2);
+
+        // Auto-fill it.
+        sUiBot.selectDataset("Partition 3");
+
+        // Check the results.
+        expectation3.assertAutoFilled();
+
+        // 4th partition - manual
+        // Prepare.
+        final CannedFillResponse response4 = new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("Partition 4"))
+                        .setField(ID_L4C1, "l4c1")
+                        .setField(ID_L4C2, "l4c2")
+                        .build())
+                .build();
+        sReplier.addResponse(response4);
+        final FillExpectation expectation4 = mActivity.expectAutofill()
+                .onCell(4, 1, "l4c1")
+                .onCell(4, 2, "l4c2");
+
+        // Trigger auto-fill.
+        mActivity.forceAutofill(4, 1);
+        final FillRequest fillRequest4 = sReplier.getNextFillRequest();
+        assertThat(fillRequest4.flags).isEqualTo(FLAG_MANUAL_REQUEST);
+
+        assertValue(fillRequest4.structure, ID_L1C1, "l1c1");
+        assertValue(fillRequest4.structure, ID_L1C2, "l1c2");
+        assertValue(fillRequest4.structure, ID_L2C1, "l2c1");
+        assertValue(fillRequest4.structure, ID_L2C2, "l2c2");
+        assertValue(fillRequest4.structure, ID_L3C1, "l3c1");
+        assertValue(fillRequest4.structure, ID_L3C2, "l3c2");
+        assertTextIsSanitized(fillRequest4.structure, ID_L4C1);
+        assertTextIsSanitized(fillRequest4.structure, ID_L4C2);
+
+        // Check the results.
+        expectation4.assertAutoFilled();
+    }
+
+    @Test
     public void testAutofillBundleDataIsPassedAlong() throws Exception {
         // Set service.
         enableService();
@@ -221,6 +499,7 @@
         // Trigger auto-fill on 1st partition.
         mActivity.focusCell(1, 1);
         final FillRequest fillRequest1 = sReplier.getNextFillRequest();
+        assertThat(fillRequest1.flags).isEqualTo(0);
         assertThat(fillRequest1.data).isNull();
         sUiBot.assertDatasets("l1c1");
 
@@ -241,6 +520,7 @@
         // Trigger auto-fill on 2nd partition
         mActivity.focusCell(2, 1);
         final FillRequest fillRequest2 = sReplier.getNextFillRequest();
+        assertThat(fillRequest2.flags).isEqualTo(0);
         assertWithMessage("null bundle on request 2").that(fillRequest2.data).isNotNull();
         assertWithMessage("wrong number of extras on request 2 bundle")
                 .that(fillRequest2.data.size()).isEqualTo(1);
@@ -259,6 +539,7 @@
         // Trigger auto-fill on 3rd partition
         mActivity.focusCell(3, 1);
         final FillRequest fillRequest3 = sReplier.getNextFillRequest();
+        assertThat(fillRequest3.flags).isEqualTo(0);
         assertWithMessage("null bundle on request 3").that(fillRequest2.data).isNotNull();
         assertWithMessage("wrong number of extras on request 3 bundle")
                 .that(fillRequest3.data.size()).isEqualTo(2);
@@ -283,6 +564,7 @@
         // Trigger auto-fill on 4th partition
         mActivity.focusCell(4, 1);
         final FillRequest fillRequest4 = sReplier.getNextFillRequest();
+        assertThat(fillRequest4.flags).isEqualTo(0);
         assertWithMessage("non-null bundle on request 4").that(fillRequest4.data).isNull();
 
         // Trigger save
@@ -617,6 +899,7 @@
         // Trigger auto-fill on 1st partition.
         mActivity.focusCell(1, 1);
         final FillRequest fillRequest1 = sReplier.getNextFillRequest();
+        assertThat(fillRequest1.flags).isEqualTo(0);
         final ViewNode p1l1c1 = assertTextIsSanitized(fillRequest1.structure, ID_L1C1);
         final ViewNode p1l1c2 = assertTextIsSanitized(fillRequest1.structure, ID_L1C2);
         assertWithMessage("Focus on p1l1c1").that(p1l1c1.isFocused()).isTrue();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
index 3b8c12a..fa7780a 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
@@ -31,6 +31,7 @@
 import android.app.UiAutomation;
 import android.content.res.Resources;
 import android.os.SystemClock;
+import android.service.autofill.SaveInfo;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.BySelector;
@@ -249,6 +250,10 @@
     }
 
     UiObject2 assertSaveShowing(String description, int... types) {
+        return assertSaveShowing(SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL, description, types);
+    }
+
+    UiObject2 assertSaveShowing(int negativeButtonStyle, String description, int... types) {
         final UiObject2 snackbar = waitForObject(By.res("android", RESOURCE_ID_SAVE_SNACKBAR),
                 SAVE_TIMEOUT_MS);
 
@@ -288,6 +293,12 @@
             assertWithMessage("save subtitle(%s)", description).that(saveSubTitle).isNotNull();
         }
 
+        final String negativeButtonText = (negativeButtonStyle
+                == SaveInfo.NEGATIVE_BUTTON_STYLE_REJECT) ? "NOT NOW" : "NO THANKS";
+        UiObject2 negativeButton = snackbar.findObject(By.text(negativeButtonText));
+        assertWithMessage("negative button (%s)", negativeButtonText)
+                .that(negativeButton).isNotNull();
+
         final String expectedAccessibilityTitle =
                 getString(RESOURCE_STRING_SAVE_SNACKBAR_ACCESSIBILITY_TITLE);
         assertAccessibilityTitle(snackbar, expectedAccessibilityTitle);
@@ -302,7 +313,19 @@
      * @param types expected types of save info.
      */
     void saveForAutofill(boolean yesDoIt, int... types) {
-        final UiObject2 saveSnackBar = assertSaveShowing(null, types);
+        final UiObject2 saveSnackBar = assertSaveShowing(
+                SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,null, types);
+        saveForAutofill(saveSnackBar, yesDoIt);
+    }
+
+    /**
+     * Taps an option in the save snackbar.
+     *
+     * @param yesDoIt {@code true} for 'YES', {@code false} for 'NO THANKS'.
+     * @param types expected types of save info.
+     */
+    void saveForAutofill(int negativeButtonStyle, boolean yesDoIt, int... types) {
+        final UiObject2 saveSnackBar = assertSaveShowing(negativeButtonStyle,null, types);
         saveForAutofill(saveSnackBar, yesDoIt);
     }
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
index 670832c..2102773 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
@@ -41,7 +41,6 @@
 import android.view.autofill.AutofillValue;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -161,7 +160,8 @@
     @Override
     public void dispatchProvideAutofillStructure(ViewStructure structure, int flags) {
         if (mOverrideDispatchProvideAutofillStructure) {
-            Log.d(TAG, "Overriding dispatchProvideAutofillStructure");
+            Log.d(TAG, "Overriding dispatchProvideAutofillStructure()");
+            structure.setAutofillId(getAutofillId());
             onProvideAutofillVirtualStructure(structure, flags);
         } else {
             super.dispatchProvideAutofillStructure(structure, flags);
@@ -184,7 +184,7 @@
             final ViewStructure child = mSync
                     ? structure.newChild(index)
                     : structure.asyncNewChild(index);
-            child.setAutofillId(structure, item.id);
+            child.setAutofillId(structure.getAutofillId(), item.id);
             child.setDataIsSensitive(item.sensitive);
             index++;
             final String className = item.editable ? TEXT_CLASS : LABEL_CLASS;
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index e4ca5af..ba902bf 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -296,5 +296,12 @@
     "android.telecom.cts.WiredHeadsetTest"
   ],
   bug: 26149528
+},
+{
+  desciption: "Seems to be failing on X86, flaky on arm. Root cause to be investigated",
+  names: [
+    "android.webkit.cts.WebViewClientTest#testOnRenderProcessGone"
+  ],
+  bug: 37704262
 }
 ]
diff --git a/tests/fragment/src/android/fragment/cts/FragmentAnimatorTest.java b/tests/fragment/src/android/fragment/cts/FragmentAnimatorTest.java
index dba0c07..67f90b4 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentAnimatorTest.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentAnimatorTest.java
@@ -101,9 +101,9 @@
     }
 
     // Ensure that showing and popping a Fragment uses the enter and popExit animators
-    // This tests optimized transactions
+    // This tests reordered transactions
     @Test
-    public void showAnimatorsOptimized() throws Throwable {
+    public void showAnimatorsReordered() throws Throwable {
         final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
 
         // One fragment with a view
@@ -133,9 +133,9 @@
     }
 
     // Ensure that showing and popping a Fragment uses the enter and popExit animators
-    // This tests unoptimized transactions
+    // This tests ordered transactions
     @Test
-    public void showAnimatorsUnoptimized() throws Throwable {
+    public void showAnimatorsOrdered() throws Throwable {
         final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
 
         // One fragment with a view
@@ -143,7 +143,7 @@
         fm.beginTransaction()
                 .add(R.id.fragmentContainer, fragment)
                 .hide(fragment)
-                .setAllowOptimization(false)
+                .setReorderingAllowed(false)
                 .commit();
         FragmentTestUtil.waitForExecution(mActivityRule);
 
@@ -154,7 +154,7 @@
         fm.beginTransaction()
                 .setCustomAnimations(ENTER, EXIT, POP_ENTER, POP_EXIT)
                 .show(fragment)
-                .setAllowOptimization(false)
+                .setReorderingAllowed(false)
                 .addToBackStack(null)
                 .commit();
         FragmentTestUtil.waitForExecution(mActivityRule);
diff --git a/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java b/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
index abf7fd8..ed48c82 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
@@ -884,11 +884,11 @@
             StrictFragment fragment2 = new StrictFragment();
             fm.beginTransaction()
                     .add(fragment1, "1")
-                    .setAllowOptimization(false)
+                    .setReorderingAllowed(false)
                     .commit();
             fm.beginTransaction()
                     .add(fragment2, "Hello")
-                    .setAllowOptimization(false)
+                    .setReorderingAllowed(false)
                     .commit();
             fm.executePendingTransactions();
 
diff --git a/tests/fragment/src/android/fragment/cts/FragmentOptimizationTest.java b/tests/fragment/src/android/fragment/cts/FragmentReorderingTest.java
similarity index 95%
rename from tests/fragment/src/android/fragment/cts/FragmentOptimizationTest.java
rename to tests/fragment/src/android/fragment/cts/FragmentReorderingTest.java
index bbd8d10..f1c6b9f 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentOptimizationTest.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentReorderingTest.java
@@ -32,7 +32,7 @@
 
 @MediumTest
 @RunWith(AndroidJUnit4.class)
-public class FragmentOptimizationTest {
+public class FragmentReorderingTest {
     @Rule
     public ActivityTestRule<FragmentTestActivity> mActivityRule =
             new ActivityTestRule<FragmentTestActivity>(FragmentTestActivity.class);
@@ -141,7 +141,7 @@
     // ensure that removing a view after adding it is optimized into no
     // View being created. Hide still gets notified.
     @Test
-    public void optimizeRemove() throws Throwable {
+    public void removeRedundantRemove() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         final int[] id = new int[1];
         mActivityRule.runOnUiThread(new Runnable() {
@@ -175,7 +175,7 @@
 
     // Ensure that removing and adding the same view results in no operation
     @Test
-    public void optimizeAdd() throws Throwable {
+    public void removeRedundantAdd() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         int id = mFM.beginTransaction()
                 .add(R.id.fragmentContainer, fragment1)
@@ -212,7 +212,7 @@
 
     // detaching, then attaching results in on change. Hide still functions
     @Test
-    public void optimizeAttach() throws Throwable {
+    public void removeRedundantAttach() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         int id = mFM.beginTransaction()
                 .add(R.id.fragmentContainer, fragment1)
@@ -256,7 +256,7 @@
 
     // attaching, then detaching shouldn't result in a View being created
     @Test
-    public void optimizeDetach() throws Throwable {
+    public void removeRedundantDetach() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         int id = mFM.beginTransaction()
                 .add(R.id.fragmentContainer, fragment1)
@@ -304,7 +304,7 @@
 
     // show, then hide should optimize out
     @Test
-    public void optimizeHide() throws Throwable {
+    public void removeRedundantHide() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         int id = mFM.beginTransaction()
                 .add(R.id.fragmentContainer, fragment1)
@@ -395,7 +395,7 @@
 
     // hiding and showing the same view should optimize out
     @Test
-    public void optimizeShow() throws Throwable {
+    public void removeRedundantShow() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         int id = mFM.beginTransaction()
                 .add(R.id.fragmentContainer, fragment1)
@@ -428,7 +428,7 @@
         assertEquals(0, fragment1.onHideCount);
     }
 
-    // The View order shouldn't be messed up by optimization -- a view that
+    // The View order shouldn't be messed up by reordering -- a view that
     // is optimized to not remove/add should be in its correct position after
     // the transaction completes.
     @Test
@@ -486,7 +486,7 @@
     }
 
     // A non-back-stack transaction doesn't interfere with back stack add/pop
-    // optimization.
+    // reodering/removing of redundant operations.
     @Test
     public void popNonBackStack() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
@@ -511,10 +511,10 @@
         assertEquals(0, fragment1.onCreateViewCount);
     }
 
-    // When optimization is disabled, the transaction prior to the disabled optimization
-    // transaction should all be run prior to running the non-optimized transaction.
+    // When reordering is disabled, the transaction prior to the disabled reordering
+    // transaction should all be run prior to running the ordered transaction.
     @Test
-    public void noOptimization() throws Throwable {
+    public void noReordering() throws Throwable {
         final CountCallsFragment fragment1 = new CountCallsFragment();
         final CountCallsFragment fragment2 = new CountCallsFragment();
         mActivityRule.runOnUiThread(new Runnable() {
@@ -527,14 +527,14 @@
                 mFM.beginTransaction()
                         .replace(R.id.fragmentContainer, fragment2)
                         .addToBackStack(null)
-                        .setAllowOptimization(false)
+                        .setReorderingAllowed(false)
                         .commit();
                 mFM.executePendingTransactions();
             }
         });
         FragmentTestUtil.assertChildren(mContainer, fragment2);
 
-        // No optimization, so fragment1 should have created its View
+        // No reordering, so fragment1 should have created its View
         assertEquals(1, fragment1.onCreateViewCount);
     }
 
diff --git a/tests/fragment/src/android/fragment/cts/FragmentTransactionTest.java b/tests/fragment/src/android/fragment/cts/FragmentTransactionTest.java
index 7deea1b..ea713fc 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentTransactionTest.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentTransactionTest.java
@@ -180,13 +180,13 @@
     }
 
     @Test
-    public void testPostOnCommit() throws Throwable {
+    public void testRunOnCommit() throws Throwable {
         mActivityRule.runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 final boolean[] ran = new boolean[1];
                 FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
-                fm.beginTransaction().postOnCommit(new Runnable() {
+                fm.beginTransaction().runOnCommit(new Runnable() {
                     @Override
                     public void run() {
                         ran[0] = true;
@@ -194,13 +194,13 @@
                 }).commit();
                 fm.executePendingTransactions();
 
-                assertTrue("postOnCommit runnable never ran", ran[0]);
+                assertTrue("runOnCommit runnable never ran", ran[0]);
 
                 ran[0] = false;
 
                 boolean threw = false;
                 try {
-                    fm.beginTransaction().postOnCommit(new Runnable() {
+                    fm.beginTransaction().runOnCommit(new Runnable() {
                         @Override
                         public void run() {
                             ran[0] = true;
@@ -212,9 +212,9 @@
 
                 fm.executePendingTransactions();
 
-                assertTrue("postOnCommit was allowed to be called for back stack transaction",
+                assertTrue("runOnCommit was allowed to be called for back stack transaction",
                         threw);
-                assertFalse("postOnCommit runnable for back stack transaction was run", ran[0]);
+                assertFalse("runOnCommit runnable for back stack transaction was run", ran[0]);
             }
         });
     }
diff --git a/tests/fragment/src/android/fragment/cts/FragmentTransitionTest.java b/tests/fragment/src/android/fragment/cts/FragmentTransitionTest.java
index 7421377..7a73046 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentTransitionTest.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentTransitionTest.java
@@ -54,7 +54,7 @@
 @MediumTest
 @RunWith(Parameterized.class)
 public class FragmentTransitionTest {
-    private final boolean mOptimize;
+    private final boolean mReordered;
 
     @Parameterized.Parameters
     public static Object[] data() {
@@ -69,8 +69,8 @@
 
     private FragmentManager mFragmentManager;
 
-    public FragmentTransitionTest(final boolean optimize) {
-        mOptimize = optimize;
+    public FragmentTransitionTest(final boolean reordered) {
+        mReordered = reordered;
     }
 
     @Before
@@ -90,7 +90,7 @@
 
         // exit transition
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .remove(fragment)
                 .addToBackStack(null)
                 .commit();
@@ -164,7 +164,7 @@
             @Override
             public void run() {
                 mFragmentManager.beginTransaction()
-                        .setAllowOptimization(mOptimize)
+                        .setReorderingAllowed(mReordered)
                         .replace(R.id.fragmentContainer, fragment2)
                         .replace(R.id.fragmentContainer, fragment1)
                         .replace(R.id.fragmentContainer, fragment2)
@@ -175,7 +175,10 @@
         FragmentTestUtil.waitForExecution(mActivityRule);
 
         // should be a normal transition from fragment1 to fragment2
+        fragment1.waitForTransition();
         fragment2.waitForTransition();
+        FragmentTestUtil.waitForExecution(mActivityRule);
+
         final View endBlue = findBlue();
         final View endGreen = findGreen();
         verifyAndClearTransition(fragment1.exitTransition, null, startBlue, startGreen);
@@ -187,6 +190,9 @@
         FragmentTestUtil.popBackStackImmediate(mActivityRule);
 
         fragment1.waitForTransition();
+        fragment2.waitForTransition();
+        FragmentTestUtil.waitForExecution(mActivityRule);
+
         final View popBlue = findBlue();
         final View popGreen = findGreen();
         verifyAndClearTransition(fragment1.reenterTransition, null, popBlue, popGreen);
@@ -204,7 +210,7 @@
         TransitionFragment fragment2 = new TransitionFragment();
         fragment2.setLayoutId(R.layout.scene1);
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .add(R.id.fragmentContainer1, fragment1)
                 .add(R.id.fragmentContainer2, fragment2)
                 .addToBackStack(null)
@@ -320,7 +326,7 @@
         mFragmentManager.beginTransaction()
                 .addSharedElement(startBlue, "blueSquare")
                 .replace(R.id.fragmentContainer, fragment2)
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .addToBackStack(null)
                 .commit();
         FragmentTestUtil.waitForExecution(mActivityRule);
@@ -387,7 +393,7 @@
         mFragmentManager.beginTransaction()
                 .addSharedElement(startBlue, "blueSquare")
                 .replace(R.id.fragmentContainer, fragment2)
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .addToBackStack(null)
                 .commit();
         FragmentTestUtil.waitForExecution(mActivityRule);
@@ -512,7 +518,7 @@
         final View startGreen = findGreen();
 
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .add(R.id.fragmentContainer, fragment2)
                 .hide(fragment1)
                 .addToBackStack(null)
@@ -563,7 +569,7 @@
         final View startGreen = findGreen();
 
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .add(R.id.fragmentContainer, fragment2)
                 .detach(fragment1)
                 .addToBackStack(null)
@@ -610,7 +616,7 @@
         mFragmentManager.beginTransaction()
                 .addSharedElement(startBlue, "fooSquare")
                 .replace(R.id.fragmentContainer, fragment2)
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .addToBackStack(null)
                 .commit();
         FragmentTestUtil.waitForExecution(mActivityRule);
@@ -621,7 +627,7 @@
         final View endBlue = findBlue();
         final View endGreen = findGreen();
 
-        if (mOptimize) {
+        if (mReordered) {
             verifyAndClearTransition(fragment1.exitTransition, null, startGreen, startBlue);
         } else {
             verifyAndClearTransition(fragment1.exitTransition, startBlueBounds, startGreen);
@@ -661,14 +667,14 @@
     // Test that invisible fragment views don't participate in transitions
     @Test
     public void invisibleNoTransitions() throws Throwable {
-        if (!mOptimize) {
-            return; // only optimized transitions can avoid interaction
+        if (!mReordered) {
+            return; // only reordered transitions can avoid interaction
         }
         // enter transition
         TransitionFragment fragment = new InvisibleFragment();
         fragment.setLayoutId(R.layout.scene1);
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .add(R.id.fragmentContainer, fragment)
                 .addToBackStack(null)
                 .commit();
@@ -678,7 +684,7 @@
 
         // exit transition
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .remove(fragment)
                 .addToBackStack(null)
                 .commit();
@@ -710,7 +716,7 @@
         fragment2.setLayoutId(R.layout.scene2);
 
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .addSharedElement(startBlue, "blueSquare")
                 .replace(R.id.fragmentContainer, fragment2)
                 .addToBackStack(null)
@@ -735,7 +741,7 @@
             public void run() {
                 mFragmentManager.popBackStack();
                 mFragmentManager.beginTransaction()
-                        .setAllowOptimization(mOptimize)
+                        .setReorderingAllowed(mReordered)
                         .replace(R.id.fragmentContainer, fragment3)
                         .addToBackStack(null)
                         .commit();
@@ -746,8 +752,8 @@
         FragmentTestUtil.executePendingTransactions(mActivityRule);
 
         fragment2.waitForTransition();
-        // It does not transition properly for unoptimized transactions, though.
-        if (mOptimize) {
+        // It does not transition properly for ordered transactions, though.
+        if (mReordered) {
             verifyAndClearTransition(fragment2.returnTransition, null, midGreen, midBlue);
             final View endGreen = findGreen();
             final View endBlue = findBlue();
@@ -758,7 +764,7 @@
         } else {
             // fragment3 doesn't get a transition since it conflicts with the pop transition
             verifyNoOtherTransitions(fragment3);
-            // Everything else is just doing its best. Unoptimized transactions can't handle
+            // Everything else is just doing its best. Reordered transactions can't handle
             // multiple transitions acting together except for popping multiple together.
         }
     }
@@ -767,7 +773,7 @@
         TransitionFragment fragment1 = new TransitionFragment();
         fragment1.setLayoutId(R.layout.scene1);
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .add(R.id.fragmentContainer, fragment1)
                 .addToBackStack(null)
                 .commit();
@@ -834,7 +840,7 @@
         final Rect startBlueRect = getBoundsOnScreen(startBlue);
 
         mFragmentManager.beginTransaction()
-                .setAllowOptimization(mOptimize)
+                .setReorderingAllowed(mReordered)
                 .addSharedElement(startBlue, sharedElementName)
                 .replace(R.id.fragmentContainer, to)
                 .addToBackStack(null)
@@ -886,13 +892,13 @@
 
         mActivityRule.runOnUiThread(() -> {
             mFragmentManager.beginTransaction()
-                    .setAllowOptimization(mOptimize)
+                    .setReorderingAllowed(mReordered)
                     .addSharedElement(fromShared1, "blueSquare")
                     .replace(R.id.fragmentContainer1, to1)
                     .addToBackStack(null)
                     .commit();
             mFragmentManager.beginTransaction()
-                    .setAllowOptimization(mOptimize)
+                    .setReorderingAllowed(mReordered)
                     .addSharedElement(fromShared2, sharedElementName)
                     .replace(R.id.fragmentContainer2, to2)
                     .addToBackStack(null)
diff --git a/tests/fragment/src/android/fragment/cts/FragmentViewTests.java b/tests/fragment/src/android/fragment/cts/FragmentViewTests.java
index e9c80e0..f0d5947 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentViewTests.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentViewTests.java
@@ -23,9 +23,7 @@
 
 import android.app.Fragment;
 import android.app.FragmentManager;
-import android.app.Instrumentation;
 import android.os.Bundle;
-import android.os.Debug;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.MediumTest;
 import android.support.test.rule.ActivityTestRule;
@@ -34,7 +32,6 @@
 import android.view.View;
 import android.view.ViewGroup;
 
-import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -930,11 +927,11 @@
         FragmentTestUtil.assertChildren(container, fragment3);
     }
 
-    // Ensure that non-optimized transactions are executed individually rather than together.
+    // Ensure that ordered transactions are executed individually rather than together.
     // This forces references from one fragment to another that should be executed earlier
     // to work.
     @Test
-    public void nonOptimizeTogether() throws Throwable {
+    public void orderedOperationsTogether() throws Throwable {
         FragmentTestUtil.setContentView(mActivityRule, R.layout.simple_container);
         ViewGroup container = (ViewGroup)
                 mActivityRule.getActivity().findViewById(R.id.fragmentContainer);
@@ -950,12 +947,12 @@
             public void run() {
                 fm.beginTransaction()
                         .add(R.id.fragmentContainer, fragment1)
-                        .setAllowOptimization(false)
+                        .setReorderingAllowed(false)
                         .addToBackStack(null)
                         .commit();
                 fm.beginTransaction()
                         .add(R.id.squareContainer, fragment2)
-                        .setAllowOptimization(false)
+                        .setReorderingAllowed(false)
                         .addToBackStack(null)
                         .commit();
                 fm.executePendingTransactions();
@@ -992,7 +989,7 @@
         FragmentTestUtil.assertChildren(innerContainer, fragment2);
     }
 
-    // Popping the backstack with non-optimized fragments should execute the operations together.
+    // Popping the backstack with ordered fragments should execute the operations together.
     // When a non-backstack fragment will be raised, it should not be destroyed.
     @Test
     public void popToNonBackStackFragment() throws Throwable {
diff --git a/tests/jdwp/AndroidTest.xml b/tests/jdwp/AndroidTest.xml
index 3cd1be2..9bab5b1 100644
--- a/tests/jdwp/AndroidTest.xml
+++ b/tests/jdwp/AndroidTest.xml
@@ -30,10 +30,11 @@
         <option name="classpath" value="/data/local/tmp/ctsjdwp/CtsJdwpTestCases.jar" />
         <option name="dalvik-arg" value="-Xcompiler-option" />
         <option name="dalvik-arg" value="--debuggable" />
+        <option name="dalvik-arg" value="-Xusejit:true" />
         <option name="dalvik-arg" value="-Djpda.settings.verbose=false" />
         <option name="dalvik-arg" value="-Djpda.settings.timeout=10000" />
         <option name="dalvik-arg" value="-Djpda.settings.waitingTime=10000" />
-        <option name="dalvik-arg" value="-Djpda.settings.debuggeeJavaPath='dalvikvm|#ABI#| -XXlib:libart.so -Xcompiler-option --debuggable'" />
+        <option name="dalvik-arg" value="-Djpda.settings.debuggeeJavaPath='dalvikvm|#ABI#| -XXlib:libart.so -Xcompiler-option --debuggable -Xusejit:true'" />
         <option name="known-failures" value="/expectations/jdwp-known-failures.txt" />
         <option name="runtime-hint" value="16m" />
 
diff --git a/tests/sensor/jni/SensorTest.cpp b/tests/sensor/jni/SensorTest.cpp
index eb2bfe8..38964aa 100644
--- a/tests/sensor/jni/SensorTest.cpp
+++ b/tests/sensor/jni/SensorTest.cpp
@@ -163,16 +163,15 @@
                 .width = static_cast<uint32_t>(size),
                 .height = 1,
                 .layers = 1,
-                .usage0 = AHARDWAREBUFFER_USAGE0_SENSOR_DIRECT_DATA
-                        | AHARDWAREBUFFER_USAGE0_CPU_READ_OFTEN,
-                .usage1 = 0,
+                .usage = AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA
+                         | AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
                 .format = AHARDWAREBUFFER_FORMAT_BLOB
             };
 
             // allocate
             if (AHardwareBuffer_allocate(&desc, &mHardwareBuffer) == 0) {
                 // lock
-                if (AHardwareBuffer_lock(mHardwareBuffer, AHARDWAREBUFFER_USAGE0_CPU_READ,
+                if (AHardwareBuffer_lock(mHardwareBuffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY,
                                          -1, nullptr, reinterpret_cast<void **>(&mBuffer)) == 0) {
                     if (mBuffer != nullptr) {
                         mSize = size;
diff --git a/tests/sensor/jni/android_hardware_cts_SensorDirectReportTest.cpp b/tests/sensor/jni/android_hardware_cts_SensorDirectReportTest.cpp
index 2616ff9..f189cf9 100644
--- a/tests/sensor/jni/android_hardware_cts_SensorDirectReportTest.cpp
+++ b/tests/sensor/jni/android_hardware_cts_SensorDirectReportTest.cpp
@@ -43,7 +43,7 @@
     void *address;
     int32_t fence = -1;
     jboolean ret = false;
-    if (AHardwareBuffer_lock(hardwareBuffer, AHARDWAREBUFFER_USAGE0_CPU_READ,
+    if (AHardwareBuffer_lock(hardwareBuffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY,
                              fence, nullptr, &address) == 0) {
         if (address != nullptr) {
             env->SetByteArrayRegion(
diff --git a/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java b/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java
index 03e088b..6c2462f 100644
--- a/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java
@@ -332,8 +332,8 @@
 
         hardwareBuffer = HardwareBuffer.create(
                 SHARED_MEMORY_SIZE, 1 /* height */, HardwareBuffer.BLOB, 1 /* layer */,
-                HardwareBuffer.USAGE0_CPU_READ_OFTEN | HardwareBuffer.USAGE0_GPU_DATA_BUFFER
-                    | HardwareBuffer.USAGE0_SENSOR_DIRECT_DATA);
+                HardwareBuffer.USAGE_CPU_READ_OFTEN | HardwareBuffer.USAGE_GPU_DATA_BUFFER
+                    | HardwareBuffer.USAGE_SENSOR_DIRECT_DATA);
         return hardwareBuffer;
     }
 
diff --git a/tests/tests/app/AndroidManifest.xml b/tests/tests/app/AndroidManifest.xml
index be903e3..707b22b 100644
--- a/tests/tests/app/AndroidManifest.xml
+++ b/tests/tests/app/AndroidManifest.xml
@@ -23,6 +23,11 @@
 
         <activity android:name=".ApplyOverrideConfigurationActivity"
                   android:configChanges="orientation|screenSize" />
+
+        <activity android:name=".PictureInPictureActivity"
+                  android:resizeableActivity="false"
+                  android:supportsPictureInPicture="true"
+                  android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout" />
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/app/src/android/app/cts/PictureInPictureActionsTest.java b/tests/tests/app/src/android/app/cts/PictureInPictureActionsTest.java
index d08b29f..da02a81 100644
--- a/tests/tests/app/src/android/app/cts/PictureInPictureActionsTest.java
+++ b/tests/tests/app/src/android/app/cts/PictureInPictureActionsTest.java
@@ -15,12 +15,16 @@
  */
 package android.app.cts;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
-import android.app.ActivityManager;
+import android.app.Activity;
+import android.app.Instrumentation;
 import android.support.test.filters.SmallTest;
+import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
 
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -32,9 +36,20 @@
 @RunWith(AndroidJUnit4.class)
 public class PictureInPictureActionsTest {
 
+    private Activity mActivity;
+
+    @Rule
+    public ActivityTestRule<PictureInPictureActivity> mActivityRule =
+            new ActivityTestRule<>(PictureInPictureActivity.class);
+
+    @Before
+    public void setup() {
+        mActivity = mActivityRule.getActivity();
+    }
+
     @Test
     public void testNumPictureInPictureActions() throws Exception {
-        // Currently enforce that there are a max of three actions
-        assertEquals(ActivityManager.getMaxNumPictureInPictureActions(), 3);
+        // Currently enforce that there are at least 3 actions
+        assertTrue(mActivity.getMaxNumPictureInPictureActions() >= 3);
     }
 }
diff --git a/tests/tests/app/src/android/app/cts/PictureInPictureActivity.java b/tests/tests/app/src/android/app/cts/PictureInPictureActivity.java
new file mode 100644
index 0000000..75245b7
--- /dev/null
+++ b/tests/tests/app/src/android/app/cts/PictureInPictureActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package android.app.cts;
+
+import android.app.Activity;
+
+public class PictureInPictureActivity extends Activity {
+    // Empty
+}
diff --git a/tests/tests/app/src/android/app/cts/PictureInPictureParamsBuilderTest.java b/tests/tests/app/src/android/app/cts/PictureInPictureParamsBuilderTest.java
new file mode 100644
index 0000000..639c4d1
--- /dev/null
+++ b/tests/tests/app/src/android/app/cts/PictureInPictureParamsBuilderTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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.app.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import android.app.PictureInPictureParams;
+import android.app.PictureInPictureParams.Builder;
+import android.graphics.Rect;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.util.Rational;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+
+/**
+ * Tests the {@link PictureInPictureParams} builder.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class PictureInPictureParamsBuilderTest {
+
+    @Test
+    public void testBuildParams() throws Exception {
+        // Set the params
+        Builder builder = new Builder()
+                .setAspectRatio(new Rational(1, 2))
+                .setActions(new ArrayList<>())
+                .setSourceRectHint(new Rect(0, 0, 100, 100));
+
+        PictureInPictureParams params = builder.build();
+        assertTrue(Float.compare(0.5f, params.getAspectRatio()) == 0);
+        assertTrue(params.getActions().isEmpty());
+        assertEquals(new Rect(0, 0, 100, 100), params.getSourceRectHint());
+
+        // Reset the params
+        builder.setAspectRatio(null)
+                .setActions(null)
+                .setSourceRectHint(null);
+        params = builder.build();
+
+        assertTrue(Float.compare(0f, params.getAspectRatio()) == 0);
+        assertNull(params.getActions());
+        assertNull(params.getSourceRectHint());
+    }
+}
diff --git a/tests/tests/content/res/values/attrs.xml b/tests/tests/content/res/values/attrs.xml
index 12b731b..236ee6c 100644
--- a/tests/tests/content/res/values/attrs.xml
+++ b/tests/tests/content/res/values/attrs.xml
@@ -49,6 +49,7 @@
     <attr name="type15" format="reference"/>
     <attr name="type16" format="string"/>
     <attr name="type17" format="reference|color"/>
+    <attr name="type18" format="reference|string"/>
     <attr name="typeEmpty" format="reference"/>
     <attr name="typeUndefined" format="reference"/>
     <declare-styleable name="style1">
@@ -69,6 +70,7 @@
         <attr name="type15"/>
         <attr name="type16"/>
         <attr name="type17"/>
+        <attr name="type18"/>
         <attr name="typeEmpty"/>
         <attr name="typeUndefined"/>
     </declare-styleable>
diff --git a/tests/tests/content/res/values/styles.xml b/tests/tests/content/res/values/styles.xml
index d1c30d7..b4db3ac 100644
--- a/tests/tests/content/res/values/styles.xml
+++ b/tests/tests/content/res/values/styles.xml
@@ -34,6 +34,7 @@
         <item name="type15">@array/difficultyLevel</item>
         <item name="type16">Typed Value!</item>
         <item name="type17">@color/testcolor_orientation</item>
+        <item name="type18">@font/samplefont</item>
         <item name="typeEmpty">@empty</item>
         <item name="typeUndefined">@null</item>
     </style>
@@ -181,4 +182,8 @@
     <style name="Theme_OrientationDependent">
         <item name="themeDimension">999px</item>
     </style>
+
+    <style name="Theme_InlineString">
+        <item name="testString">"This is a string"</item>
+    </style>
 </resources>
diff --git a/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java b/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
index 7613e72..e038117f 100644
--- a/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
+++ b/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
@@ -145,17 +145,17 @@
         Uri contentUri8 = Uri.parse("content://ctstest/testtable2/3");
 
         ClipData clipData = ClipData.newPlainText("TextLabel", "Text");
-        clipData.addItem(new Item("More Text"), contentResolver);
-        clipData.addItem(new Item(intent), contentResolver);
-        clipData.addItem(new Item(uri), contentResolver);
-        clipData.addItem(new Item(contentUri1), contentResolver);
-        clipData.addItem(new Item(contentUri2), contentResolver);
-        clipData.addItem(new Item(contentUri3), contentResolver);
-        clipData.addItem(new Item(contentUri4), contentResolver);
-        clipData.addItem(new Item(contentUri5), contentResolver);
-        clipData.addItem(new Item(contentUri6), contentResolver);
-        clipData.addItem(new Item(contentUri7), contentResolver);
-        clipData.addItem(new Item(contentUri8), contentResolver);
+        clipData.addItem(contentResolver, new Item("More Text"));
+        clipData.addItem(contentResolver, new Item(intent));
+        clipData.addItem(contentResolver, new Item(uri));
+        clipData.addItem(contentResolver, new Item(contentUri1));
+        clipData.addItem(contentResolver, new Item(contentUri2));
+        clipData.addItem(contentResolver, new Item(contentUri3));
+        clipData.addItem(contentResolver, new Item(contentUri4));
+        clipData.addItem(contentResolver, new Item(contentUri5));
+        clipData.addItem(contentResolver, new Item(contentUri6));
+        clipData.addItem(contentResolver, new Item(contentUri7));
+        clipData.addItem(contentResolver, new Item(contentUri8));
 
         assertClipData(clipData, "TextLabel",
                 new String[] {
diff --git a/tests/tests/content/src/android/content/cts/ContentResolverTest.java b/tests/tests/content/src/android/content/cts/ContentResolverTest.java
index e5e8fe4..d1c03d2 100644
--- a/tests/tests/content/src/android/content/cts/ContentResolverTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentResolverTest.java
@@ -427,7 +427,7 @@
         Bundle queryArgs = new Bundle();
         queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 10);
         queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 3);
-        queryArgs.putInt(TestPagingContentProvider.RECORDSET_SIZE, 100);
+        queryArgs.putInt(TestPagingContentProvider.RECORD_COUNT, 100);
 
         mCursor = mContentResolver.query(
                 TestPagingContentProvider.PAGED_DATA_URI, null, queryArgs, null);
@@ -436,8 +436,8 @@
         extras = extras != null ? extras : Bundle.EMPTY;
 
         assertEquals(3, mCursor.getCount());
-        assertTrue(extras.containsKey(ContentResolver.EXTRA_TOTAL_SIZE));
-        assertEquals(100, extras.getInt(ContentResolver.EXTRA_TOTAL_SIZE));
+        assertTrue(extras.containsKey(ContentResolver.EXTRA_TOTAL_COUNT));
+        assertEquals(100, extras.getInt(ContentResolver.EXTRA_TOTAL_COUNT));
 
         String[] honoredArgs = extras.getStringArray(ContentResolver.EXTRA_HONORED_ARGS);
         assertNotNull(honoredArgs);
diff --git a/tests/tests/content/src/android/content/cts/TestPagingContentProvider.java b/tests/tests/content/src/android/content/cts/TestPagingContentProvider.java
index 42e0019..6e38809 100644
--- a/tests/tests/content/src/android/content/cts/TestPagingContentProvider.java
+++ b/tests/tests/content/src/android/content/cts/TestPagingContentProvider.java
@@ -42,7 +42,7 @@
     static final Uri UNPAGED_DATA_URI = Uri.parse("content://" + AUTHORITY + "/un-paged/");
 
     /** Required queryArgument specifying corpus size. */
-    static final String RECORDSET_SIZE = "test-recordset-size";
+    static final String RECORD_COUNT = "test-record-count";
     static final String COLUMN_POS = "ColumnPos";
     static final String COLUMN_A = "ColumnA";
     static final String COLUMN_B = "ColumnB";
@@ -69,26 +69,28 @@
 
         queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
 
-        int recordsetSize = queryArgs.getInt(RECORDSET_SIZE, Integer.MIN_VALUE);
-        if (recordsetSize == Integer.MIN_VALUE) {
+        int recordCount = queryArgs.getInt(RECORD_COUNT, Integer.MIN_VALUE);
+        if (recordCount == Integer.MIN_VALUE) {
             throw new RuntimeException("Recordset size must be specified.");
         }
 
-        if (recordsetSize < 0) {
+        if (recordCount < 0) {
             throw new RuntimeException("Recordset size must be >= 0");
         }
 
         Cursor cursor = null;
         if (PAGED_DATA_URI.equals(uri)) {
-            cursor = buildPagedResults(queryArgs, recordsetSize);
+            cursor = buildPagedResults(queryArgs, recordCount);
         } else if (UNPAGED_DATA_URI.equals(uri)) {
-            cursor = buildUnpagedResults(recordsetSize);
+            cursor = buildUnpagedResults(recordCount);
         }
 
         if (cursor == null) {
             throw new IllegalArgumentException("Unsupported URI: " + uri);
         }
 
+        cursor.setNotificationUri(getContext().getContentResolver(), uri);
+
         Log.v(TAG, "Final cursor contains " + cursor.getCount() + " rows.");
         return cursor;
     }
@@ -118,7 +120,7 @@
             ContentResolver.QUERY_ARG_OFFSET,
             ContentResolver.QUERY_ARG_LIMIT
         });
-        extras.putInt(ContentResolver.EXTRA_TOTAL_SIZE, recordsetSize);
+        extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
         return c;
     }
 
diff --git a/tests/tests/content/src/android/content/res/cts/Resources_ThemeTest.java b/tests/tests/content/src/android/content/res/cts/Resources_ThemeTest.java
index b7a621f..24c61ae 100644
--- a/tests/tests/content/src/android/content/res/cts/Resources_ThemeTest.java
+++ b/tests/tests/content/src/android/content/res/cts/Resources_ThemeTest.java
@@ -83,6 +83,16 @@
     }
 
     @SmallTest
+    public void testObtainStyledAttributesWithInlineStringInTheme() {
+        mResTheme.applyStyle(R.style.Theme_InlineString, false);
+        final TypedArray ta = mResTheme.obtainStyledAttributes(new int[] { R.attr.testString });
+        assertNotNull(ta);
+        assertEquals(1, ta.length());
+        assertEquals(TypedValue.TYPE_STRING, ta.getType(0));
+        assertEquals("This is a string", ta.getString(0));
+    }
+
+    @SmallTest
     public void testResolveAttribute() {
         final TypedValue value = new TypedValue();
         getContext().getResources().getValue(R.raw.testmp3, value, true);
diff --git a/tests/tests/content/src/android/content/res/cts/TypedArrayTest.java b/tests/tests/content/src/android/content/res/cts/TypedArrayTest.java
index b31b446..5739554 100644
--- a/tests/tests/content/src/android/content/res/cts/TypedArrayTest.java
+++ b/tests/tests/content/src/android/content/res/cts/TypedArrayTest.java
@@ -25,6 +25,7 @@
 import android.content.pm.ActivityInfo;
 import android.content.res.TypedArray;
 import android.content.res.XmlResourceParser;
+import android.graphics.Typeface;
 import android.test.AndroidTestCase;
 import android.util.AttributeSet;
 import android.util.TypedValue;
@@ -48,9 +49,9 @@
     private static final String EXPECTED_TEXT = "TypedArray Test!";
     private static final String[] EXPECTED_TEXT_ARRAY = {"Easy", "Medium", "Hard"};
     private static final TypedValue DEF_VALUE = new TypedValue();
-    private static final int EXPECTED_INDEX_COUNT = 17;
+    private static final int EXPECTED_INDEX_COUNT = 18;
     private static final String EXPTECTED_POS_DESCRIP = "<internal>";
-    private static final int EXPECTED_LENGTH = 19;
+    private static final int EXPECTED_LENGTH = 20;
     private static final String EXPECTED_NON_RESOURCE_STRING = "testNonResourcesString";
     private static final String XML_BEGIN = "resources";
     private static final int EXPECTED_INT_ATT = 86400;
@@ -62,7 +63,8 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        mTypedArray = getContext().getTheme().obtainStyledAttributes(R.style.Whatever, R.styleable.style1);
+        mTypedArray = getContext().getTheme()
+                .obtainStyledAttributes(R.style.Whatever, R.styleable.style1);
     }
 
     @Override
@@ -167,6 +169,9 @@
             actual_indices[idx] = attr_index;
         }
 
+        final Typeface font = t.getFont(R.styleable.style1_type18);
+        assertEquals(mContext.getResources().getFont(R.font.samplefont), font);
+
         // NOTE: order does not matter here.
         // R.styleable.style1_typeEmpty and R.styleable.style1_typeUndefined are not
         // expected because TYPE_NULL values do not get included in the index list.
@@ -187,7 +192,8 @@
                 R.styleable.style1_type14,
                 R.styleable.style1_type15,
                 R.styleable.style1_type16,
-                R.styleable.style1_type17);
+                R.styleable.style1_type17,
+                R.styleable.style1_type18);
     }
 
     public void testPeekValue() {
diff --git a/tests/tests/graphics/AndroidManifest.xml b/tests/tests/graphics/AndroidManifest.xml
index b154154..ece0908 100644
--- a/tests/tests/graphics/AndroidManifest.xml
+++ b/tests/tests/graphics/AndroidManifest.xml
@@ -32,7 +32,8 @@
         </activity>
 
         <activity android:name="android.graphics.drawable.cts.DrawableStubActivity"
-                  android:theme="@style/WhiteBackgroundNoWindowAnimation"/>
+                  android:theme="@style/WhiteBackgroundNoWindowAnimation"
+                  android:screenOrientation="locked"/>
 
         <activity android:name="android.graphics.fonts.cts.MockActivity"/>
     </application>
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_2_golden_pressed.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_2_pressed_golden.png
similarity index 100%
rename from tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_2_golden_pressed.png
rename to tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_2_pressed_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_golden_pressed.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_golden_pressed.png
deleted file mode 100644
index c5d06f6..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_golden_pressed.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_2_golden_pressed.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_pressed_golden.png
similarity index 100%
copy from tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_2_golden_pressed.png
copy to tests/tests/graphics/res/drawable-nodpi/vector_icon_state_list_pressed_golden.png
Binary files differ
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapColorSpaceTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapColorSpaceTest.java
index a296659..e255f8e 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapColorSpaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapColorSpaceTest.java
@@ -122,6 +122,18 @@
         assertSame(sRGB, cs);
     }
 
+    @Test
+    public void createDefaultColorSpace() {
+        ColorSpace sRGB = ColorSpace.get(ColorSpace.Named.SRGB);
+        Bitmap.Config[] configs = new Bitmap.Config[] {
+                Bitmap.Config.ALPHA_8, Bitmap.Config.RGB_565, Bitmap.Config.ARGB_8888
+        };
+        for (Bitmap.Config config : configs) {
+            Bitmap bitmap = Bitmap.createBitmap(32, 32, config, true);
+            assertSame(sRGB, bitmap.getColorSpace());
+        }
+    }
+
     @Test(expected = IllegalArgumentException.class)
     public void createWithoutColorSpace() {
         Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888, true, null);
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
index 4156ed5..0d43322 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
@@ -129,7 +129,7 @@
     @Test
     public void testCopyConfigs() {
         Config[] supportedConfigs = new Config[] {
-                Config.ALPHA_8, Config.RGB_565, Config.ARGB_8888
+                Config.ALPHA_8, Config.RGB_565, Config.ARGB_8888, Config.RGBA_F16,
         };
         for (Config src : supportedConfigs) {
             for (Config dst : supportedConfigs) {
diff --git a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
index a113afa..52db21f 100644
--- a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
@@ -51,6 +51,8 @@
 import android.text.SpannedString;
 import android.util.DisplayMetrics;
 
+import com.android.compatibility.common.util.ColorUtils;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.Vector;
@@ -68,14 +70,6 @@
     private final static int BITMAP_HEIGHT = 28;
     private final static int FLOAT_ARRAY_LEN = 9;
 
-    private final Rect mRect = new Rect(0, 0, 10, 31);
-    private final Rect mInRect = new Rect(0, 0, 20, 10);
-    private final Rect mOutRect = new Rect(10, 31, 11, 32);
-
-    private final RectF mRectF = new RectF(0, 0, 10, 31);
-    private final RectF mInRectF = new RectF(0, 0, 20, 10);
-    private final RectF mOutRectF = new RectF(10, 31, 11, 32);
-
     // used for save related methods tests
     private final float[] values1 = {
             1, 2, 3, 4, 5, 6, 7, 8, 9
@@ -1035,7 +1029,7 @@
     }
 
     @Test
-    public void testClipRect4F() {
+    public void testClipRect4I() {
         // intersect with clip larger than canvas
         assertTrue(mCanvas.clipRect(0, 0, 10, 31, Op.INTERSECT));
         // intersect with clip outside of canvas bounds
@@ -1051,6 +1045,58 @@
     }
 
     @Test
+    public void testClipRect4F() {
+        // intersect with clip larger than canvas
+        assertTrue(mCanvas.clipRect(0f, 0f, 10f, 31f, Op.INTERSECT));
+        // intersect with clip outside of canvas bounds
+        assertFalse(mCanvas.clipRect(10f, 31f, 11f, 32f, Op.INTERSECT));
+        // replace with clip that is larger than canvas
+        assertTrue(mCanvas.clipRect(0f, 0f, 10f, 31f, Op.REPLACE));
+        // intersect with clip that covers top portion of canvas
+        assertTrue(mCanvas.clipRect(0f, 0f, 20f, 10f, Op.INTERSECT));
+        // intersect with clip that covers bottom portion of canvas
+        assertFalse(mCanvas.clipRect(0f, 10f, 20f, 32f, Op.INTERSECT));
+        // ensure that difference doesn't widen already closed clip
+        assertFalse(mCanvas.clipRect(0f, 0f, 10f, 31f, Op.DIFFERENCE));
+    }
+
+    @Test
+    public void testClipOutRectF() {
+        // remove center, clip not empty
+        assertTrue(mCanvas.clipOutRect(new RectF(1, 1, 9, 27)));
+        // replace clip, verify difference doesn't widen
+        assertFalse(mCanvas.clipRect(new RectF(0, 0, 0, 0), Op.REPLACE));
+        assertFalse(mCanvas.clipOutRect(new RectF(0, 0, 100, 100)));
+    }
+
+    @Test
+    public void testClipOutRect() {
+        // remove center, clip not empty
+        assertTrue(mCanvas.clipOutRect(new Rect(1, 1, 9, 27)));
+        // replace clip, verify difference doesn't widen
+        assertFalse(mCanvas.clipRect(new Rect(0, 0, 0, 0), Op.REPLACE));
+        assertFalse(mCanvas.clipOutRect(new Rect(0, 0, 100, 100)));
+    }
+
+    @Test
+    public void testClipOutRect4I() {
+        // remove center, clip not empty
+        assertTrue(mCanvas.clipOutRect(1, 1, 9, 27));
+        // replace clip, verify difference doesn't widen
+        assertFalse(mCanvas.clipRect(0, 0, 0, 0, Op.REPLACE));
+        assertFalse(mCanvas.clipOutRect(0, 0, 100, 100));
+    }
+
+    @Test
+    public void testClipOutRect4F() {
+        // remove center, clip not empty
+        assertTrue(mCanvas.clipOutRect(1f, 1f, 9f, 27f));
+        // replace clip, verify difference doesn't widen
+        assertFalse(mCanvas.clipRect(0f, 0f, 0f, 0f, Op.REPLACE));
+        assertFalse(mCanvas.clipOutRect(0f, 0f, 100f, 100f));
+    }
+
+    @Test
     public void testIntersectClipRectF() {
         // intersect with clip larger than canvas
         assertTrue(mCanvas.clipRect(new RectF(0, 0, 10, 31)));
@@ -1075,14 +1121,9 @@
     }
 
     @Test
-    public void testClipRect7() {
-        assertTrue(mCanvas.clipRect(0, 0, 10, 31));
-    }
-
-    @Test
     public void testClipPath1() {
         final Path p = new Path();
-        p.addRect(mRectF, Direction.CCW);
+        p.addRect(new RectF(0, 0, 10, 31), Direction.CCW);
         assertTrue(mCanvas.clipPath(p));
     }
 
@@ -1135,14 +1176,14 @@
 
     @Test
     public void testQuickReject1() {
-        assertFalse(mCanvas.quickReject(mRectF, EdgeType.AA));
-        assertFalse(mCanvas.quickReject(mRectF, EdgeType.BW));
+        assertFalse(mCanvas.quickReject(new RectF(0, 0, 10, 31), EdgeType.AA));
+        assertFalse(mCanvas.quickReject(new RectF(0, 0, 10, 31), EdgeType.BW));
     }
 
     @Test
     public void testQuickReject2() {
         final Path p = new Path();
-        p.addRect(mRectF, Direction.CCW);
+        p.addRect(new RectF(0, 0, 10, 31), Direction.CCW);
 
         assertFalse(mCanvas.quickReject(p, EdgeType.AA));
         assertFalse(mCanvas.quickReject(p, EdgeType.BW));
@@ -2179,4 +2220,18 @@
             Assert.fail();
         }
     }
+
+    @Test
+    public void testShadowLayer_paintColorPreserved() {
+        Bitmap bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
+        Canvas canvas = new Canvas(bitmap);
+        Paint paint = new Paint();
+
+        paint.setShadowLayer(5.0f, 10.0f, 10.0f, 0xFFFF0000);
+        paint.setColor(0xFF0000FF);
+        canvas.drawPaint(paint);
+
+        // Since the shadow is in the background, the canvas should be blue.
+        ColorUtils.verifyColor(0xFF0000FF, bitmap.getPixel(50, 50));
+    }
 }
diff --git a/tests/tests/graphics/src/android/graphics/cts/ColorMatrixColorFilterTest.java b/tests/tests/graphics/src/android/graphics/cts/ColorMatrixColorFilterTest.java
index 61d46b2..358e401 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ColorMatrixColorFilterTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ColorMatrixColorFilterTest.java
@@ -15,7 +15,9 @@
  */
 package android.graphics.cts;
 
+import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
 
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
@@ -97,5 +99,26 @@
         canvas.drawPoint(0, 0, paint);
         ColorUtils.verifyColor(Color.BLUE, bitmap.getPixel(0, 0));
     }
+
+    @Test
+    public void testGetColorMatrix() {
+        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(new ColorMatrix());
+        ColorMatrix getMatrix = new ColorMatrix();
+
+        filter.getColorMatrix(getMatrix);
+        assertEquals(new ColorMatrix(), getMatrix);
+
+        ColorMatrix scaleTranslate = new ColorMatrix(new float[] {
+                1, 0, 0, 0, 8,
+                0, 2, 0, 0, 7,
+                0, 0, 3, 0, 6,
+                0, 0, 0, 4, 5
+        });
+
+        filter = new ColorMatrixColorFilter(scaleTranslate);
+        filter.getColorMatrix(getMatrix);
+        assertEquals(scaleTranslate, getMatrix);
+        assertArrayEquals(scaleTranslate.getArray(), getMatrix.getArray(), 0);
+    }
 }
 
diff --git a/tests/tests/graphics/src/android/graphics/cts/ColorSpaceTest.java b/tests/tests/graphics/src/android/graphics/cts/ColorSpaceTest.java
index 3f82150..952f7e3 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ColorSpaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ColorSpaceTest.java
@@ -435,12 +435,14 @@
 
         assertSame(ColorSpace.get(ColorSpace.Named.SRGB), connector.getSource());
         assertSame(ColorSpace.get(ColorSpace.Named.DCI_P3), connector.getDestination());
+        assertSame(ColorSpace.RenderIntent.PERCEPTUAL, connector.getRenderIntent());
 
         connector = ColorSpace.connect(
                 ColorSpace.get(ColorSpace.Named.SRGB),
                 ColorSpace.get(ColorSpace.Named.SRGB));
 
         assertSame(connector.getDestination(), connector.getSource());
+        assertSame(ColorSpace.RenderIntent.RELATIVE, connector.getRenderIntent());
 
         connector = ColorSpace.connect(ColorSpace.get(ColorSpace.Named.DCI_P3));
         assertSame(ColorSpace.get(ColorSpace.Named.SRGB), connector.getDestination());
@@ -543,6 +545,7 @@
                 ColorSpace.get(ColorSpace.Named.SRGB));
 
         assertSame(connector.getSource(), connector.getDestination());
+        assertSame(ColorSpace.RenderIntent.RELATIVE, connector.getRenderIntent());
 
         float[] source = new float[] { 0.11112f, 0.22227f, 0.444448f };
 
@@ -585,6 +588,12 @@
         };
 
         assertArrayEquals(sRGBD50, ((ColorSpace.Rgb) adapted).getTransform(), 1e-7f);
+
+        adapted = ColorSpace.adapt(
+                ColorSpace.get(ColorSpace.Named.SRGB),
+                ColorSpace.ILLUMINANT_D50,
+                ColorSpace.Adaptation.BRADFORD);
+        assertArrayEquals(sRGBD50, ((ColorSpace.Rgb) adapted).getTransform(), 1e-7f);
     }
 
     @Test
diff --git a/tests/tests/graphics/src/android/graphics/cts/LightingColorFilterTest.java b/tests/tests/graphics/src/android/graphics/cts/LightingColorFilterTest.java
index da2b934..c7befa8 100644
--- a/tests/tests/graphics/src/android/graphics/cts/LightingColorFilterTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/LightingColorFilterTest.java
@@ -35,6 +35,10 @@
 public class LightingColorFilterTest {
     private static final int TOLERANCE = 2;
 
+    private void verifyColor(int expected, int actual) {
+        ColorUtils.verifyColor(expected, actual, TOLERANCE);
+    }
+
     @Test
     public void testLightingColorFilter() {
         Bitmap bitmap = Bitmap.createBitmap(1, 1, Config.ARGB_8888);
@@ -86,7 +90,22 @@
         verifyColor(Color.argb(0x80, 30, 30, 30), bitmap.getPixel(0, 0));
     }
 
-    private void verifyColor(int expected, int actual) {
-        ColorUtils.verifyColor(expected, actual, TOLERANCE);
+    @Test
+    public void testGetColorAdd() {
+        LightingColorFilter filter = new LightingColorFilter(Color.WHITE, Color.BLACK);
+        ColorUtils.verifyColor(Color.BLACK, filter.getColorAdd());
+
+        filter = new LightingColorFilter(0x87654321, 0x12345678);
+        ColorUtils.verifyColor(0x12345678, filter.getColorAdd());
+    }
+
+
+    @Test
+    public void testGetColorMultiply() {
+        LightingColorFilter filter = new LightingColorFilter(Color.WHITE, Color.BLACK);
+        ColorUtils.verifyColor(Color.WHITE, filter.getColorMultiply());
+
+        filter = new LightingColorFilter(0x87654321, 0x12345678);
+        ColorUtils.verifyColor(0x87654321, filter.getColorMultiply());
     }
 }
diff --git a/tests/tests/graphics/src/android/graphics/cts/PathTest.java b/tests/tests/graphics/src/android/graphics/cts/PathTest.java
index db3884c..ade4a97 100644
--- a/tests/tests/graphics/src/android/graphics/cts/PathTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/PathTest.java
@@ -16,6 +16,11 @@
 
 package android.graphics.cts;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Color;
@@ -25,11 +30,10 @@
 import android.graphics.RectF;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static org.junit.Assert.*;
-
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class PathTest {
@@ -440,6 +444,41 @@
         assertEquals(expectedRect, offsettedRect);
     }
 
+    @Test
+    public void testApproximate_rect_cw() {
+        Path path = new Path();
+        path.addRect(0, 0, 100, 100, Path.Direction.CW);
+        assertArrayEquals(new float[] {
+                0, 0, 0,
+                0.25f, 100, 0,
+                0.50f, 100, 100,
+                0.75f, 0, 100,
+                1, 0, 0,
+        }, path.approximate(1f), 0);
+    }
+
+    @Test
+    public void testApproximate_rect_ccw() {
+        Path path = new Path();
+        path.addRect(0, 0, 100, 100, Path.Direction.CCW);
+        assertArrayEquals(new float[] {
+                0, 0, 0,
+                0.25f, 0, 100,
+                0.50f, 100, 100,
+                0.75f, 100, 0,
+                1, 0, 0,
+        }, path.approximate(1f), 0);
+    }
+
+    @Test
+    public void testApproximate_empty() {
+        Path path = new Path();
+        assertArrayEquals(new float[] {
+                0, 0, 0,
+                1, 0, 0,
+        }, path.approximate(0.5f), 0);
+    }
+
     private static void verifyPathsAreEquivalent(Path actual, Path expected) {
         Bitmap actualBitmap = drawAndGetBitmap(actual);
         Bitmap expectedBitmap = drawAndGetBitmap(expected);
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableParameterizedTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableParameterizedTest.java
index 29da030..4a05b85 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableParameterizedTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableParameterizedTest.java
@@ -29,16 +29,20 @@
 import android.graphics.Rect;
 import android.graphics.cts.R;
 import android.graphics.drawable.AnimatedVectorDrawable;
+import android.support.annotation.Nullable;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.LargeTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
 import android.util.Log;
+import android.view.PixelCopy;
 import android.view.View;
 import android.widget.ImageView;
 
+import com.android.compatibility.common.util.SynchronousPixelCopy;
 import com.android.compatibility.common.util.SystemUtil;
+import com.android.compatibility.common.util.WidgetTestUtils;
 
 import org.junit.AfterClass;
 import org.junit.Assert;
@@ -116,43 +120,50 @@
     public void testAnimationOnLayer() throws Throwable {
         final AnimatedVectorDrawableTest.MyCallback callback
                 = new AnimatedVectorDrawableTest.MyCallback();
-        final Rect imageViewRect = new Rect();
-        final int size = mResources.getDimensionPixelSize(R.dimen.imageview_fixed_size);
+        // Can't simply use final here, b/c it needs to be initialized and referred later in UI
+        // thread.
+        final ImageView[] imageView = new ImageView[1];
         mActivityRule.runOnUiThread(() -> {
             mActivity.setContentView(R.layout.fixed_sized_imageview);
-            final ImageView imageView = (ImageView) mActivity.findViewById(R.id.imageview);
-            imageView.setLayerType(mLayerType, null);
-            AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView.getDrawable();
-            avd.registerAnimationCallback(callback);
-            int[] locationOnScreen = new int[2];
-            imageView.getLocationOnScreen(locationOnScreen);
-            imageViewRect.set(locationOnScreen[0], locationOnScreen[1],
-                    locationOnScreen[0] + size, locationOnScreen[1] + size);
-            avd.start();
+            imageView[0] = (ImageView) mActivity.findViewById(R.id.imageview);
         });
+        WidgetTestUtils.runOnMainAndDrawSync(mActivityRule, imageView[0],
+                (Runnable) () -> {
+                    imageView[0].setImageDrawable(
+                            mResources.getDrawable(R.drawable.animated_vector_favorite));
+                    imageView[0].setLayerType(mLayerType, null);
+                    AnimatedVectorDrawable avd =
+                            (AnimatedVectorDrawable) imageView[0].getDrawable();
+                    avd.registerAnimationCallback(callback);
+                    avd.start();
+                });
         callback.waitForStart();
+        waitWhilePumpingFrames(5, imageView[0], 200);
 
-        // Wait another few frames to make sure that RT has started and rendered the animation, and
-        // the frame buffer with the started animation is being rendered on screen.
-        waitWhilePumpingFrames(5, mActivity.findViewById(R.id.imageview), 200);
         Bitmap lastScreenShot = null;
+        final Rect srcRect = new Rect();
+        mActivityRule.runOnUiThread(() -> {
+            imageView[0].getGlobalVisibleRect(srcRect);
+        });
+
         int counter = 0;
         while (!callback.endIsCalled()) {
             // Take a screen shot every 50ms, and compare with previous screenshot for the ImageView
             // content, to make sure the AVD is animating when set on HW layer.
-            Bitmap screenShot = InstrumentationRegistry.getInstrumentation().getUiAutomation()
-                    .takeScreenshot();
+            Bitmap screenShot = takeScreenshot(srcRect);
             if (callback.endIsCalled()) {
                 // Animation already ended, the screenshot may not contain valid animation content,
                 // skip the comparison.
                 break;
             }
             counter++;
-            boolean isIdentical = isAlmostIdenticalInRect(screenShot, lastScreenShot, imageViewRect);
+            boolean isIdentical = isAlmostIdenticalInRect(screenShot, lastScreenShot);
             if (isIdentical) {
-                DrawableTestUtils.saveVectorDrawableIntoPNG(screenShot, "screenshot_" + counter);
-                DrawableTestUtils.saveVectorDrawableIntoPNG(lastScreenShot, "screenshot_"
-                        + (counter - 1));
+                String outputFolder = mActivity.getExternalFilesDir(null).getAbsolutePath();
+                DrawableTestUtils.saveVectorDrawableIntoPNG(screenShot, outputFolder,
+                        "screenshot_" + counter);
+                DrawableTestUtils.saveVectorDrawableIntoPNG(lastScreenShot, outputFolder,
+                        "screenshot_" + (counter - 1));
                 fail("Two consecutive screenshots of AVD are identical, AVD is "
                         + "likely not animating");
             }
@@ -166,6 +177,11 @@
         }
         // In this test, we want to make sure that we at least have 5 screenshots.
         assertTrue(counter >= 5);
+
+        mActivityRule.runOnUiThread(() -> {
+            AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView[0].getDrawable();
+            avd.stop();
+        });
     }
 
     // Pump frames by repeatedly invalidating the given view. Return true if successfully pumped
@@ -235,12 +251,19 @@
         callback.assertAVDRuntime(0, TimeUnit.MILLISECONDS.toNanos(64)); // 4 frames
     }
 
-    // Does a fuzzy comparison between two images in the given rect. Returns true if the rect area
-    // is within acceptable delta, false otherwise.
-    private static boolean isAlmostIdenticalInRect(Bitmap image1, Bitmap image2, Rect rangeRect) {
+    // Does a fuzzy comparison between two images.
+    private static boolean isAlmostIdenticalInRect(Bitmap image1, Bitmap image2) {
         if (image1 == null || image2 == null) {
             return false;
         }
+
+        if (image1.getWidth() != image2.getWidth() || image1.getHeight() != image2.getHeight()) {
+            throw new IllegalArgumentException("Images size are not the same. image1:" + image1
+                    + "image2:" + image2);
+        }
+
+        Rect rangeRect = new Rect(0, 0, image1.getWidth(), image1.getHeight());
+
         for (int x = rangeRect.left; x < rangeRect.right; x++) {
             for (int y = rangeRect.top; y < rangeRect.bottom; y++) {
                 if (image1.getPixel(x, y) != image2.getPixel(x, y)) {
@@ -263,39 +286,42 @@
     public void testInfiniteAVD() throws Throwable {
         final AnimatedVectorDrawableTest.MyCallback callback
                 = new AnimatedVectorDrawableTest.MyCallback();
-        final Rect imageViewRect = new Rect();
-        final int size = mResources.getDimensionPixelSize(R.dimen.imageview_fixed_size);
+        // Can't simply use final here, b/c it needs to be initialized and referred later in UI
+        // thread.
+        final ImageView[] imageView = new ImageView[1];
         mActivityRule.runOnUiThread(() -> {
             mActivity.setContentView(R.layout.fixed_sized_imageview);
-            final ImageView imageView = (ImageView) mActivity.findViewById(R.id.imageview);
-            imageView.setImageDrawable(mResources.getDrawable(R.drawable.infinite_avd));
-            imageView.setLayerType(mLayerType, null);
-            AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView.getDrawable();
-            avd.registerAnimationCallback(callback);
-            int[] locationOnScreen = new int[2];
-            imageView.getLocationOnScreen(locationOnScreen);
-            imageViewRect.set(locationOnScreen[0], locationOnScreen[1],
-                    locationOnScreen[0] + size, locationOnScreen[1] + size);
-            avd.start();
+            imageView[0] = (ImageView) mActivity.findViewById(R.id.imageview);
         });
-        callback.waitForStart();
+        WidgetTestUtils.runOnMainAndDrawSync(mActivityRule, imageView[0],
+                (Runnable) () -> {
+                    imageView[0].setImageDrawable(mResources.getDrawable(R.drawable.infinite_avd));
+                    imageView[0].setLayerType(mLayerType, null);
+                    AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView[0].getDrawable();
+                    avd.registerAnimationCallback(callback);
 
-        // Wait another few frames to make sure that RT has started and rendered the animation, and
-        // the frame buffer with the started animation is being rendered on screen.
-        waitWhilePumpingFrames(5, mActivity.findViewById(R.id.imageview), 200);
+                    avd.start();
+                });
+
+        callback.waitForStart();
+        waitWhilePumpingFrames(5, imageView[0], 200);
         Bitmap lastScreenShot = null;
+        final Rect srcRect = new Rect();
+        mActivityRule.runOnUiThread(() -> {
+            mActivity.findViewById(R.id.imageview).getGlobalVisibleRect(srcRect);
+        });
 
         for (int counter = 0; counter < 10; counter++) {
             // Take a screen shot every 100ms, and compare with previous screenshot for the ImageView
             // content, to make sure the AVD is animating when set on HW layer.
-            Bitmap screenShot = InstrumentationRegistry.getInstrumentation().getUiAutomation()
-                    .takeScreenshot();
-            boolean isIdentical = isAlmostIdenticalInRect(screenShot, lastScreenShot, imageViewRect);
+            Bitmap screenShot = takeScreenshot(srcRect);
+            boolean isIdentical = isAlmostIdenticalInRect(screenShot, lastScreenShot);
             if (isIdentical) {
-                DrawableTestUtils.saveVectorDrawableIntoPNG(screenShot, "inf_avd_screenshot_"
-                        + mLayerType + "_" +         counter);
-                DrawableTestUtils.saveVectorDrawableIntoPNG(lastScreenShot, "inf_avd_screenshot_"
-                        + mLayerType + "_" + (counter - 1));
+                String outputFolder = mActivity.getExternalFilesDir(null).getAbsolutePath();
+                DrawableTestUtils.saveVectorDrawableIntoPNG(screenShot, outputFolder,
+                        "inf_avd_screenshot_" + mLayerType + "_" + counter);
+                DrawableTestUtils.saveVectorDrawableIntoPNG(lastScreenShot, outputFolder,
+                        "inf_avd_screenshot_" + mLayerType + "_" + (counter - 1));
                 fail("Two consecutive screenshots of AVD are identical, AVD is "
                         + "likely not animating");
             }
@@ -310,10 +336,18 @@
         }
         Assert.assertFalse(callback.endIsCalled());
         mActivityRule.runOnUiThread(() -> {
-            ImageView imageView = (ImageView) mActivity.findViewById(R.id.imageview);
-            AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView.getDrawable();
+            AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView[0].getDrawable();
             avd.stop();
         });
     }
 
+    // Copy the source rectangle from the screen into the returned bitmap.
+    private Bitmap takeScreenshot(Rect srcRect) {
+        SynchronousPixelCopy copy = new SynchronousPixelCopy();
+        Bitmap dest = Bitmap.createBitmap(
+                srcRect.width(), srcRect.height(), Bitmap.Config.ARGB_8888);
+        int copyResult = copy.request(mActivity.getWindow(), srcRect, dest);
+        Assert.assertEquals(PixelCopy.SUCCESS, copyResult);
+        return dest;
+    }
 }
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java
index d1f6282..990a8fb 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java
@@ -105,7 +105,7 @@
         assertTrue(earthColor == 0xFF5656EA);
 
         if (DBG_DUMP_PNG) {
-            DrawableTestUtils.saveVectorDrawableIntoPNG(bitmap, mResId, mResources);
+            DrawableTestUtils.saveAutoNamedVectorDrawableIntoPNG(mActivity, bitmap, mResId, null);
         }
     }
 
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTestUtils.java b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTestUtils.java
index f91be12..077836c 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTestUtils.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableTestUtils.java
@@ -16,6 +16,7 @@
 
 package android.graphics.drawable.cts;
 
+import android.content.Context;
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.content.res.XmlResourceParser;
@@ -23,6 +24,9 @@
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.drawable.Drawable;
+import android.support.annotation.IntegerRes;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 import android.util.AttributeSet;
 import android.util.Log;
 import android.util.Xml;
@@ -206,34 +210,40 @@
         return pixel;
     }
 
-
     /**
      * Save a bitmap for debugging or golden image (re)generation purpose.
-     * The file name will be referred from the resource id and added "_golden".
+     * The file name will be referred from the resource id, plus optionally {@code extras}, and
+     * "_golden"
      */
-    static void saveVectorDrawableIntoPNG(Bitmap bitmap, int resId, Resources res) throws
-            IOException {
-        String originalFilePath = res.getString(resId);
+    static void saveAutoNamedVectorDrawableIntoPNG(@NonNull Context context, @NonNull Bitmap bitmap,
+            @IntegerRes int resId, @Nullable String extras)
+            throws IOException {
+        String originalFilePath = context.getResources().getString(resId);
         File originalFile = new File(originalFilePath);
         String fileFullName = originalFile.getName();
         String fileTitle = fileFullName.substring(0, fileFullName.lastIndexOf("."));
-        saveVectorDrawableIntoPNG(bitmap, fileTitle);
+        String outputFolder = context.getExternalFilesDir(null).getAbsolutePath();
+        if (extras != null) {
+            fileTitle += "_" + extras;
+        }
+        saveVectorDrawableIntoPNG(bitmap, outputFolder, fileTitle);
     }
 
     /**
-     * Save a bitmap to the given name plus "_golden" under /sdcard/temp/
+     * Save a {@code bitmap} to the {@code fileFullName} plus "_golden".
      */
-    static void saveVectorDrawableIntoPNG(Bitmap bitmap, String fileFullName)
+    static void saveVectorDrawableIntoPNG(@NonNull Bitmap bitmap, @NonNull String outputFolder,
+            @NonNull String fileFullName)
             throws IOException {
         // Save the image to the disk.
         FileOutputStream out = null;
         try {
-            String outputFolder = "/sdcard/temp/";
             File folder = new File(outputFolder);
             if (!folder.exists()) {
                 folder.mkdir();
             }
-            String outputFilename = outputFolder + fileFullName + "_golden.png";
+            String outputFilename = outputFolder + "/" + fileFullName + "_golden";
+            outputFilename +=".png";
             File outputFile = new File(outputFilename);
             if (!outputFile.exists()) {
                 outputFile.createNewFile();
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableScaleTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableScaleTest.java
index e7daf65..4e5fb15 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableScaleTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableScaleTest.java
@@ -71,7 +71,8 @@
 
         screenShot = takeScreenshot(srcRect);
         if (DBG_SCREENSHOT) {
-            DrawableTestUtils.saveVectorDrawableIntoPNG(screenShot, "scale");
+            String outputFolder = mActivity.getExternalFilesDir(null).getAbsolutePath();
+            DrawableTestUtils.saveVectorDrawableIntoPNG(screenShot, outputFolder, "scale");
         }
 
         Bitmap golden = BitmapFactory.decodeResource(mResources,
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java
index 276bf50..c09a139 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
+import android.content.Context;
 import android.content.res.Resources;
 import android.content.res.Resources.Theme;
 import android.content.res.XmlResourceParser;
@@ -32,6 +33,7 @@
 import android.graphics.cts.R;
 import android.graphics.drawable.Drawable.ConstantState;
 import android.graphics.drawable.VectorDrawable;
+import android.support.annotation.Nullable;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
@@ -170,9 +172,9 @@
                     R.drawable.vector_icon_state_list_2_golden
             },
             {
-                    R.drawable.vector_icon_state_list_golden_pressed,
-                    R.drawable.vector_icon_state_list_golden_pressed,
-                    R.drawable.vector_icon_state_list_2_golden_pressed
+                    R.drawable.vector_icon_state_list_pressed_golden,
+                    R.drawable.vector_icon_state_list_pressed_golden,
+                    R.drawable.vector_icon_state_list_2_pressed_golden
             }
     };
 
@@ -189,6 +191,7 @@
     private Resources mResources;
     private Bitmap mBitmap;
     private Canvas mCanvas;
+    private Context mContext;
 
     @Before
     public void setup() {
@@ -197,7 +200,8 @@
 
         mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
         mCanvas = new Canvas(mBitmap);
-        mResources = InstrumentationRegistry.getTargetContext().getResources();
+        mContext = InstrumentationRegistry.getTargetContext();
+        mResources = mContext.getResources();
     }
 
     @Test
@@ -234,7 +238,6 @@
             VectorDrawable vectorDrawable = new VectorDrawable();
             vectorDrawable.setBounds(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
 
-
             // Setup VectorDrawable from xml file and draw into the bitmap.
             XmlPullParser parser = mResources.getXml(resIds[i]);
             AttributeSet attrs = Xml.asAttributeSet(parser);
@@ -261,7 +264,9 @@
             vectorDrawable.draw(mCanvas);
 
             if (DBG_DUMP_PNG) {
-                saveVectorDrawableIntoPNG(mBitmap, resIds, i, stateSet);
+                String stateSetTitle = getTitleForStateSet(stateSet);
+                DrawableTestUtils.saveAutoNamedVectorDrawableIntoPNG(mContext, mBitmap, resIds[i],
+                        stateSetTitle);
             } else {
                 // Start to compare
                 Bitmap golden = BitmapFactory.decodeResource(mResources, goldenImages[i]);
@@ -274,59 +279,23 @@
         }
     }
 
-    // This is only for debugging or golden image (re)generation purpose.
-    private void saveVectorDrawableIntoPNG(Bitmap bitmap, int[] resIds, int index, int[] stateSet)
-            throws IOException {
-        // Save the image to the disk.
-        FileOutputStream out = null;
-        try {
-            String outputFolder = "/sdcard/temp/";
-            File folder = new File(outputFolder);
-            if (!folder.exists()) {
-                folder.mkdir();
-            }
-            String originalFilePath = mResources.getString(resIds[index]);
-            File originalFile = new File(originalFilePath);
-            String fileFullName = originalFile.getName();
-            String fileTitle = fileFullName.substring(0, fileFullName.lastIndexOf("."));
-            String stateSetTitle = getTitleForStateSet(stateSet);
-            String outputFilename = outputFolder + fileTitle + "_golden" + stateSetTitle + ".png";
-            File outputFile = new File(outputFilename);
-            if (!outputFile.exists()) {
-                outputFile.createNewFile();
-            }
-
-            out = new FileOutputStream(outputFile, false);
-            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
-            Log.v(LOGTAG, "Write test No." + index + " to file successfully.");
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            if (out != null) {
-                out.close();
-            }
-        }
-    }
-
     /**
      * Generates an underline-delimited list of states in a given state set.
      * <p>
      * For example, the array {@code {R.attr.state_pressed}} would return
-     * {@code "_pressed"}.
+     * {@code "pressed"}.
      *
      * @param stateSet a state set
-     * @return a string representing the state set, or the empty string if the
-     *         state set is empty or {@code null}
+     * @return a string representing the state set, or {@code null} if the state set is empty or
+     * {@code null}
      */
-    private String getTitleForStateSet(int[] stateSet) {
+    private @Nullable String getTitleForStateSet(int[] stateSet) {
         if (stateSet == null || stateSet.length == 0) {
-            return "";
+            return null;
         }
 
         final StringBuilder builder = new StringBuilder();
         for (int i = 0; i < stateSet.length; i++) {
-            builder.append('_');
-
             final String state = mResources.getResourceName(stateSet[i]);
             final int stateIndex = state.indexOf("state_");
             if (stateIndex >= 0) {
diff --git a/tests/tests/hardware/jni/android_hardware_cts_HardwareBufferTest.cpp b/tests/tests/hardware/jni/android_hardware_cts_HardwareBufferTest.cpp
index 59c1637..c5b5c35 100644
--- a/tests/tests/hardware/jni/android_hardware_cts_HardwareBufferTest.cpp
+++ b/tests/tests/hardware/jni/android_hardware_cts_HardwareBufferTest.cpp
@@ -27,13 +27,12 @@
 static jobject android_hardware_HardwareBuffer_nativeCreateHardwareBuffer(JNIEnv* env, jclass,
         jint width, jint height, jint format, jint layers, jlong usage) {
     AHardwareBuffer* buffer = NULL;
-    AHardwareBuffer_Desc desc;
+    AHardwareBuffer_Desc desc = {};
 
     desc.width = width;
     desc.height = height;
     desc.layers = layers;
-    desc.usage0 = usage;
-    desc.usage1 = 0;
+    desc.usage = usage;
     desc.format = format;
     int res = AHardwareBuffer_allocate(&desc, &buffer);
     if (res == android::NO_ERROR) {
diff --git a/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java b/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java
index 2655573..5ea845a 100644
--- a/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java
@@ -99,33 +99,33 @@
     @Test
     public void testCreate() {
         HardwareBuffer buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBA_8888, 1,
-                HardwareBuffer.USAGE0_CPU_READ);
+                HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertTrue(buffer != null);
         assertEquals(2, buffer.getWidth());
         assertEquals(4, buffer.getHeight());
         assertEquals(HardwareBuffer.RGBA_8888, buffer.getFormat());
         assertEquals(1, buffer.getLayers());
-        assertEquals(HardwareBuffer.USAGE0_CPU_READ, buffer.getUsage());
+        assertEquals(HardwareBuffer.USAGE_CPU_READ_RARELY, buffer.getUsage());
 
         buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBX_8888, 1,
-                HardwareBuffer.USAGE0_CPU_READ);
+                HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertEquals(HardwareBuffer.RGBX_8888, buffer.getFormat());
         buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGB_888, 1,
-                HardwareBuffer.USAGE0_CPU_READ);
+                HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertEquals(HardwareBuffer.RGB_888, buffer.getFormat());
         buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGB_565, 1,
-                HardwareBuffer.USAGE0_CPU_READ);
+                HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertEquals(HardwareBuffer.RGB_565, buffer.getFormat());
         buffer = HardwareBuffer.create(2, 1, HardwareBuffer.BLOB, 1,
-                HardwareBuffer.USAGE0_CPU_READ);
+                HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertEquals(HardwareBuffer.BLOB, buffer.getFormat());
 
         if (sHasFloatBuffers) {
             buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBA_FP16, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
             assertEquals(HardwareBuffer.RGBA_FP16, buffer.getFormat());
             buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBA_1010102, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
             assertEquals(HardwareBuffer.RGBA_1010102, buffer.getFormat());
         }
     }
@@ -136,40 +136,40 @@
         HardwareBuffer buffer = null;
         try {
             buffer = HardwareBuffer.create(0, 4, HardwareBuffer.RGB_888, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
         } catch (IllegalArgumentException e) {}
         assertEquals(null, buffer);
         try {
             buffer = HardwareBuffer.create(2, 0, HardwareBuffer.RGB_888, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
         } catch (IllegalArgumentException e) {}
         assertEquals(null, buffer);
         try {
             buffer = HardwareBuffer.create(2, 4, 0, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
         } catch (IllegalArgumentException e) {}
         assertEquals(null, buffer);
         try {
             buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGB_888, -1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
         } catch (IllegalArgumentException e) {}
         assertEquals(null, buffer);
         try {
             buffer = HardwareBuffer.create(2, 2, HardwareBuffer.BLOB, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
         } catch (IllegalArgumentException e) {}
         assertEquals(null, buffer);
 
         if (sHasFloatBuffers) {
             try {
                 buffer = HardwareBuffer.create(0, 4, HardwareBuffer.RGBA_FP16, 1,
-                        HardwareBuffer.USAGE0_CPU_READ);
+                        HardwareBuffer.USAGE_CPU_READ_RARELY);
             } catch (IllegalArgumentException e) {
             }
             assertEquals(null, buffer);
             try {
                 buffer = HardwareBuffer.create(0, 4, HardwareBuffer.RGBA_1010102, 1,
-                        HardwareBuffer.USAGE0_CPU_READ);
+                        HardwareBuffer.USAGE_CPU_READ_RARELY);
             } catch (IllegalArgumentException e) {
             }
             assertEquals(null, buffer);
@@ -179,13 +179,13 @@
     @Test
     public void testCreateFromNativeObject() {
         HardwareBuffer buffer = nativeCreateHardwareBuffer(2, 4, HardwareBuffer.RGBA_8888, 1,
-                    HardwareBuffer.USAGE0_CPU_READ);
+                    HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertTrue(buffer != null);
         assertEquals(2, buffer.getWidth());
         assertEquals(4, buffer.getHeight());
         assertEquals(HardwareBuffer.RGBA_8888, buffer.getFormat());
         assertEquals(1, buffer.getLayers());
-        assertEquals(HardwareBuffer.USAGE0_CPU_READ, buffer.getUsage());
+        assertEquals(HardwareBuffer.USAGE_CPU_READ_RARELY, buffer.getUsage());
         nativeReleaseHardwareBuffer(buffer);
     }
 }
diff --git a/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp b/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp
index 8570a2c..a8ce1c7 100644
--- a/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp
+++ b/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp
@@ -51,11 +51,11 @@
 static constexpr int kTestImageFormat = AIMAGE_FORMAT_JPEG;
 
 static constexpr int supportedUsage[] = {
-    AHARDWAREBUFFER_USAGE0_CPU_READ,
-    AHARDWAREBUFFER_USAGE0_CPU_READ_OFTEN,
-    AHARDWAREBUFFER_USAGE0_GPU_SAMPLED_IMAGE,
-    AHARDWAREBUFFER_USAGE0_GPU_DATA_BUFFER,
-    AHARDWAREBUFFER_USAGE0_VIDEO_ENCODE,
+    AHARDWAREBUFFER_USAGE_CPU_READ_RARELY,
+    AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
+    AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE,
+    AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER,
+    AHARDWAREBUFFER_USAGE_VIDEO_ENCODE,
 };
 
 class CameraHelper {
@@ -394,16 +394,16 @@
             }
         }
 
-        if ((outDesc.usage0 & mUsage) != mUsage) {
+        if ((outDesc.usage & mUsage) != mUsage) {
             ALOGE("Mismatched output buffer usage: actual (%" PRIu64 "), expected (%" PRIu64 ")",
-                  outDesc.usage0, mUsage);
+                  outDesc.usage, mUsage);
             return;
         }
 
         uint8_t* data = nullptr;
         int dataLength = 0;
         ret = AImage_getPlaneData(img.get(), 0, &data, &dataLength);
-        if (mUsage & AHARDWAREBUFFER_USAGE0_CPU_READ_OFTEN) {
+        if (mUsage & AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN) {
             // When we have CPU_READ_OFTEN usage bits, we can lock the image.
             if (ret != AMEDIA_OK || data == nullptr || dataLength < 0) {
                 ALOGE("Failed to access CPU data, ret=%d, data=%p, dataLength=%d", ret, data,
@@ -518,12 +518,12 @@
 extern "C" jboolean Java_android_media_cts_NativeImageReaderTest_\
 testTakePicturesNative(JNIEnv* /*env*/, jclass /*clazz*/) {
     for (auto& readerUsage :
-         {AHARDWAREBUFFER_USAGE0_CPU_READ_OFTEN, AHARDWAREBUFFER_USAGE0_GPU_DATA_BUFFER}) {
+         {AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN, AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER}) {
         for (auto& readerMaxImages : {1, 4, 8}) {
             for (auto& readerAsync : {true, false}) {
                 for (auto& pictureCount : {1, 8, 16}) {
                     if (takePictures(readerUsage, readerMaxImages, readerAsync, pictureCount)) {
-                        ALOGE("Test takePictures failed for test case usage=%d, maxImages=%d, "
+                        ALOGE("Test takePictures failed for test case usage=%" PRIu64 ", maxImages=%d, "
                               "async=%d, pictureCount=%d",
                               readerUsage, readerMaxImages, readerAsync, pictureCount);
                         return false;
@@ -537,7 +537,7 @@
 
 extern "C" jobject Java_android_media_cts_NativeImageReaderTest_\
 testCreateSurfaceNative(JNIEnv* env, jclass /*clazz*/) {
-    static constexpr uint64_t kTestImageUsage = AHARDWAREBUFFER_USAGE0_CPU_READ_OFTEN;
+    static constexpr uint64_t kTestImageUsage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN;
     static constexpr int kTestImageCount = 8;
 
     ImageReaderTestCase testCase(
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index ba657bf..4c6eb27 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -78,6 +78,11 @@
                 && (packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
                         || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION));
     }
+    @Override
+    protected void tearDown() throws Exception {
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), false);
+    }
 
     public void testMicrophoneMute() throws Exception {
         mAudioManager.setMicrophoneMute(true);
@@ -94,7 +99,7 @@
             mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
         } finally {
             Utils.toggleNotificationPolicyAccess(
-                mContext.getPackageName(), getInstrumentation(), false);
+                    mContext.getPackageName(), getInstrumentation(), false);
         }
         Settings.System.putInt(mContext.getContentResolver(), SOUND_EFFECTS_ENABLED, 1);
 
@@ -193,165 +198,150 @@
         if (mUseFixedVolume || !mHasVibrator) {
             return;
         }
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            // VIBRATE_SETTING_ON
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        // VIBRATE_SETTING_ON
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                    mAudioManager.getRingerMode());
-            assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                mAudioManager.getRingerMode());
+        assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            // VIBRATE_SETTING_OFF
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
-            assertEquals(VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        // VIBRATE_SETTING_OFF
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
+        assertEquals(VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                    mAudioManager.getRingerMode());
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                mAudioManager.getRingerMode());
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            // VIBRATE_SETTING_ONLY_SILENT
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        // VIBRATE_SETTING_ONLY_SILENT
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                    mAudioManager.getRingerMode());
-            assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                mAudioManager.getRingerMode());
+        assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION));
 
-            // VIBRATE_TYPE_NOTIFICATION
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
-            assertEquals(VIBRATE_SETTING_OFF, mAudioManager
-                    .getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
-        }
+        // VIBRATE_TYPE_NOTIFICATION
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
+        assertEquals(VIBRATE_SETTING_OFF, mAudioManager
+                .getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION));
     }
 
     public void testVibrateRinger() throws Exception {
         if (mUseFixedVolume || !mHasVibrator) {
             return;
         }
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            // VIBRATE_TYPE_RINGER
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        // VIBRATE_TYPE_RINGER
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                    mAudioManager.getRingerMode());
-            assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                mAudioManager.getRingerMode());
+        assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            // VIBRATE_SETTING_OFF
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
-            assertEquals(VIBRATE_SETTING_OFF, mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        // VIBRATE_SETTING_OFF
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
+        assertEquals(VIBRATE_SETTING_OFF, mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                    mAudioManager.getRingerMode());
-            // Note: as of Froyo, if VIBRATE_TYPE_RINGER is set to OFF, it will
-            // not vibrate, even in RINGER_MODE_VIBRATE. This allows users to
-            // disable the vibration for incoming calls only.
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                mAudioManager.getRingerMode());
+        // Note: as of Froyo, if VIBRATE_TYPE_RINGER is set to OFF, it will
+        // not vibrate, even in RINGER_MODE_VIBRATE. This allows users to
+        // disable the vibration for incoming calls only.
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            // VIBRATE_SETTING_ONLY_SILENT
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        // VIBRATE_SETTING_ONLY_SILENT
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertFalse(mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                    mAudioManager.getRingerMode());
-            assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                mAudioManager.getRingerMode());
+        assertEquals(mHasVibrator, mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER));
 
-            // VIBRATE_TYPE_NOTIFICATION
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
-            assertEquals(VIBRATE_SETTING_OFF, mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
-            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
-            assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
-                    mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
-        }
+        // VIBRATE_TYPE_NOTIFICATION
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ON : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
+        assertEquals(VIBRATE_SETTING_OFF, mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
+        mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
+        assertEquals(mHasVibrator ? VIBRATE_SETTING_ONLY_SILENT : VIBRATE_SETTING_OFF,
+                mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER));
     }
 
     public void testAccessRingMode() throws Exception {
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        // AudioService#setRingerMode() has:
+        // if (isTelevision) return;
+        if (mUseFixedVolume || mIsTelevision) {
             assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+        } else {
+            assertEquals(RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+        }
 
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            // AudioService#setRingerMode() has:
-            // if (isTelevision) return;
-            if (mUseFixedVolume || mIsTelevision) {
-                assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-            } else {
-                assertEquals(RINGER_MODE_SILENT, mAudioManager.getRingerMode());
-            }
-
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-            if (mUseFixedVolume || mIsTelevision) {
-                assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-            } else {
-                assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
-                        mAudioManager.getRingerMode());
-            }
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
+        mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+        if (mUseFixedVolume || mIsTelevision) {
+            assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+        } else {
+            assertEquals(mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT,
+                    mAudioManager.getRingerMode());
         }
     }
 
@@ -359,32 +349,47 @@
         if (mUseFixedVolume || mIsTelevision) {
             return;
         }
+        // Apps without policy access cannot change silent -> normal or silent -> vibrate.
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        assertEquals(RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), false);
+
         try {
-            // Apps without policy access cannot change silent -> normal or silent -> vibrate.
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            assertEquals(RINGER_MODE_SILENT, mAudioManager.getRingerMode());
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
-
-            try {
-                mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-                fail("Apps without notification policy access cannot change ringer mode");
-            } catch (SecurityException e) {
-            }
-
-            try {
-                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-                fail("Apps without notification policy access cannot change ringer mode");
-            } catch (SecurityException e) {
-            }
-
-            // Apps without policy access cannot change normal -> silent.
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
             mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+            fail("Apps without notification policy access cannot change ringer mode");
+        } catch (SecurityException e) {
+        }
+
+        try {
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            fail("Apps without notification policy access cannot change ringer mode");
+        } catch (SecurityException e) {
+        }
+
+        // Apps without policy access cannot change normal -> silent.
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), false);
+
+        try {
+            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+            fail("Apps without notification policy access cannot change ringer mode");
+        } catch (SecurityException e) {
+        }
+        assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+
+        if (mHasVibrator) {
+            // Apps without policy access cannot change vibrate -> silent.
+            Utils.toggleNotificationPolicyAccess(
+                    mContext.getPackageName(), getInstrumentation(), true);
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            assertEquals(RINGER_MODE_VIBRATE, mAudioManager.getRingerMode());
             Utils.toggleNotificationPolicyAccess(
                     mContext.getPackageName(), getInstrumentation(), false);
 
@@ -393,33 +398,13 @@
                 fail("Apps without notification policy access cannot change ringer mode");
             } catch (SecurityException e) {
             }
+
+            // Apps without policy access can change vibrate -> normal and vice versa.
+            assertEquals(RINGER_MODE_VIBRATE, mAudioManager.getRingerMode());
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
             assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-
-            if (mHasVibrator) {
-                // Apps without policy access cannot change vibrate -> silent.
-                Utils.toggleNotificationPolicyAccess(
-                        mContext.getPackageName(), getInstrumentation(), true);
-                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-                assertEquals(RINGER_MODE_VIBRATE, mAudioManager.getRingerMode());
-                Utils.toggleNotificationPolicyAccess(
-                        mContext.getPackageName(), getInstrumentation(), false);
-
-                try {
-                    mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-                    fail("Apps without notification policy access cannot change ringer mode");
-                } catch (SecurityException e) {
-                }
-
-                // Apps without policy access can change vibrate -> normal and vice versa.
-                assertEquals(RINGER_MODE_VIBRATE, mAudioManager.getRingerMode());
-                mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-                assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
-                assertEquals(RINGER_MODE_VIBRATE, mAudioManager.getRingerMode());
-            }
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            assertEquals(RINGER_MODE_VIBRATE, mAudioManager.getRingerMode());
         }
     }
 
@@ -464,150 +449,145 @@
     }
 
     public void testVolume() throws Exception {
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            int volume, volumeDelta;
-            int[] streams = {AudioManager.STREAM_ALARM,
-                    AudioManager.STREAM_MUSIC,
-                    AudioManager.STREAM_VOICE_CALL,
-                    AudioManager.STREAM_RING};
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        int volume, volumeDelta;
+        int[] streams = {AudioManager.STREAM_ALARM,
+                AudioManager.STREAM_MUSIC,
+                AudioManager.STREAM_VOICE_CALL,
+                AudioManager.STREAM_RING};
 
-            mAudioManager.adjustVolume(ADJUST_RAISE, 0);
-            // adjusting volume is aynchronous, wait before other volume checks
-            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
-            mAudioManager.adjustSuggestedStreamVolume(
-                    ADJUST_LOWER, USE_DEFAULT_STREAM_TYPE, 0);
-            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
-            int maxMusicVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
+        mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+        // adjusting volume is aynchronous, wait before other volume checks
+        Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+        mAudioManager.adjustSuggestedStreamVolume(
+                ADJUST_LOWER, USE_DEFAULT_STREAM_TYPE, 0);
+        Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+        int maxMusicVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
 
-            for (int stream : streams) {
-                // set ringer mode to back normal to not interfere with volume tests
-                mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        for (int stream : streams) {
+            // set ringer mode to back normal to not interfere with volume tests
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
 
-                int maxVolume = mAudioManager.getStreamMaxVolume(stream);
-                int minVolume = mAudioManager.getStreamMinVolume(stream);
+            int maxVolume = mAudioManager.getStreamMaxVolume(stream);
+            int minVolume = mAudioManager.getStreamMinVolume(stream);
 
-                // validate min
-                assertTrue(String.format("minVolume(%d) must be >= 0", minVolume), minVolume >= 0);
-                assertTrue(String.format("minVolume(%d) must be < maxVolume(%d)", minVolume,
-                        maxVolume),
-                        minVolume < maxVolume);
+            // validate min
+            assertTrue(String.format("minVolume(%d) must be >= 0", minVolume), minVolume >= 0);
+            assertTrue(String.format("minVolume(%d) must be < maxVolume(%d)", minVolume,
+                    maxVolume),
+                    minVolume < maxVolume);
 
-                mAudioManager.setStreamVolume(stream, 1, 0);
-                if (mUseFixedVolume) {
-                    assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
-                    continue;
-                }
-                assertEquals(String.format("stream=%d", stream),
-                             1, mAudioManager.getStreamVolume(stream));
-
-                if (stream == AudioManager.STREAM_MUSIC && mAudioManager.isWiredHeadsetOn()) {
-                    // due to new regulations, music sent over a wired headset may be volume limited
-                    // until the user explicitly increases the limit, so we can't rely on being able
-                    // to set the volume to getStreamMaxVolume(). Instead, determine the current limit
-                    // by increasing the volume until it won't go any higher, then use that volume as
-                    // the maximum for the purposes of this test
-                    int curvol = 0;
-                    int prevvol = 0;
-                    do {
-                        prevvol = curvol;
-                        mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
-                        curvol = mAudioManager.getStreamVolume(stream);
-                    } while (curvol != prevvol);
-                    maxVolume = maxMusicVolume = curvol;
-                }
-                mAudioManager.setStreamVolume(stream, maxVolume, 0);
-                mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
-                assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
-
-                volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
-                mAudioManager.adjustSuggestedStreamVolume(ADJUST_LOWER, stream, 0);
-                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
-                assertEquals(maxVolume - volumeDelta, mAudioManager.getStreamVolume(stream));
-
-                // volume lower
-                mAudioManager.setStreamVolume(stream, maxVolume, 0);
-                volume = mAudioManager.getStreamVolume(stream);
-                while (volume > minVolume) {
-                    volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
-                    mAudioManager.adjustStreamVolume(stream, ADJUST_LOWER, 0);
-                    assertEquals(Math.max(0, volume - volumeDelta),
-                            mAudioManager.getStreamVolume(stream));
-                    volume = mAudioManager.getStreamVolume(stream);
-                }
-
-                mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
-
-                // volume raise
-                mAudioManager.setStreamVolume(stream, 1, 0);
-                volume = mAudioManager.getStreamVolume(stream);
-                while (volume < maxVolume) {
-                    volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
-                    mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
-                    assertEquals(Math.min(volume + volumeDelta, maxVolume),
-                            mAudioManager.getStreamVolume(stream));
-                    volume = mAudioManager.getStreamVolume(stream);
-                }
-
-                // volume same
-                mAudioManager.setStreamVolume(stream, maxVolume, 0);
-                for (int k = 0; k < maxVolume; k++) {
-                    mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
-                    assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
-                }
-
-                mAudioManager.setStreamVolume(stream, maxVolume, 0);
-            }
-
+            mAudioManager.setStreamVolume(stream, 1, 0);
             if (mUseFixedVolume) {
-                return;
+                assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
+                continue;
+            }
+            assertEquals(String.format("stream=%d", stream),
+                    1, mAudioManager.getStreamVolume(stream));
+
+            if (stream == AudioManager.STREAM_MUSIC && mAudioManager.isWiredHeadsetOn()) {
+                // due to new regulations, music sent over a wired headset may be volume limited
+                // until the user explicitly increases the limit, so we can't rely on being able
+                // to set the volume to getStreamMaxVolume(). Instead, determine the current limit
+                // by increasing the volume until it won't go any higher, then use that volume as
+                // the maximum for the purposes of this test
+                int curvol = 0;
+                int prevvol = 0;
+                do {
+                    prevvol = curvol;
+                    mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
+                    curvol = mAudioManager.getStreamVolume(stream);
+                } while (curvol != prevvol);
+                maxVolume = maxMusicVolume = curvol;
+            }
+            mAudioManager.setStreamVolume(stream, maxVolume, 0);
+            mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
+            assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
+
+            volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
+            mAudioManager.adjustSuggestedStreamVolume(ADJUST_LOWER, stream, 0);
+            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            assertEquals(maxVolume - volumeDelta, mAudioManager.getStreamVolume(stream));
+
+            // volume lower
+            mAudioManager.setStreamVolume(stream, maxVolume, 0);
+            volume = mAudioManager.getStreamVolume(stream);
+            while (volume > minVolume) {
+                volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
+                mAudioManager.adjustStreamVolume(stream, ADJUST_LOWER, 0);
+                assertEquals(Math.max(0, volume - volumeDelta),
+                        mAudioManager.getStreamVolume(stream));
+                volume = mAudioManager.getStreamVolume(stream);
             }
 
-            // adjust volume
-            mAudioManager.adjustVolume(ADJUST_RAISE, 0);
-            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
 
-            MediaPlayer mp = MediaPlayer.create(mContext, MP3_TO_PLAY);
-            assertNotNull(mp);
-            mp.setAudioStreamType(STREAM_MUSIC);
-            mp.setLooping(true);
-            mp.start();
-            Thread.sleep(TIME_TO_PLAY);
-            assertTrue(mAudioManager.isMusicActive());
-
-            // adjust volume as ADJUST_SAME
-            for (int k = 0; k < maxMusicVolume; k++) {
-                mAudioManager.adjustVolume(ADJUST_SAME, 0);
-                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
-                assertEquals(maxMusicVolume, mAudioManager.getStreamVolume(STREAM_MUSIC));
+            // volume raise
+            mAudioManager.setStreamVolume(stream, 1, 0);
+            volume = mAudioManager.getStreamVolume(stream);
+            while (volume < maxVolume) {
+                volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
+                mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
+                assertEquals(Math.min(volume + volumeDelta, maxVolume),
+                        mAudioManager.getStreamVolume(stream));
+                volume = mAudioManager.getStreamVolume(stream);
             }
 
-            // adjust volume as ADJUST_RAISE
-            mAudioManager.setStreamVolume(STREAM_MUSIC, 0, 0);
-            volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(STREAM_MUSIC));
-            mAudioManager.adjustVolume(ADJUST_RAISE, 0);
-            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
-            assertEquals(Math.min(volumeDelta, maxMusicVolume),
-                    mAudioManager.getStreamVolume(STREAM_MUSIC));
+            // volume same
+            mAudioManager.setStreamVolume(stream, maxVolume, 0);
+            for (int k = 0; k < maxVolume; k++) {
+                mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
+                assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
+            }
 
-            // adjust volume as ADJUST_LOWER
-            mAudioManager.setStreamVolume(STREAM_MUSIC, maxMusicVolume, 0);
-            maxMusicVolume = mAudioManager.getStreamVolume(STREAM_MUSIC);
-            volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(STREAM_MUSIC));
-            mAudioManager.adjustVolume(ADJUST_LOWER, 0);
-            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
-            assertEquals(Math.max(0, maxMusicVolume - volumeDelta),
-                    mAudioManager.getStreamVolume(STREAM_MUSIC));
-
-            mp.stop();
-            mp.release();
-            Thread.sleep(TIME_TO_PLAY);
-            assertFalse(mAudioManager.isMusicActive());
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
+            mAudioManager.setStreamVolume(stream, maxVolume, 0);
         }
+
+        if (mUseFixedVolume) {
+            return;
+        }
+
+        // adjust volume
+        mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+        Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+
+        MediaPlayer mp = MediaPlayer.create(mContext, MP3_TO_PLAY);
+        assertNotNull(mp);
+        mp.setAudioStreamType(STREAM_MUSIC);
+        mp.setLooping(true);
+        mp.start();
+        Thread.sleep(TIME_TO_PLAY);
+        assertTrue(mAudioManager.isMusicActive());
+
+        // adjust volume as ADJUST_SAME
+        for (int k = 0; k < maxMusicVolume; k++) {
+            mAudioManager.adjustVolume(ADJUST_SAME, 0);
+            Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            assertEquals(maxMusicVolume, mAudioManager.getStreamVolume(STREAM_MUSIC));
+        }
+
+        // adjust volume as ADJUST_RAISE
+        mAudioManager.setStreamVolume(STREAM_MUSIC, 0, 0);
+        volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(STREAM_MUSIC));
+        mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+        Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+        assertEquals(Math.min(volumeDelta, maxMusicVolume),
+                mAudioManager.getStreamVolume(STREAM_MUSIC));
+
+        // adjust volume as ADJUST_LOWER
+        mAudioManager.setStreamVolume(STREAM_MUSIC, maxMusicVolume, 0);
+        maxMusicVolume = mAudioManager.getStreamVolume(STREAM_MUSIC);
+        volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(STREAM_MUSIC));
+        mAudioManager.adjustVolume(ADJUST_LOWER, 0);
+        Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+        assertEquals(Math.max(0, maxMusicVolume - volumeDelta),
+                mAudioManager.getStreamVolume(STREAM_MUSIC));
+
+        mp.stop();
+        mp.release();
+        Thread.sleep(TIME_TO_PLAY);
+        assertFalse(mAudioManager.isMusicActive());
     }
 
     public void testAccessibilityVolume() throws Exception {
@@ -681,77 +661,72 @@
             return;
         }
         int[] streams = { AudioManager.STREAM_RING };
-        try {
-            // Mute streams
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            mAudioManager.setRingerMode(RINGER_MODE_SILENT);
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
-            // Verify streams cannot be unmuted without policy access.
-            for (int stream : streams) {
-                try {
-                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_UNMUTE, 0);
-                    assertEquals("Apps without Notification policy access can't change ringer mode",
-                            RINGER_MODE_SILENT, mAudioManager.getRingerMode());
-                } catch (SecurityException e) {
-                }
-
-                try {
-                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE,
-                            0);
-                    assertEquals("Apps without Notification policy access can't change ringer mode",
-                            RINGER_MODE_SILENT, mAudioManager.getRingerMode());
-                } catch (SecurityException e) {
-                }
-
-                try {
-                    mAudioManager.setStreamMute(stream, false);
-                    assertEquals("Apps without Notification policy access can't change ringer mode",
-                            RINGER_MODE_SILENT, mAudioManager.getRingerMode());
-                } catch (SecurityException e) {
-                }
+        // Mute streams
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), false);
+        // Verify streams cannot be unmuted without policy access.
+        for (int stream : streams) {
+            try {
+                mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_UNMUTE, 0);
+                assertEquals("Apps without Notification policy access can't change ringer mode",
+                        RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+            } catch (SecurityException e) {
             }
 
-            // This ensures we're out of vibrate or silent modes.
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            for (int stream : streams) {
-                // ensure each stream is on and turned up.
-                mAudioManager.setStreamVolume(stream,
-                        mAudioManager.getStreamMaxVolume(stream),
+            try {
+                mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE,
                         0);
-
-                Utils.toggleNotificationPolicyAccess(
-                        mContext.getPackageName(), getInstrumentation(), false);
-                try {
-                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
-                    assertEquals("Apps without Notification policy access can't change ringer mode",
-                            RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-                } catch (SecurityException e) {
-                }
-                try {
-                    mAudioManager.adjustStreamVolume(
-                            stream, AudioManager.ADJUST_TOGGLE_MUTE, 0);
-                    assertEquals("Apps without Notification policy access can't change ringer mode",
-                            RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-                } catch (SecurityException e) {
-                }
-
-                try {
-                    mAudioManager.setStreamMute(stream, true);
-                    assertEquals("Apps without Notification policy access can't change ringer mode",
-                            RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-                } catch (SecurityException e) {
-                }
-                Utils.toggleNotificationPolicyAccess(
-                        mContext.getPackageName(), getInstrumentation(), true);
-                testStreamMuting(stream);
+                assertEquals("Apps without Notification policy access can't change ringer mode",
+                        RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+            } catch (SecurityException e) {
             }
-        } finally {
+
+            try {
+                mAudioManager.setStreamMute(stream, false);
+                assertEquals("Apps without Notification policy access can't change ringer mode",
+                        RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+            } catch (SecurityException e) {
+            }
+        }
+
+        // This ensures we're out of vibrate or silent modes.
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        for (int stream : streams) {
+            // ensure each stream is on and turned up.
+            mAudioManager.setStreamVolume(stream,
+                    mAudioManager.getStreamMaxVolume(stream),
+                    0);
+
             Utils.toggleNotificationPolicyAccess(
                     mContext.getPackageName(), getInstrumentation(), false);
+            try {
+                mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
+                assertEquals("Apps without Notification policy access can't change ringer mode",
+                        RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+            } catch (SecurityException e) {
+            }
+            try {
+                mAudioManager.adjustStreamVolume(
+                        stream, AudioManager.ADJUST_TOGGLE_MUTE, 0);
+                assertEquals("Apps without Notification policy access can't change ringer mode",
+                        RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+            } catch (SecurityException e) {
+            }
+
+            try {
+                mAudioManager.setStreamMute(stream, true);
+                assertEquals("Apps without Notification policy access can't change ringer mode",
+                        RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+            } catch (SecurityException e) {
+            }
+            Utils.toggleNotificationPolicyAccess(
+                    mContext.getPackageName(), getInstrumentation(), true);
+            testStreamMuting(stream);
         }
     }
 
@@ -765,44 +740,39 @@
                 AudioManager.STREAM_ALARM
         };
 
-        try {
-            int muteAffectedStreams = System.getInt(mContext.getContentResolver(),
-                    System.MUTE_STREAMS_AFFECTED,
-                    // Same defaults as in AudioService. Should be kept in
-                    // sync.
-                    ((1 << AudioManager.STREAM_MUSIC) |
-                            (1 << AudioManager.STREAM_RING) |
-                            (1 << AudioManager.STREAM_NOTIFICATION) |
-                            (1 << AudioManager.STREAM_SYSTEM)));
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            // This ensures we're out of vibrate or silent modes.
-            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
-            for (int stream : streams) {
-                // ensure each stream is on and turned up.
-                mAudioManager.setStreamVolume(stream,
-                        mAudioManager.getStreamMaxVolume(stream),
+        int muteAffectedStreams = System.getInt(mContext.getContentResolver(),
+                System.MUTE_STREAMS_AFFECTED,
+                // Same defaults as in AudioService. Should be kept in
+                // sync.
+                ((1 << AudioManager.STREAM_MUSIC) |
+                        (1 << AudioManager.STREAM_RING) |
+                        (1 << AudioManager.STREAM_NOTIFICATION) |
+                        (1 << AudioManager.STREAM_SYSTEM)));
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), true);
+        // This ensures we're out of vibrate or silent modes.
+        mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+        Utils.toggleNotificationPolicyAccess(
+                mContext.getPackageName(), getInstrumentation(), false);
+        for (int stream : streams) {
+            // ensure each stream is on and turned up.
+            mAudioManager.setStreamVolume(stream,
+                    mAudioManager.getStreamMaxVolume(stream),
+                    0);
+            if (((1 << stream) & muteAffectedStreams) == 0) {
+                mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
+                assertFalse("Stream " + stream + " should not be affected by mute.",
+                        mAudioManager.isStreamMute(stream));
+                mAudioManager.setStreamMute(stream, true);
+                assertFalse("Stream " + stream + " should not be affected by mute.",
+                        mAudioManager.isStreamMute(stream));
+                mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE,
                         0);
-                if (((1 << stream) & muteAffectedStreams) == 0) {
-                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
-                    assertFalse("Stream " + stream + " should not be affected by mute.",
-                            mAudioManager.isStreamMute(stream));
-                    mAudioManager.setStreamMute(stream, true);
-                    assertFalse("Stream " + stream + " should not be affected by mute.",
-                            mAudioManager.isStreamMute(stream));
-                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE,
-                            0);
-                    assertFalse("Stream " + stream + " should not be affected by mute.",
-                            mAudioManager.isStreamMute(stream));
-                    continue;
-                }
-                testStreamMuting(stream);
+                assertFalse("Stream " + stream + " should not be affected by mute.",
+                        mAudioManager.isStreamMute(stream));
+                continue;
             }
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
+            testStreamMuting(stream);
         }
     }
 
@@ -863,8 +833,6 @@
 
         } finally {
             setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
         }
     }
 
@@ -888,8 +856,6 @@
 
         } finally {
             setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
         }
     }
 
@@ -912,8 +878,6 @@
             assertEquals(7, mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
         } finally {
             setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
         }
     }
 
@@ -935,8 +899,6 @@
             assertEquals(7, mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
         } finally {
             setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
         }
     }
 
diff --git a/tests/tests/media/src/android/media/cts/Utils.java b/tests/tests/media/src/android/media/cts/Utils.java
index fb461fe..33cc1b7 100644
--- a/tests/tests/media/src/android/media/cts/Utils.java
+++ b/tests/tests/media/src/android/media/cts/Utils.java
@@ -27,7 +27,7 @@
 import android.os.HandlerThread;
 import android.os.ParcelFileDescriptor;
 import android.provider.Settings;
-
+import com.google.android.collect.Lists;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -87,44 +87,77 @@
 
     protected static void toggleNotificationPolicyAccess(String packageName,
             Instrumentation instrumentation, boolean on) throws IOException {
-        Context context = instrumentation.getContext();
+
+        // Read the setting listing the package allowed to manage notification policy configuration
+        String alreadyEnabledServices = querryNotificationPolicyAccessPakages(instrumentation);
+
+        // The property is a list of : separated package
+        List<String> enabledServices = Lists.newArrayList(alreadyEnabledServices.split(":"));
+
+        // Actually add or remove the package from the list
+        if (on) {
+            // Only add the package if it is not already in the list
+            if (!enabledServices.contains(packageName)) {
+                enabledServices.add(packageName);
+                setNotificationPolicyAccessPackages(enabledServices, instrumentation);
+            }
+        } else {
+            // Remove all instance of the package in the list
+            if (enabledServices.removeIf(packageName::equals)) {
+                // Only update the settings if there was a change
+                setNotificationPolicyAccessPackages(enabledServices, instrumentation);
+            }
+        }
+    }
+
+    /** Read the setting listing the package allowed to manage notification policy configuration */
+    private static String querryNotificationPolicyAccessPakages(Instrumentation instrumentation) {
+        ContentResolver cr = instrumentation.getContext().getContentResolver();
+        String enabledService = Settings.Secure.getString(
+                cr,Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
+
+        // A non existing property is equivalent to no package listed
+        if (enabledService == null) {
+            enabledService = "";
+        }
+        return enabledService;
+    }
+
+    private static void setNotificationPolicyAccessPackages(final List<String> enabledServicesList,
+            final Instrumentation instrumentation) throws IOException {
+        // Format the list back to a string
+        String enabledServices = String.join(":", enabledServicesList);
+
+        // If the list is empty, remove the property by setting it to null
+        String enabledServicesStrOrNull = enabledServices.isEmpty() ? "null" : enabledServices;
+
+        // Write back the property to the settings database
+        String command = "settings --user cur put secure "
+                + Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES + "  "
+                + enabledServicesStrOrNull;
 
         // Get permission to enable accessibility
         UiAutomation uiAutomation = instrumentation.getUiAutomation();
 
-        ContentResolver cr = context.getContentResolver();
-        String alreadyEnabledServices = Settings.Secure.getString(
-                cr, Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
-        ParcelFileDescriptor fd = null;
-        if (on) {
-            if ((alreadyEnabledServices == null) || !alreadyEnabledServices.contains(packageName)) {
-                // Change the settings to enable the media cts package
-                final String newEnabledServices = (alreadyEnabledServices == null) ? packageName
-                        : alreadyEnabledServices + ":" + packageName;
-                fd = uiAutomation.executeShellCommand(
-                        "settings --user cur put secure "
-                                + Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES + " "
-                                + newEnabledServices);
+        // Execute command
+        try (ParcelFileDescriptor fd = uiAutomation.executeShellCommand(command)) {
+            Assert.assertNotNull("Failed to execute shell command: " + command, fd);
+            // Wait for the command to finish by reading until EOF
+            try (InputStream in = new FileInputStream(fd.getFileDescriptor())) {
+                byte[] buffer = new byte[4096];
+                while (in.read(buffer) > 0) {}
+            } catch (IOException e) {
+                throw new IOException("Could not read stdout of command: " + command, e);
             }
-        } else if (alreadyEnabledServices != null) {
-            int index =  alreadyEnabledServices.indexOf(":" + packageName);
-            if (index >= 0) {
-                fd = uiAutomation.executeShellCommand(
-                        "settings --user cur put secure "
-                                + Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES + " "
-                                + alreadyEnabledServices.substring(0, index));
-            } else if (alreadyEnabledServices.equals(packageName)) {
-                // "packageName" is the only enabled service
-                fd = uiAutomation.executeShellCommand("settings --user cur put secure "
-                        + Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES + "  null");
-            }
+        } finally {
+            uiAutomation.destroy();
         }
-        if (fd != null) {
-            InputStream in = new FileInputStream(fd.getFileDescriptor());
-            byte[] buffer = new byte[4096];
-            while (in.read(buffer) > 0) ;
-        }
-        uiAutomation.destroy();
+
+        // Read the settings again to make sure it is updated
+        String nowEnabledServices = querryNotificationPolicyAccessPakages(instrumentation);
+        Assert.assertEquals("Wrote setting should be the same as the read one",
+                enabledServices, nowEnabledServices);
+
     }
 
     /**
diff --git a/tests/tests/mediastress/src/android/mediastress/cts/NativeMediaTest.java b/tests/tests/mediastress/src/android/mediastress/cts/NativeMediaTest.java
index 192f213..5e77162 100644
--- a/tests/tests/mediastress/src/android/mediastress/cts/NativeMediaTest.java
+++ b/tests/tests/mediastress/src/android/mediastress/cts/NativeMediaTest.java
@@ -70,10 +70,14 @@
         waitForNativeMediaLifeCycle(activity, true);
         Thread.sleep(PLAY_WAIT_TIME_MS); // let it play for some time
         for (int i = 0; i < NUMBER_PLAY_PAUSE_REPEATITIONS; i++) {
-            instrumentation.callActivityOnPause(activity);
+            instrumentation.runOnMainSync(() -> {
+                instrumentation.callActivityOnPause(activity);
+            });
             instrumentation.waitForIdleSync();
             waitForNativeMediaLifeCycle(activity, false);
-            instrumentation.callActivityOnResume(activity);
+            instrumentation.runOnMainSync(() -> {
+                instrumentation.callActivityOnResume(activity);
+            });
             waitForNativeMediaLifeCycle(activity, true);
             Thread.sleep(PLAY_WAIT_TIME_MS); // let it play for some time
         }
diff --git a/tests/tests/nativehardware/src/AHardwareBufferTest.cpp b/tests/tests/nativehardware/src/AHardwareBufferTest.cpp
index b3fa82b..d467929 100644
--- a/tests/tests/nativehardware/src/AHardwareBufferTest.cpp
+++ b/tests/tests/nativehardware/src/AHardwareBufferTest.cpp
@@ -53,10 +53,8 @@
         return BuildFailureMessage(desc.height, bufferDesc.height, "heights");
     if (bufferDesc.layers != desc.layers)
         return BuildFailureMessage(desc.layers, bufferDesc.layers, "layers");
-    if (bufferDesc.usage0 != desc.usage0)
-        return BuildHexFailureMessage(desc.usage0, bufferDesc.usage0, "usage0");
-    if (bufferDesc.usage1 != desc.usage1)
-        return BuildHexFailureMessage(desc.usage1, bufferDesc.usage1, "usage1");
+    if (bufferDesc.usage != desc.usage)
+        return BuildHexFailureMessage(desc.usage, bufferDesc.usage, "usage");
     if (bufferDesc.format != desc.format)
         return BuildFailureMessage(desc.format, bufferDesc.format, "formats");
     return ::testing::AssertionSuccess();
@@ -80,13 +78,12 @@
 // Test that passing in NULL values to allocate works as expected.
 TEST(AHardwareBufferTest, AHardwareBuffer_allocate_BlobFormatRequiresHeight1) {
     AHardwareBuffer* buffer;
-    AHardwareBuffer_Desc desc;
+    AHardwareBuffer_Desc desc = {};
 
     desc.width = 2;
     desc.height = 4;
     desc.layers = 1;
-    desc.usage0 = AHARDWAREBUFFER_USAGE0_CPU_READ;
-    desc.usage1 = 0;
+    desc.usage = AHARDWAREBUFFER_USAGE_CPU_READ_RARELY;
     desc.format = AHARDWAREBUFFER_FORMAT_BLOB;
     int res = AHardwareBuffer_allocate(&desc, &buffer);
     EXPECT_EQ(BAD_VALUE, res);
@@ -102,13 +99,12 @@
 // Test that allocate can create an AHardwareBuffer correctly.
 TEST(AHardwareBufferTest, AHardwareBuffer_allocate_Succeeds) {
     AHardwareBuffer* buffer = NULL;
-    AHardwareBuffer_Desc desc;
+    AHardwareBuffer_Desc desc = {};
 
     desc.width = 2;
     desc.height = 4;
     desc.layers = 1;
-    desc.usage0 = AHARDWAREBUFFER_USAGE0_GPU_SAMPLED_IMAGE;
-    desc.usage1 = 0;
+    desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
     desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
     int res = AHardwareBuffer_allocate(&desc, &buffer);
     EXPECT_EQ(NO_ERROR, res);
@@ -119,8 +115,7 @@
     desc.width = 4;
     desc.height = 12;
     desc.layers = 1;
-    desc.usage0 = AHARDWAREBUFFER_USAGE0_GPU_SAMPLED_IMAGE;
-    desc.usage1 = 0;
+    desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
     desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
     res = AHardwareBuffer_allocate(&desc, &buffer);
     EXPECT_EQ(NO_ERROR, res);
@@ -130,13 +125,12 @@
 
 TEST(AHardwareBufferTest, AHardwareBuffer_describe_Succeeds) {
     AHardwareBuffer* buffer = NULL;
-    AHardwareBuffer_Desc desc;
+    AHardwareBuffer_Desc desc = {};
 
     desc.width = 2;
     desc.height = 4;
     desc.layers = 1;
-    desc.usage0 = AHARDWAREBUFFER_USAGE0_GPU_SAMPLED_IMAGE;
-    desc.usage1 = 0;
+    desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
     desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
     int res = AHardwareBuffer_allocate(&desc, &buffer);
     EXPECT_EQ(NO_ERROR, res);
@@ -170,13 +164,12 @@
 
 TEST(AHardwareBufferTest, AHardwareBuffer_SendAndRecv_Succeeds) {
     AHardwareBuffer* buffer = NULL;
-    AHardwareBuffer_Desc desc;
+    AHardwareBuffer_Desc desc = {};
 
     desc.width = 2;
     desc.height = 4;
     desc.layers = 1;
-    desc.usage0 = AHARDWAREBUFFER_USAGE0_GPU_SAMPLED_IMAGE;
-    desc.usage1 = 0;
+    desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
     desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
 
     // Test that an invalid buffer fails.
@@ -219,14 +212,12 @@
 
 TEST(AHardwareBufferTest, AHardwareBuffer_Lock_and_Unlock_Succeed) {
     AHardwareBuffer* buffer = NULL;
-    AHardwareBuffer_Desc desc;
+    AHardwareBuffer_Desc desc = {};
 
     desc.width = 2;
     desc.height = 4;
     desc.layers = 1;
-    desc.usage0 = AHARDWAREBUFFER_USAGE0_GPU_SAMPLED_IMAGE |
-            AHARDWAREBUFFER_USAGE0_CPU_READ;
-    desc.usage1 = 0;
+    desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY;
     desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
 
     // Test that an invalid buffer fails.
@@ -238,7 +229,7 @@
     err = AHardwareBuffer_allocate(&desc, &buffer);
     EXPECT_EQ(NO_ERROR, err);
     void* bufferData = NULL;
-    err = AHardwareBuffer_lock(buffer, AHARDWAREBUFFER_USAGE0_CPU_READ, -1,
+    err = AHardwareBuffer_lock(buffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1,
           NULL, &bufferData);
     EXPECT_EQ(NO_ERROR, err);
     EXPECT_TRUE(bufferData != NULL);
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index 83f087b..b951378 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -437,7 +437,7 @@
         final TestNetworkCallback callback = new TestNetworkCallback();
         mCm.requestNetwork(new NetworkRequest.Builder()
                 .addTransportType(TRANSPORT_WIFI)
-                .build(), 100, callback);
+                .build(), callback, 100);
 
         try {
             // Wait to get callback for unavailability of requested network
diff --git a/tests/tests/net/src/android/net/cts/IpSecManagerTest.java b/tests/tests/net/src/android/net/cts/IpSecManagerTest.java
deleted file mode 100644
index bcecee1..0000000
--- a/tests/tests/net/src/android/net/cts/IpSecManagerTest.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net.cts;
-
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.IpSecAlgorithm;
-import android.net.IpSecManager;
-import android.net.IpSecTransform;
-import android.os.ParcelFileDescriptor;
-import android.system.Os;
-import android.system.OsConstants;
-import android.test.AndroidTestCase;
-import java.io.ByteArrayOutputStream;
-import java.net.DatagramSocket;
-import java.io.FileDescriptor;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Arrays;
-
-public class IpSecManagerTest extends AndroidTestCase {
-
-    private static final String TAG = IpSecManagerTest.class.getSimpleName();
-
-    private IpSecManager mISM;
-
-    private ConnectivityManager mCM;
-
-    private static final InetAddress GOOGLE_DNS_4;
-    private static final InetAddress GOOGLE_DNS_6;
-
-    static {
-        try {
-            // Google Public DNS Addresses;
-            GOOGLE_DNS_4 = InetAddress.getByName("8.8.8.8");
-            GOOGLE_DNS_6 = InetAddress.getByName("2001:4860:4860::8888");
-        } catch (UnknownHostException e) {
-            throw new RuntimeException("Could not resolve DNS Addresses", e);
-        }
-    }
-
-    private static final InetAddress[] GOOGLE_DNS_LIST =
-            new InetAddress[] {GOOGLE_DNS_4, GOOGLE_DNS_6};
-
-    private static final int DROID_SPI = 0xD1201D;
-
-    private static final byte[] CRYPT_KEY =
-            new byte[] {
-                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
-                0x0E, 0x0F
-            };
-    private static final byte[] AUTH_KEY =
-            new byte[] {
-                0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                0x00, 0x7F
-            };
-
-    protected void setUp() throws Exception {
-        super.setUp();
-        mCM = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
-        mISM = (IpSecManager) getContext().getSystemService(Context.IPSEC_SERVICE);
-    }
-
-    /*
-     * Allocate a random SPI
-     * Allocate a specific SPI using previous randomly created SPI value
-     * Realloc the same SPI that was specifically created (expect SpiUnavailable)
-     * Close SPIs
-     */
-    public void testAllocSpi() throws Exception {
-        for (InetAddress addr : GOOGLE_DNS_LIST) {
-            IpSecManager.SecurityParameterIndex randomSpi = null, droidSpi = null;
-            randomSpi = mISM.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, addr);
-            assertTrue(
-                    "Failed to receive a valid SPI",
-                    randomSpi.getSpi() != IpSecManager.INVALID_SECURITY_PARAMETER_INDEX);
-
-            droidSpi =
-                    mISM.reserveSecurityParameterIndex(
-                            IpSecTransform.DIRECTION_IN, addr, DROID_SPI);
-            assertTrue(
-                    "Failed to allocate specified SPI, " + DROID_SPI,
-                    droidSpi.getSpi() == DROID_SPI);
-
-            try {
-                mISM.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_IN, addr, DROID_SPI);
-                fail("Duplicate SPI was allowed to be created");
-            } catch (IpSecManager.SpiUnavailableException expected) {
-                // This is a success case because we expect a dupe SPI to throw
-            }
-
-            randomSpi.close();
-            droidSpi.close();
-        }
-    }
-
-    /*
-     * Alloc outbound SPI
-     * Alloc inbound SPI
-     * Create transport mode transform
-     * open socket
-     * apply transform to socket
-     * send data on socket
-     * release transform
-     * send data (expect exception)
-     */
-    public void testCreateTransform() throws Exception {
-        InetAddress local = InetAddress.getLoopbackAddress();
-        IpSecManager.SecurityParameterIndex outSpi =
-                mISM.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, local);
-
-        IpSecManager.SecurityParameterIndex inSpi =
-                mISM.reserveSecurityParameterIndex(
-                        IpSecTransform.DIRECTION_IN, local, outSpi.getSpi());
-
-        IpSecTransform transform =
-                new IpSecTransform.Builder(mContext)
-                        .setSpi(IpSecTransform.DIRECTION_OUT, outSpi)
-                        .setEncryption(
-                                IpSecTransform.DIRECTION_OUT,
-                                new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, CRYPT_KEY))
-                        .setAuthentication(
-                                IpSecTransform.DIRECTION_OUT,
-                                new IpSecAlgorithm(
-                                        IpSecAlgorithm.AUTH_HMAC_SHA256,
-                                        AUTH_KEY,
-                                        AUTH_KEY.length * 8))
-                        .setSpi(IpSecTransform.DIRECTION_IN, inSpi)
-                        .setEncryption(
-                                IpSecTransform.DIRECTION_IN,
-                                new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, CRYPT_KEY))
-                        .setAuthentication(
-                                IpSecTransform.DIRECTION_IN,
-                                new IpSecAlgorithm(
-                                        IpSecAlgorithm.AUTH_HMAC_SHA256,
-                                        AUTH_KEY,
-                                        CRYPT_KEY.length * 8))
-                        .buildTransportModeTransform(local);
-
-        // Hack to ensure the socket doesn't block indefinitely on failure
-        DatagramSocket localSocket = new DatagramSocket(8888);
-        localSocket.setSoTimeout(500);
-        ParcelFileDescriptor pin = ParcelFileDescriptor.fromDatagramSocket(localSocket);
-        FileDescriptor udpSocket = pin.getFileDescriptor();
-
-        mISM.applyTransportModeTransform(udpSocket, transform);
-        byte[] data = new String("Best test data ever!").getBytes("UTF-8");
-
-        byte[] in = new byte[data.length];
-        Os.sendto(udpSocket, data, 0, data.length, 0, local, 8888);
-        Os.read(udpSocket, in, 0, in.length);
-        assertTrue("Encapsulated data did not match.", Arrays.equals(data, in));
-        mISM.removeTransportModeTransform(udpSocket, transform);
-        Os.close(udpSocket);
-        transform.close();
-    }
-}
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index d489a6a..c9650bd 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -33,6 +33,7 @@
 
 import junit.framework.TestCase;
 
+import static android.os.Build.VERSION.CODENAME;
 import static android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
 
 public class BuildTest extends TestCase {
@@ -223,21 +224,7 @@
         assertTrue(TYPE_PATTERN.matcher(Build.TYPE).matches());
 
         assertNotEmpty(Build.USER);
-    }
 
-    public void testBuildConstants_forPrereleaseOrRelease() {
-        checkBuildConstants(CUR_DEVELOPMENT);
-    }
-
-    @RestrictedBuildTest // Expected to fail on prelease/dev builds, http://b/35922665
-    public void testBuildConstants_forRelease() {
-        checkBuildConstants(CUR_DEVELOPMENT - 1);
-    }
-
-    /**
-     * @param maxAllowedValue the maximum permitted value for constants other than CUR_DEVELOPMENT
-     */
-    private static void checkBuildConstants(int maxAllowedValue) {
         // CUR_DEVELOPMENT must be larger than any released version.
         Field[] fields = Build.VERSION_CODES.class.getDeclaredFields();
         for (Field field : fields) {
@@ -253,9 +240,12 @@
                     // It should be okay to change the value of this constant in future, but it
                     // should at least be a conscious decision.
                     assertEquals(10000, fieldValue);
+                } else if (fieldName.equals(CODENAME) && !CODENAME.equals("REL")) {
+                    // This is the current development version.
+                    assertEquals(CUR_DEVELOPMENT, fieldValue);
                 } else {
-                    assertTrue("Expected " + fieldName + " value to be <= " + maxAllowedValue
-                            + ", got " + fieldValue, fieldValue <= maxAllowedValue);
+                    assertTrue("Expected " + fieldName + " value to be < " + CUR_DEVELOPMENT
+                            + ", got " + fieldValue, fieldValue < CUR_DEVELOPMENT);
                 }
             }
         }
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index 58cac14..3564b21 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -37,7 +37,6 @@
     <protected-broadcast android:name="android.intent.action.BOOT_COMPLETED" />
     <protected-broadcast android:name="android.intent.action.PACKAGE_INSTALL" />
     <protected-broadcast android:name="android.intent.action.PACKAGE_ADDED" />
-    <protected-broadcast android:name="android.intent.action.PACKAGE_FIRST_ADDED" />
     <protected-broadcast android:name="android.intent.action.PACKAGE_REPLACED" />
     <protected-broadcast android:name="android.intent.action.MY_PACKAGE_REPLACED" />
     <protected-broadcast android:name="android.intent.action.PACKAGE_REMOVED" />
@@ -127,6 +126,7 @@
     <protected-broadcast android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
     <protected-broadcast android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED" />
     <protected-broadcast android:name="android.bluetooth.adapter.action.LOCAL_NAME_CHANGED" />
+    <protected-broadcast android:name="android.bluetooth.adapter.action.BLUETOOTH_ADDRESS_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.device.action.UUID" />
     <protected-broadcast android:name="android.bluetooth.device.action.MAS_INSTANCE" />
@@ -285,7 +285,6 @@
     <protected-broadcast android:name="android.btopp.intent.action.STOP_HANDOVER_TRANSFER" />
     <protected-broadcast android:name="android.nfc.handover.intent.action.HANDOVER_SEND" />
     <protected-broadcast android:name="android.nfc.handover.intent.action.HANDOVER_SEND_MULTIPLE" />
-    <protected-broadcast android:name="com.android.nfc.handover.action.CANCEL_HANDOVER_TRANSFER" />
 
     <protected-broadcast android:name="android.intent.action.CLEAR_DNS_CACHE" />
     <protected-broadcast android:name="android.intent.action.PROXY_CHANGE" />
@@ -1670,21 +1669,6 @@
     <permission android:name="android.permission.BIND_IMS_SERVICE"
         android:protectionLevel="signature|privileged" />
 
-    <!-- Allows an application to manage embedded subscriptions (those on a eUICC) through
-         EuiccManager APIs.
-         <p>Protection level: signature|privileged|development
-         TODO(b/35851809): Mark this as a SystemApi.
-         @hide -->
-    <permission android:name="android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS"
-                android:protectionLevel="signature|privileged|development" />
-
-    <!-- Must be required by an EuiccService to ensure that only the system can bind to it.
-         <p>Protection level: signature
-         TODO(b/35851809): Mark this as a SystemApi.
-         @hide -->
-    <permission android:name="android.permission.BIND_EUICC_SERVICE"
-                android:protectionLevel="signature" />
-
 
     <!-- ================================== -->
     <!-- Permissions for sdcard interaction -->
@@ -1892,11 +1876,6 @@
         android:description="@string/permdesc_useDataInBackground"
         android:protectionLevel="signature" />
 
-    <!-- @hide Allows an application to set display offsets for the screen.
-         This permission is not available to third party applications. -->
-    <permission android:name="android.permission.SET_DISPLAY_OFFSET"
-                android:protectionLevel="signature|privileged" />
-
     <!-- ================================== -->
     <!-- Permissions affecting the system wallpaper -->
     <!-- ================================== -->
@@ -2506,13 +2485,11 @@
          to ensure that only the system can bind to it.
          <p>Protection level: signature
     -->
-    <permission android:name="android.permission.BIND_AUTOFILL"
+    <permission android:name="android.permission.BIND_AUTOFILL_SERVICE"
         android:protectionLevel="signature" />
 
-    <!--  TODO(b/35956626): temporary until clients change to BIND_AUTOFILL
-         <p>Protection level: signature
-    -->
-    <permission android:name="android.permission.BIND_AUTO_FILL"
+    <!-- @hide TODO(b/37563972): remove once clients use BIND_AUTOFILL_SERVICE -->
+    <permission android:name="android.permission.BIND_AUTOFILL"
         android:protectionLevel="signature" />
 
     <!-- Must be required by hotword enrollment application,
@@ -3182,6 +3159,14 @@
     <permission android:name="android.permission.BIND_CHOOSER_TARGET_SERVICE"
         android:protectionLevel="signature" />
 
+    <!-- @SystemApi Must be held by services that extend
+         {@link android.service.resolver.ResolverRankerService}.
+         <p>Protection level: signature|privileged
+         @hide
+    -->
+    <permission android:name="android.permission.PROVIDE_RESOLVER_RANKER_SERVICE"
+                android:protectionLevel="signature|privileged" />
+
     <!-- @SystemApi Must be required by services that extend
          {@link android.service.resolver.ResolverRankerService}, to ensure that only the system can
          bind to them.
@@ -3191,14 +3176,6 @@
     <permission android:name="android.permission.BIND_RESOLVER_RANKER_SERVICE"
                 android:protectionLevel="signature" />
 
-    <!-- @SystemApi Must be held by services that extend
-         {@link android.service.resolver.ResolverRankerService}.
-         <p>Protection level: signature|privileged
-         @hide
-    -->
-    <permission android:name="android.permission.PROVIDE_RESOLVER_RANKER_SERVICE"
-                android:protectionLevel="signature|privileged" />
-
     <!-- Must be required by a {@link
          android.service.notification.ConditionProviderService},
          to ensure that only the system can bind to it.
@@ -3653,6 +3630,22 @@
             </intent-filter>
         </receiver>
 
+        <receiver android:name="com.android.server.updates.LangIdInstallReceiver"
+                  android:permission="android.permission.UPDATE_CONFIG">
+            <intent-filter>
+                <action android:name="android.intent.action.UPDATE_LANG_ID" />
+                <data android:scheme="content" android:host="*" android:mimeType="*/*" />
+            </intent-filter>
+        </receiver>
+
+        <receiver android:name="com.android.server.updates.SmartSelectionInstallReceiver"
+                  android:permission="android.permission.UPDATE_CONFIG">
+            <intent-filter>
+                <action android:name="android.intent.action.UPDATE_SMART_SELECTION" />
+                <data android:scheme="content" android:host="*" android:mimeType="*/*" />
+            </intent-filter>
+        </receiver>
+
         <receiver android:name="com.android.server.MasterClearReceiver"
             android:permission="android.permission.MASTER_CLEAR">
             <intent-filter
@@ -3715,7 +3708,6 @@
         <service android:name="com.android.server.PreloadsFileCacheExpirationJobService"
                  android:permission="android.permission.BIND_JOB_SERVICE" >
         </service>
-
     </application>
 
 </manifest>
diff --git a/tests/tests/preference2/src/android/preference2/cts/PreferenceDataStoreTest.java b/tests/tests/preference2/src/android/preference2/cts/PreferenceDataStoreTest.java
index 2e30e0c..8e521b9 100644
--- a/tests/tests/preference2/src/android/preference2/cts/PreferenceDataStoreTest.java
+++ b/tests/tests/preference2/src/android/preference2/cts/PreferenceDataStoreTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.AdditionalMatchers.or;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyBoolean;
@@ -35,9 +36,11 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
 
 import android.content.Context;
 import android.content.SharedPreferences;
+import android.preference.CheckBoxPreference;
 import android.preference.Preference;
 import android.preference.PreferenceDataStore;
 import android.preference.PreferenceManager;
@@ -149,6 +152,40 @@
         assertEquals(TEST_DEFAULT_STR, mPreference.defaultValue);
     }
 
+    /**
+     * Test that the initial value is taken from the data store (before the preference gets assigned
+     * to the preference hierarchy).
+     */
+    @Test
+    public void testInitialValueIsTakenFromDSOnPref() {
+        when(mDataStore.getBoolean(anyString(), anyBoolean())).thenReturn(true);
+
+        CheckBoxPreference pref = new CheckBoxPreference(mActivityRule.getActivity());
+        pref.setKey("CheckboxTestPref");
+        pref.setPreferenceDataStore(mDataStore);
+
+        mScreen.addPreference(pref);
+
+        assertTrue(pref.isChecked());
+    }
+
+    /**
+     * Test that the initial value is taken from the data store (before the preference gets assigned
+     * to the preference hierarchy).
+     */
+    @Test
+    public void testInitialValueIsTakenFromDSOnMgr() {
+        when(mDataStore.getBoolean(anyString(), anyBoolean())).thenReturn(true);
+        mManager.setPreferenceDataStore(mDataStore);
+
+        CheckBoxPreference pref = new CheckBoxPreference(mActivityRule.getActivity());
+        pref.setKey("CheckboxTestPref");
+
+        mScreen.addPreference(pref);
+
+        assertTrue(pref.isChecked());
+    }
+
     @Test
     public void testPutStringSetWithDataStoreOnPref() {
         mPreference.setPreferenceDataStore(mDataStore);
diff --git a/tests/tests/preference2/src/android/preference2/cts/PreferenceParentGroupTest.java b/tests/tests/preference2/src/android/preference2/cts/PreferenceParentGroupTest.java
index 5de6e81..a645dc8 100644
--- a/tests/tests/preference2/src/android/preference2/cts/PreferenceParentGroupTest.java
+++ b/tests/tests/preference2/src/android/preference2/cts/PreferenceParentGroupTest.java
@@ -26,6 +26,7 @@
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
+import android.test.UiThreadTest;
 
 import org.junit.Before;
 import org.junit.Rule;
@@ -56,6 +57,7 @@
      * from code.
      */
     @Test
+    @UiThreadTest
     public void parentViaCodeTest() {
         PreferenceScreen screen = mActivity.getPreferenceScreen();
         assertNull(screen.getParent());
@@ -84,6 +86,7 @@
      * To see the tested hierarchy check pref_nested.xml.
      */
     @Test
+    @UiThreadTest
     public void parentViaInflationTest() {
         PreferenceScreen screen = mActivity.getPreferenceScreen();
 
@@ -112,6 +115,7 @@
      * Adds preference into two different groups without removing it first.
      */
     @Test
+    @UiThreadTest
     public void parentDoubleAddTest() throws InterruptedException {
         PreferenceScreen screen = mActivity.getPreferenceScreen();
 
diff --git a/tests/tests/graphics/src/android/graphics/fonts/cts/FontRequestTest.java b/tests/tests/provider/src/android/provider/cts/FontRequestTest.java
similarity index 62%
rename from tests/tests/graphics/src/android/graphics/fonts/cts/FontRequestTest.java
rename to tests/tests/provider/src/android/provider/cts/FontRequestTest.java
index 1b00975..d9b8a7f 100644
--- a/tests/tests/graphics/src/android/graphics/fonts/cts/FontRequestTest.java
+++ b/tests/tests/provider/src/android/provider/cts/FontRequestTest.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package android.graphics.fonts.cts;
+package android.provider.cts;
 
 import static junit.framework.Assert.assertNotNull;
 import static junit.framework.Assert.assertNull;
@@ -22,7 +22,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
-import android.graphics.fonts.FontRequest;
+import android.provider.FontRequest;
 import android.os.Parcel;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
@@ -35,7 +35,7 @@
 import java.util.List;
 
 /**
- * Tests for {@link android.graphics.fonts.FontRequest}.
+ * Tests for {@link android.provider.FontRequest}.
  */
 @SmallTest
 @RunWith(AndroidJUnit4.class)
@@ -47,46 +47,6 @@
             Base64.decode("e04fd020ea3a6910a2d808002b30", Base64.DEFAULT);
     private static final List<List<byte[]>> CERTS = Arrays.asList(Arrays.asList(BYTE_ARRAY));
 
-    @Test
-    public void testWriteToParcel() {
-        // GIVEN a FontRequest created with the long constructor
-        FontRequest request = new FontRequest(PROVIDER, PACKAGE, QUERY, CERTS);
-
-        // WHEN we write it to a Parcel
-        Parcel dest = Parcel.obtain();
-        request.writeToParcel(dest, 0);
-        dest.setDataPosition(0);
-
-        // THEN we create from that parcel and get the same values.
-        FontRequest result = FontRequest.CREATOR.createFromParcel(dest);
-        assertEquals(PROVIDER, result.getProviderAuthority());
-        assertEquals(PACKAGE, result.getProviderPackage());
-        assertEquals(QUERY, result.getQuery());
-        assertEquals(CERTS.size(), result.getCertificates().size());
-        List<byte[]> cert = CERTS.get(0);
-        List<byte[]> resultCert = result.getCertificates().get(0);
-        assertEquals(cert.size(), resultCert.size());
-        assertTrue(Arrays.equals(cert.get(0), resultCert.get(0)));
-    }
-
-    @Test
-    public void testWriteToParcel_shortConstructor() {
-        // GIVEN a FontRequest created with the short constructor
-        FontRequest request = new FontRequest(PROVIDER, PACKAGE, QUERY);
-
-        // WHEN we write it to a Parcel
-        Parcel dest = Parcel.obtain();
-        request.writeToParcel(dest, 0);
-        dest.setDataPosition(0);
-
-        // THEN we create from that parcel and get the same values.
-        FontRequest result = FontRequest.CREATOR.createFromParcel(dest);
-        assertEquals(PROVIDER, result.getProviderAuthority());
-        assertEquals(PACKAGE, result.getProviderPackage());
-        assertEquals(QUERY, result.getQuery());
-        assertNotNull(result.getCertificates());
-        assertEquals(0, result.getCertificates().size());
-    }
 
     @Test(expected = NullPointerException.class)
     public void testShortConstructor_nullAuthority() {
diff --git a/tests/tests/provider/src/android/provider/cts/FontsContractTest.java b/tests/tests/provider/src/android/provider/cts/FontsContractTest.java
index 472aed8..745a490 100644
--- a/tests/tests/provider/src/android/provider/cts/FontsContractTest.java
+++ b/tests/tests/provider/src/android/provider/cts/FontsContractTest.java
@@ -29,8 +29,8 @@
 import android.content.pm.PackageInfo;
 import android.content.Context;
 import android.graphics.Typeface;
-import android.graphics.fonts.FontRequest;
 import android.graphics.fonts.FontVariationAxis;
+import android.provider.FontRequest;
 import android.provider.FontsContract;
 import android.provider.FontsContract.FontFamilyResult;
 import android.provider.FontsContract.FontInfo;
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java b/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
index 2ca4f13..ec5e781 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/RSBase.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.content.res.Resources;
+import android.os.StrictMode;
 import android.renderscript.RenderScript.RSErrorHandler;
 import android.renderscript.RenderScript.RSMessageHandler;
 import android.renderscript.RSRuntimeException;
@@ -80,6 +81,12 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+
+        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
+                               .detectLeakedClosableObjects()
+                               .penaltyLog()
+                               .build());
+
         result = 0;
         msgHandled = false;
         mCtx = getContext();
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/refocus/ImageBuffersForRenderScript.java b/tests/tests/renderscript/src/android/renderscript/cts/refocus/ImageBuffersForRenderScript.java
index 9078764..fa7def6 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/refocus/ImageBuffersForRenderScript.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/refocus/ImageBuffersForRenderScript.java
@@ -56,4 +56,9 @@
     imageWidthPadded = inputImage.getWidth() + 2 * margin;
     imageHeightPadded = inputImage.getHeight() + 2 * margin;
   }
+
+  public void destroy() {
+    inAllocation.destroy();
+    outAllocation.destroy();
+  }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/refocus/RenderScriptTask.java b/tests/tests/renderscript/src/android/renderscript/cts/refocus/RenderScriptTask.java
index 29436c6..1f812a1 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/refocus/RenderScriptTask.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/refocus/RenderScriptTask.java
@@ -105,11 +105,13 @@
         RefocusFilterF32 rfFilterF32 = new RefocusFilterF32(renderScript);
         outputImage =
                 rfFilterF32.compute(rgbdImage, blurStack);
+        rfFilterF32.destroy();
         break;
       case d1new:
         RefocusFilterd1new rfFilterd1new = new RefocusFilterd1new(renderScript);
         outputImage =
                 rfFilterd1new.compute(rgbdImage, blurStack);
+        rfFilterd1new.destroy();
         break;
     }
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/ImageBuffersForRenderScriptd1new.java b/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/ImageBuffersForRenderScriptd1new.java
index ac67ef6..4068d1e 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/ImageBuffersForRenderScriptd1new.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/ImageBuffersForRenderScriptd1new.java
@@ -47,6 +47,17 @@
   public Allocation sharpActiveAllocation;
   public Allocation sharpMatteAllocation;
 
+  public void destroy() {
+      super.destroy();
+    sharpRGBAAllocation.destroy();
+    fuzzyRGBAAllocation.destroy();
+    integralRGBAAllocation.destroy();
+    sharpActualDepthAllocation.destroy();
+    sharpDilatedDepthAllocation.destroy();
+    sharpActiveAllocation.destroy();
+    sharpMatteAllocation.destroy();
+  }
+
   /**
    * A constructor that allocates memory buffers in Java and binds the buffers
    * with the global pointers in the Render Script.
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/RefocusFilterd1new.java b/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/RefocusFilterd1new.java
index 52bc4de..0981a54 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/RefocusFilterd1new.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/refocus/d1new/RefocusFilterd1new.java
@@ -48,11 +48,19 @@
   private static final float MIN_DISC_RADIUS_FOR_FAST_FILTER = 3;
   boolean useFastFilterForCurrentLayer = false;
   ImageBuffersForRenderScriptd1new buffers;
+  Allocation kernelInfo, kernelStack;
 
   public RefocusFilterd1new(RenderScript rs) {
     super(rs);
   }
 
+  public void destroy() {
+    buffers.destroy();
+    kernelInfo.destroy();
+    kernelStack.destroy();
+    scriptC.destroy();
+  }
+
   @Override
   protected void initializeScriptAndBuffers(Bitmap inputImage,
       LayerInfo focalLayer) {
@@ -93,6 +101,7 @@
     scriptC.forEach_PackSharpImage(mAllocation);
 
     mAllocation.copyTo(mBitmap);
+    mAllocation.destroy();
     MediaStoreSaver.savePNG(mBitmap, "sharpd1new", name, renderScript.getApplicationContext());
   }
   /*
@@ -106,6 +115,7 @@
     scriptC.forEach_PackFuzzyImage(mAllocation);
 
     mAllocation.copyTo(mBitmap);
+    mAllocation.destroy();
     MediaStoreSaver.savePNG(mBitmap, "fuzzyd1new", name, renderScript.getApplicationContext());
   }
 
@@ -132,6 +142,14 @@
     }
     scriptC.set_g_kernel_stack(kernelData.stackAllocation);
     scriptC.set_galloc_kernel_info(kernelData.infoAllocation);
+    if (kernelInfo != null) {
+      kernelInfo.destroy();
+    }
+    kernelInfo = kernelData.infoAllocation;
+    if (kernelStack != null) {
+      kernelStack.destroy();
+    }
+    kernelStack = kernelData.stackAllocation;
   }
 
   @Override
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/ImageBuffersForRenderScriptF32.java b/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/ImageBuffersForRenderScriptF32.java
index 53e6e55..33c4d21 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/ImageBuffersForRenderScriptF32.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/ImageBuffersForRenderScriptF32.java
@@ -41,6 +41,12 @@
   public Allocation fuzzyImageAllocation;
   public Allocation integralImageAllocation;
 
+  public void destroy() {
+    sharpImageAllocation.destroy();
+    fuzzyImageAllocation.destroy();
+    integralImageAllocation.destroy();
+  }
+
   /**
    * A constructor that allocates memory buffers in Java and binds the buffers
    * with the global pointers in the Render Script.
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/RefocusFilterF32.java b/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/RefocusFilterF32.java
index f819a72..e4f8ff9 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/RefocusFilterF32.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/refocus/f32/RefocusFilterF32.java
@@ -56,6 +56,11 @@
     super(rs);
   }
 
+  public void destroy() {
+    buffers.destroy();
+    scriptC.destroy();
+  }
+
   @Override
   protected void initializeScriptAndBuffers(Bitmap inputImage,
       LayerInfo focalLayer) {
@@ -96,6 +101,7 @@
     scriptC.forEach_PackSharpImage(mAllocation);
 
     mAllocation.copyTo(mBitmap);
+    mAllocation.destroy();
     MediaStoreSaver.savePNG(mBitmap, "sharpF32", name, renderScript.getApplicationContext());
     mAllocation.destroy();
   }
@@ -110,6 +116,7 @@
     scriptC.forEach_PackFuzzyImage(mAllocation);
 
     mAllocation.copyTo(mBitmap);
+    mAllocation.destroy();
     MediaStoreSaver.savePNG(mBitmap, "fuzzyF32", name, renderScript.getApplicationContext());
     mAllocation.destroy();
   }
diff --git a/tests/tests/security/res/raw/bug_34097672.mp4 b/tests/tests/security/res/raw/bug_34097672.mp4
new file mode 100644
index 0000000..79acdf4
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_34097672.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_34360591.mp4 b/tests/tests/security/res/raw/bug_34360591.mp4
new file mode 100644
index 0000000..28c47d3
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_34360591.mp4
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
index f120426..031b9f7 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -73,6 +73,10 @@
      before any existing test methods
      ***********************************************************/
 
+    public void testStagefright_bug_34360591() throws Exception {
+        doStagefrightTest(R.raw.bug_34360591);
+    }
+
     public void testStagefright_bug_35763994() throws Exception {
         doStagefrightTest(R.raw.bug_35763994);
     }
@@ -183,6 +187,11 @@
      ***********************************************************/
 
     @SecurityTest
+    public void testStagefright_bug_34097672() throws Exception {
+        doStagefrightTest(R.raw.bug_34097672);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_33818508() throws Exception {
         doStagefrightTest(R.raw.bug_33818508);
     }
diff --git a/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java b/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java
index 872820a..3920bcf 100644
--- a/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java
+++ b/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java
@@ -88,18 +88,18 @@
     }
 
     @After
-    public void cleanup() {
+    public void cleanup() throws Throwable {
         if (TargetActivity.sLastCreated != null) {
-            mInstrumentation.runOnMainSync(() -> TargetActivity.sLastCreated.finish());
+            mActivityRule.runOnUiThread(() -> TargetActivity.sLastCreated.finish());
         }
         TargetActivity.sLastCreated = null;
     }
 
     // When using ActivityOptions.makeBasic(), no transitions should run
     @Test
-    public void testMakeBasic() {
+    public void testMakeBasic() throws Throwable {
         assertFalse(mActivity.isActivityTransitionRunning());
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             Intent intent = new Intent(mActivity, TargetActivity.class);
             ActivityOptions activityOptions =
                     ActivityOptions.makeBasic();
@@ -110,7 +110,7 @@
 
         TargetActivity targetActivity = waitForTargetActivity();
         assertFalse(targetActivity.isActivityTransitionRunning());
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             targetActivity.finish();
         });
 
@@ -123,7 +123,7 @@
     @Test
     public void viewsNotStripped() throws Throwable {
         enterScene(R.layout.scene10);
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             View sharedElement = mActivity.findViewById(R.id.blueSquare);
             Bundle options = ActivityOptions.makeSceneTransitionAnimation(mActivity,
                     sharedElement, "holder").toBundle();
@@ -156,7 +156,7 @@
         assertEquals(1, targetActivity.findViewById(R.id.greenSquare).getAlpha(), 0.01f);
         assertEquals(1, targetActivity.findViewById(R.id.holder).getAlpha(), 0.01f);
 
-        mInstrumentation.runOnMainSync(() -> targetActivity.finishAfterTransition());
+        mActivityRule.runOnUiThread(() -> targetActivity.finishAfterTransition());
         verify(mReenterListener, within(3000)).onTransitionEnd(any());
         verify(mSharedElementReenterListener, within(3000)).onTransitionEnd(any());
         verify(targetActivity.returnListener, times(1)).onTransitionEnd(any());
@@ -195,7 +195,7 @@
     @Test
     public void viewsStripped() throws Throwable {
         enterScene(R.layout.scene13);
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             View sharedElement = mActivity.findViewById(R.id.redSquare);
             Bundle options = ActivityOptions.makeSceneTransitionAnimation(mActivity,
                     sharedElement, "redSquare").toBundle();
@@ -227,7 +227,7 @@
         assertEquals(1, targetActivity.findViewById(R.id.greenSquare).getAlpha(), 0.01f);
         assertEquals(1, targetActivity.findViewById(R.id.holder).getAlpha(), 0.01f);
 
-        mInstrumentation.runOnMainSync(() -> targetActivity.finishAfterTransition());
+        mActivityRule.runOnUiThread(() -> targetActivity.finishAfterTransition());
         verify(mReenterListener, within(3000)).onTransitionEnd(any());
         verify(mSharedElementReenterListener, within(3000)).onTransitionEnd(any());
         verify(targetActivity.returnListener, times(1)).onTransitionEnd(any());
@@ -267,7 +267,7 @@
         final View hello = mActivity.findViewById(R.id.hello);
         final View red = mActivity.findViewById(R.id.redSquare);
         final View green = mActivity.findViewById(R.id.greenSquare);
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             Fade fade = new Fade();
             fade.setDuration(10000);
             fade.addListener(mExitListener);
@@ -282,7 +282,7 @@
         verify(targetActivity.enterListener, within(3000)).onTransitionEnd(any());
         verify(mExitListener, within(3000)).onTransitionEnd(any());
 
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             // Verify that the exited views have an alpha of 1 and are visible
             assertEquals(1.0f, hello.getAlpha(), 0.01f);
             assertEquals(1.0f, red.getAlpha(), 0.01f);
@@ -296,9 +296,9 @@
     }
 
     @Test
-    public void testAnimationQuery() {
+    public void testAnimationQuery() throws Throwable {
         assertFalse(mActivity.isActivityTransitionRunning());
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             mActivity.getWindow().setExitTransition(new Fade());
             Intent intent = new Intent(mActivity, TargetActivity.class);
             ActivityOptions activityOptions =
@@ -310,12 +310,19 @@
 
         TargetActivity targetActivity = waitForTargetActivity();
         assertTrue(targetActivity.isActivityTransitionRunning());
-        mInstrumentation.runOnMainSync(() -> {
-            targetActivity.finish();
+        mActivityRule.runOnUiThread(() -> { });
+        PollingCheck.waitFor(() -> !targetActivity.isActivityTransitionRunning());
+
+        assertFalse(mActivity.isActivityTransitionRunning());
+        mActivityRule.runOnUiThread(() -> {
+            targetActivity.finishAfterTransition();
+            // The target activity transition should start right away
+            assertTrue(targetActivity.isActivityTransitionRunning());
         });
 
-        assertTrue(targetActivity.isActivityTransitionRunning());
-        assertTrue(mActivity.isActivityTransitionRunning());
+        // The source activity transition should start sometime later
+        PollingCheck.waitFor(() -> mActivity.isActivityTransitionRunning());
+        PollingCheck.waitFor(() -> !mActivity.isActivityTransitionRunning());
     }
 
     // Views that are excluded from the exit/enter transition shouldn't change visibility
@@ -380,10 +387,10 @@
         TargetActivity.sLastCreated = null;
     }
 
-    private TargetActivity waitForTargetActivity() {
+    private TargetActivity waitForTargetActivity() throws Throwable {
         PollingCheck.waitFor(() -> TargetActivity.sLastCreated != null);
         // Just make sure that we're not in the middle of running on the UI thread.
-        mInstrumentation.runOnMainSync(() -> {});
+        mActivityRule.runOnUiThread(() -> { });
         return TargetActivity.sLastCreated;
     }
 
diff --git a/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java b/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java
index 4b55057..d11051f 100644
--- a/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java
+++ b/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java
@@ -77,7 +77,7 @@
 
         startTransition(R.layout.scene6);
         // The update listener will validate that it is changing throughout the animation
-        waitForEnd(400);
+        waitForEnd(800);
 
         validateInScene6();
     }
@@ -96,7 +96,7 @@
         startTransition(R.layout.scene6);
 
         // The update listener will validate that it is changing throughout the animation
-        waitForEnd(400);
+        waitForEnd(800);
 
         validateInScene6();
     }
@@ -112,7 +112,7 @@
         startTransition(R.layout.scene1);
 
         // The update listener will validate that it is changing throughout the animation
-        waitForEnd(400);
+        waitForEnd(800);
 
         validateInScene1();
     }
@@ -131,7 +131,7 @@
         startTransition(R.layout.scene6);
 
         assertFalse(isRestartingAnimation());
-        waitForEnd(500);
+        waitForEnd(1000);
         validateInScene6();
     }
 
@@ -153,7 +153,7 @@
 
         assertFalse(isRestartingAnimation());
         assertFalse(isRestartingClip());
-        waitForEnd(500);
+        waitForEnd(1000);
         validateInScene6();
     }
 
@@ -172,7 +172,7 @@
         startTransition(R.layout.scene1);
 
         assertFalse(isRestartingAnimation());
-        waitForEnd(500);
+        waitForEnd(1000);
         validateInScene1();
     }
 
@@ -195,7 +195,7 @@
 
         assertFalse(isRestartingAnimation());
         assertFalse(isRestartingClip());
-        waitForEnd(500);
+        waitForEnd(1000);
         validateInScene1();
     }
 
diff --git a/tests/tests/transition/src/android/transition/cts/ChangeImageTransformTest.java b/tests/tests/transition/src/android/transition/cts/ChangeImageTransformTest.java
index b27364e..6ae8a9f 100644
--- a/tests/tests/transition/src/android/transition/cts/ChangeImageTransformTest.java
+++ b/tests/tests/transition/src/android/transition/cts/ChangeImageTransformTest.java
@@ -236,7 +236,7 @@
         });
         waitForStart();
         verify(mListener, (startScale == endScale) ? times(1) : never()).onTransitionEnd(any());
-        waitForEnd(200);
+        waitForEnd(1000);
     }
 
     private ImageView enterImageViewScene(final ScaleType scaleType) throws Throwable {
diff --git a/tests/tests/transition/src/android/transition/cts/ChangeTransformTest.java b/tests/tests/transition/src/android/transition/cts/ChangeTransformTest.java
index fb231fa..38474a2 100644
--- a/tests/tests/transition/src/android/transition/cts/ChangeTransformTest.java
+++ b/tests/tests/transition/src/android/transition/cts/ChangeTransformTest.java
@@ -66,7 +66,7 @@
         verify(mListener, never()).onTransitionEnd(any()); // still running
         // There is no way to validate the intermediate matrix because it uses
         // hidden properties of the View to execute.
-        waitForEnd(400);
+        waitForEnd(800);
         assertEquals(500f, redSquare.getTranslationX(), 0.0f);
         assertEquals(600f, redSquare.getTranslationY(), 0.0f);
     }
@@ -86,7 +86,7 @@
         verify(mListener, never()).onTransitionEnd(any()); // still running
         // There is no way to validate the intermediate matrix because it uses
         // hidden properties of the View to execute.
-        waitForEnd(400);
+        waitForEnd(800);
         assertEquals(45f, redSquare.getRotation(), 0.0f);
     }
 
@@ -106,7 +106,7 @@
         verify(mListener, never()).onTransitionEnd(any()); // still running
         // There is no way to validate the intermediate matrix because it uses
         // hidden properties of the View to execute.
-        waitForEnd(400);
+        waitForEnd(800);
         assertEquals(2f, redSquare.getScaleX(), 0.0f);
         assertEquals(3f, redSquare.getScaleY(), 0.0f);
     }
@@ -117,7 +117,7 @@
         enterScene(R.layout.scene5);
         startTransition(R.layout.scene9);
         verify(mListener, never()).onTransitionEnd(any()); // still running
-        waitForEnd(400);
+        waitForEnd(800);
 
         resetListener();
         mChangeTransform.setReparent(false);
@@ -142,7 +142,7 @@
             mSceneRoot.getOverlay().remove(view);
             assertTrue(mActivity.findViewById(R.id.text).getVisibility() != View.VISIBLE);
         });
-        waitForEnd(400);
+        waitForEnd(800);
 
         mChangeTransform.setReparentWithOverlay(false);
         assertEquals(false, mChangeTransform.getReparentWithOverlay());
@@ -159,7 +159,7 @@
             mSceneRoot.getOverlay().remove(view);
             assertEquals(View.VISIBLE, mActivity.findViewById(R.id.text).getVisibility());
         });
-        waitForEnd(400);
+        waitForEnd(800);
     }
 }
 
diff --git a/tests/tests/transition/src/android/transition/cts/TransitionManagerTest.java b/tests/tests/transition/src/android/transition/cts/TransitionManagerTest.java
index d4375cc..f48f780 100644
--- a/tests/tests/transition/src/android/transition/cts/TransitionManagerTest.java
+++ b/tests/tests/transition/src/android/transition/cts/TransitionManagerTest.java
@@ -54,7 +54,7 @@
         });
 
         waitForStart();
-        waitForEnd(300);
+        waitForEnd(800);
         verify(mListener, never()).onTransitionResume(any());
         verify(mListener, never()).onTransitionPause(any());
         verify(mListener, never()).onTransitionCancel(any());
@@ -109,7 +109,7 @@
     public void testGo() throws Throwable {
         startTransition(R.layout.scene1);
         waitForStart();
-        waitForEnd(300);
+        waitForEnd(800);
 
         verify(mListener, never()).onTransitionResume(any());
         verify(mListener, never()).onTransitionPause(any());
@@ -156,7 +156,7 @@
         });
 
         waitForStart();
-        waitForEnd(300);
+        waitForEnd(800);
         verify(mListener, never()).onTransitionResume(any());
         verify(mListener, never()).onTransitionPause(any());
         verify(mListener, never()).onTransitionCancel(any());
@@ -195,7 +195,7 @@
         mActivityRule.runOnUiThread(() -> transitionManager.transitionTo(scenes[1]));
 
         waitForStart();
-        waitForEnd(300);
+        waitForEnd(800);
         verify(mListener, never()).onTransitionResume(any());
         verify(mListener, never()).onTransitionPause(any());
         verify(mListener, never()).onTransitionCancel(any());
@@ -220,7 +220,7 @@
         startTransition(R.layout.scene1);
         waitForStart();
         endTransition();
-        waitForEnd(100);
+        waitForEnd(400);
     }
 
     @Test
diff --git a/tests/tests/transition/src/android/transition/cts/TransitionTest.java b/tests/tests/transition/src/android/transition/cts/TransitionTest.java
index 9aaaeec..cc13eda 100644
--- a/tests/tests/transition/src/android/transition/cts/TransitionTest.java
+++ b/tests/tests/transition/src/android/transition/cts/TransitionTest.java
@@ -605,7 +605,7 @@
 
         enterScene(scene1);
 
-        mInstrumentation.runOnMainSync(() -> {
+        mActivityRule.runOnUiThread(() -> {
             // scene1
             assertSame(layout1, mActivity.findViewById(R.id.holder));
             assertNotNull(mActivity.findViewById(R.id.hello));
diff --git a/tests/tests/transition/src/android/transition/cts/VisibilityTest.java b/tests/tests/transition/src/android/transition/cts/VisibilityTest.java
index a71748a..6b608e4 100644
--- a/tests/tests/transition/src/android/transition/cts/VisibilityTest.java
+++ b/tests/tests/transition/src/android/transition/cts/VisibilityTest.java
@@ -61,19 +61,19 @@
         enterScene(R.layout.scene4);
         startTransition(R.layout.scene1);
         verify(mListener, never()).onTransitionEnd(any());
-        waitForEnd(400);
+        waitForEnd(800);
 
         resetListener();
         startTransition(R.layout.scene4);
         verify(mListener, never()).onTransitionEnd(any());
-        waitForEnd(400);
+        waitForEnd(800);
 
         // Now only animate in
         resetListener();
         mVisibilityTransition.setMode(Visibility.MODE_IN);
         startTransition(R.layout.scene1);
         verify(mListener, never()).onTransitionEnd(any());
-        waitForEnd(400);
+        waitForEnd(800);
 
         // No animation since it should only animate in
         resetListener();
@@ -90,7 +90,7 @@
         resetListener();
         startTransition(R.layout.scene4);
         verify(mListener, never()).onTransitionEnd(any());
-        waitForEnd(400);
+        waitForEnd(800);
     }
 
     @Test
diff --git a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
index c5a4bc5..140e262 100644
--- a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
+++ b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
@@ -411,12 +411,24 @@
         Uri rowUri = mContentResolver.insert(Channels.CONTENT_URI, values);
         assertNull(rowUri);
 
-        // Preview channels can be inserted without input ID
+        // Non-preview channels should not be inserted with null input ID
+        values.putNull(Channels.COLUMN_INPUT_ID);
+        rowUri = mContentResolver.insert(Channels.CONTENT_URI, values);
+        assertNull(rowUri);
+
+        // Preview channels can be inserted with null input ID
         values.put(Channels.COLUMN_TYPE, Channels.TYPE_PREVIEW);
         rowUri = mContentResolver.insert(Channels.CONTENT_URI, values);
         long channelId = ContentUris.parseId(rowUri);
         Uri channelUri = TvContract.buildChannelUri(channelId);
         verifyChannel(channelUri, values, channelId, false);
+
+        // Preview channels can be inserted without input ID
+        values.remove(Channels.COLUMN_INPUT_ID);
+        rowUri = mContentResolver.insert(Channels.CONTENT_URI, values);
+        channelId = ContentUris.parseId(rowUri);
+        channelUri = TvContract.buildChannelUri(channelId);
+        verifyChannel(channelUri, values, channelId, false);
     }
 
     public void testChannelsTableForModifyIdAndPackageName() throws Exception {
@@ -459,7 +471,6 @@
         ContentValues baseValues = createDummyChannelValues(mInputId, false);
         Uri channelUri = mContentResolver.insert(mChannelsUri, baseValues);
 
-
         // Test: insert
         ContentValues values = new ContentValues(baseValues);
         values.put(Channels.COLUMN_BROWSABLE, 1);
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapDumper.java b/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapDumper.java
index 8dd98b0..e96fe0b 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapDumper.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapDumper.java
@@ -16,15 +16,14 @@
 package android.uirendering.cts.util;
 
 import android.graphics.Bitmap;
+import android.os.Environment;
+import android.support.test.InstrumentationRegistry;
 import android.uirendering.cts.differencevisualizers.DifferenceVisualizer;
 import android.util.Log;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
+import com.android.compatibility.common.util.BitmapUtils;
 
-import libcore.io.IoUtils;
+import java.io.File;
 
 /**
  * A utility class that will allow the user to save bitmaps to the sdcard on the device.
@@ -35,7 +34,8 @@
     private final static String TESTED_RENDERING_FILE_NAME = "testedCapture.png";
     private final static String VISUALIZER_RENDERING_FILE_NAME = "visualizer.png";
     private final static String SINGULAR_FILE_NAME = "capture.png";
-    private final static String CAPTURE_SUB_DIRECTORY = "/sdcard/UiRenderingCaptures/";
+    private final static String CAPTURE_SUB_DIRECTORY = Environment.getExternalStorageDirectory()
+            + "/UiRenderingCaptures/";
 
     private BitmapDumper() {}
 
@@ -99,38 +99,8 @@
         saveFile(className, testName, SINGULAR_FILE_NAME, bitmap);
     }
 
-    private static void logIfBitmapSolidColor(String bitmapName, Bitmap bitmap) {
-        int firstColor = bitmap.getPixel(0, 0);
-        for (int x = 0; x < bitmap.getWidth(); x++) {
-            for (int y = 0; y < bitmap.getHeight(); y++) {
-                if (bitmap.getPixel(x, y) != firstColor) {
-                    return;
-                }
-            }
-        }
-
-        Log.w(TAG, String.format("%s entire bitmap color is %x", bitmapName, firstColor));
-    }
-
     private static void saveFile(String className, String testName, String fileName, Bitmap bitmap) {
-        String bitmapName = testName + "_" + fileName;
-        Log.d(TAG, "Saving file : " + bitmapName + " in directory : " + className);
-        logIfBitmapSolidColor(bitmapName, bitmap);
-
-        File file = new File(CAPTURE_SUB_DIRECTORY + className, bitmapName);
-        FileOutputStream fileStream = null;
-        try {
-            fileStream = new FileOutputStream(file);
-            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fileStream);
-            fileStream.flush();
-        } catch (FileNotFoundException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        } finally {
-            if (fileStream != null) {
-                IoUtils.closeQuietly(fileStream);
-            }
-        }
+        BitmapUtils.saveBitmap(bitmap, CAPTURE_SUB_DIRECTORY + className,
+                testName + "_" + fileName);
     }
 }
diff --git a/tests/tests/view/src/android/view/animation/cts/AnimationTest.java b/tests/tests/view/src/android/view/animation/cts/AnimationTest.java
index c47b4b1..aac14e6 100644
--- a/tests/tests/view/src/android/view/animation/cts/AnimationTest.java
+++ b/tests/tests/view/src/android/view/animation/cts/AnimationTest.java
@@ -77,6 +77,8 @@
     /** It is defined in R.anim.decelerate_alpha */
     private static final int DECELERATE_ALPHA_DURATION = 2000;
 
+    private static final int CANCELATION_TIMEOUT = 1000;
+
     private Instrumentation mInstrumentation;
     private Activity mActivity;
 
@@ -658,7 +660,7 @@
         MyAnimation anim = new MyAnimation();
         final CountDownLatch latch1 = new CountDownLatch(1);
         runCanceledAnimation(anim, latch1, false, false);
-        assertTrue(latch1.await(200, TimeUnit.MILLISECONDS));
+        assertTrue(latch1.await(CANCELATION_TIMEOUT, TimeUnit.MILLISECONDS));
         assertFalse(anim.isStillAnimating());
     }
 
@@ -667,7 +669,7 @@
         MyAnimation anim = new MyAnimation();
         final CountDownLatch latch2 = new CountDownLatch(1);
         runCanceledAnimation(anim, latch2, true, false);
-        assertTrue(latch2.await(200, TimeUnit.MILLISECONDS));
+        assertTrue(latch2.await(CANCELATION_TIMEOUT, TimeUnit.MILLISECONDS));
         assertFalse(anim.isStillAnimating());
     }
 
@@ -676,7 +678,7 @@
         MyAnimation anim = new MyAnimation();
         final CountDownLatch latch3 = new CountDownLatch(1);
         runCanceledAnimation(anim, latch3, false, true);
-        assertTrue(latch3.await(250, TimeUnit.MILLISECONDS));
+        assertTrue(latch3.await(CANCELATION_TIMEOUT, TimeUnit.MILLISECONDS));
         assertFalse(anim.isStillAnimating());
     }
 
@@ -685,7 +687,7 @@
         MyAnimation anim = new MyAnimation();
         final CountDownLatch latch4 = new CountDownLatch(1);
         runCanceledAnimation(anim, latch4, true, true);
-        assertTrue(latch4.await(250, TimeUnit.MILLISECONDS));
+        assertTrue(latch4.await(CANCELATION_TIMEOUT, TimeUnit.MILLISECONDS));
         assertFalse(anim.isStillAnimating());
     }
 
diff --git a/tests/tests/widget/src/android/widget/cts/SearchView_CursorTest.java b/tests/tests/widget/src/android/widget/cts/SearchView_CursorTest.java
index 2cc8993..c40c0fd 100644
--- a/tests/tests/widget/src/android/widget/cts/SearchView_CursorTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SearchView_CursorTest.java
@@ -143,7 +143,7 @@
 
     @UiThreadTest
     @Before
-    public void setup() {
+    public void setup() throws Throwable {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mActivity = mActivityRule.getActivity();
         mSearchView = (SearchView) mActivity.findViewById(R.id.search_view);
@@ -154,14 +154,16 @@
         // Use an adapter with our custom layout for each entry. The adapter "maps"
         // the content of the text column of our cursor to the @id/text1 view in the
         // layout.
-        mSuggestionsAdapter = new SimpleCursorAdapter(
-                mActivity,
-                R.layout.searchview_suggestion_item,
-                null,
-                new String[] { TEXT_COLUMN_NAME },
-                new int[] { android.R.id.text1 },
-                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
-        mSearchView.setSuggestionsAdapter(mSuggestionsAdapter);
+        mActivityRule.runOnUiThread(() -> {
+            mSuggestionsAdapter = new SimpleCursorAdapter(
+                    mActivity,
+                    R.layout.searchview_suggestion_item,
+                    null,
+                    new String[] { TEXT_COLUMN_NAME },
+                    new int[] { android.R.id.text1 },
+                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
+            mSearchView.setSuggestionsAdapter(mSuggestionsAdapter);
+        });
     }
 
     @UiThreadTest
diff --git a/tools/cts-tradefed/res/config/cts-known-failures.xml b/tools/cts-tradefed/res/config/cts-known-failures.xml
index e912981..1d86477 100644
--- a/tools/cts-tradefed/res/config/cts-known-failures.xml
+++ b/tools/cts-tradefed/res/config/cts-known-failures.xml
@@ -190,4 +190,7 @@
     <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp9Goog0Perf1280x0720" />
     <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp9Goog0Perf1920x1080" />
 
+    <!-- b/37105075 -->
+    <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.BatteryStatsValidationTest#testWifiUpload" />
+
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-sts.xml b/tools/cts-tradefed/res/config/security-bulletin.xml
similarity index 95%
rename from tools/cts-tradefed/res/config/cts-sts.xml
rename to tools/cts-tradefed/res/config/security-bulletin.xml
index 8e4c030..02175a9 100644
--- a/tools/cts-tradefed/res/config/cts-sts.xml
+++ b/tools/cts-tradefed/res/config/security-bulletin.xml
@@ -15,7 +15,7 @@
 -->
 <configuration description="Runs Security Patch test cases">
 
-    <option name="plan" value="cts-sts" />
+    <option name="plan" value="security-bulletin" />
 
     <include name="cts"/>
 
diff --git a/tools/selinux/SELinuxNeverallowTestFrame.py b/tools/selinux/SELinuxNeverallowTestFrame.py
index 7e9c304..f84f2ec 100644
--- a/tools/selinux/SELinuxNeverallowTestFrame.py
+++ b/tools/selinux/SELinuxNeverallowTestFrame.py
@@ -95,7 +95,7 @@
 
         /* run sepolicy-analyze neverallow check on policy file using given neverallow rules */
         ProcessBuilder pb = new ProcessBuilder(sepolicyAnalyze.getAbsolutePath(),
-                devicePolicyFile.getAbsolutePath(), "neverallow", "-n",
+                devicePolicyFile.getAbsolutePath(), "neverallow", "-w", "-n",
                 neverallowRule);
         pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
         pb.redirectErrorStream(true);