Merge "Add CTS test for SystemUpdatePolicy.ValidationFailedException#writeToParcel."
diff --git a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
index cf30457..75a95d2 100644
--- a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
+++ b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
@@ -63,23 +63,50 @@
         if np.isclose(sensor_ar, convert_ar_to_float(ar_string), atol=FMT_ATOL):
             match_ar = ar_string
     if not match_ar:
-        print "Error: no aspect ratio match with sensor parameters!"
+        print "Warning! RAW aspect ratio not in:", AR_CHECKED
     return match_ar
 
 
-def aspect_ratio_scale_factors(camera_ar_string):
+def aspect_ratio_scale_factors(ref_ar_string, props):
     """Determine scale factors for each aspect ratio to correct cropping.
 
     Args:
-        camera_ar_string:   camera aspect ratio that is the baseline
+        ref_ar_string:      camera aspect ratio that is the reference
+        props:              camera properties
     Returns:
         dict of correction ratios with AR_CHECKED values as keys
     """
-    ar_scaling = {}
-    camera_ar = convert_ar_to_float(camera_ar_string)
+    ref_ar = convert_ar_to_float(ref_ar_string)
+
+    # find sensor area
+    height_max = 0
+    width_max = 0
     for ar_string in AR_CHECKED:
-        ar = convert_ar_to_float(ar_string)
-        ar_scaling[ar_string] = ar / camera_ar
+        match_ar = [float(x) for x in ar_string.split(":")]
+        f = its.objects.get_largest_yuv_format(props, match_ar=match_ar)
+        if f["height"] > height_max:
+            height_max = f["height"]
+        if f["width"] > width_max:
+            width_max = f["width"]
+    sensor_ar = float(width_max) / height_max
+
+    # apply scaling
+    ar_scaling = {}
+    for ar_string in AR_CHECKED:
+        target_ar = convert_ar_to_float(ar_string)
+        # scale down to sensor with greater (or equal) dims
+        if ref_ar >= sensor_ar:
+            scaling = sensor_ar / ref_ar
+        else:
+            scaling = ref_ar / sensor_ar
+
+        # scale up due to cropping to other format
+        if target_ar >= sensor_ar:
+            scaling = scaling * target_ar / sensor_ar
+        else:
+            scaling = scaling * sensor_ar / target_ar
+
+        ar_scaling[ar_string] = scaling
     return ar_scaling
 
 
@@ -95,10 +122,20 @@
         ref_fov:    dict with [fmt, % coverage, w, h]
     """
     ref_fov = {}
-    ar = determine_sensor_aspect_ratio(props)
-    match_ar = [float(x) for x in ar.split(":")]
-    fmt = its.objects.get_largest_yuv_format(props, match_ar=match_ar)
-    cap = cam.do_capture(req, fmt)
+    pixels = []
+    fmt_list = []
+    # find number of pixels in different formats
+    for ar in AR_CHECKED:
+        match_ar = [float(x) for x in ar.split(":")]
+        f = its.objects.get_largest_yuv_format(props, match_ar=match_ar)
+        pixels.append(f["height"] * f["width"])
+        fmt_list.append(f)
+
+    # use image with largest coverage as reference
+    ar_max_pixels = np.argmax(pixels)
+
+    # capture and determine circle area in image
+    cap = cam.do_capture(req, fmt_list[ar_max_pixels])
     w = cap["width"]
     h = cap["height"]
     img = its.image.convert_capture_to_rgb_image(cap, props=props)
@@ -106,7 +143,7 @@
     img_name = "%s_%s_w%d_h%d.png" % (NAME, "yuv", w, h)
     _, _, circle_size = measure_aspect_ratio(img, False, img_name, True)
     fov_percent = calc_circle_image_ratio(circle_size[1], circle_size[0], w, h)
-    ref_fov["fmt"] = ar
+    ref_fov["fmt"] = AR_CHECKED[ar_max_pixels]
     ref_fov["percent"] = fov_percent
     ref_fov["w"] = w
     ref_fov["h"] = h
@@ -259,16 +296,20 @@
             factor_cp_thres = (min(size_raw[0:1])/4.0) / max(circle_size_raw)
             thres_l_cp_test = THRESH_L_CP * factor_cp_thres
             thres_xs_cp_test = THRESH_XS_CP * factor_cp_thres
+            # If RAW in AR_CHECKED, use it as reference
             ref_fov["fmt"] = determine_sensor_aspect_ratio(props)
-            ref_fov["percent"] = raw_fov_percent
-            ref_fov["w"] = w_raw
-            ref_fov["h"] = h_raw
-            print "Using RAW reference:", ref_fov
+            if ref_fov["fmt"]:
+                ref_fov["percent"] = raw_fov_percent
+                ref_fov["w"] = w_raw
+                ref_fov["h"] = h_raw
+                print "Using RAW reference:", ref_fov
+            else:
+                ref_fov = find_yuv_fov_reference(cam, req, props)
         else:
             ref_fov = find_yuv_fov_reference(cam, req, props)
 
         # Determine scaling factors for AR calculations
-        ar_scaling = aspect_ratio_scale_factors(ref_fov["fmt"])
+        ar_scaling = aspect_ratio_scale_factors(ref_fov["fmt"], props)
 
         # Take pictures of each settings with all the image sizes available.
         for fmt in format_list:
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
index 3d1fa10..36148cb 100755
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
@@ -476,7 +476,9 @@
                     return result;
                 }
                 try {
-                    while (child.getActionList().contains(AccessibilityAction.ACTION_SCROLL_FORWARD)) {
+                    while (child.getActionList().contains(
+                            AccessibilityAction.ACTION_SCROLL_FORWARD) || child.getActionList()
+                            .contains(AccessibilityAction.ACTION_SCROLL_DOWN)) {
                         scrollForward(child);
                         result = getNodeTimed(() -> findByText(child, text), false);
                         if (result != null) {
diff --git a/hostsidetests/devicepolicy/Android.mk b/hostsidetests/devicepolicy/Android.mk
index f9a861c..6ff06d9 100644
--- a/hostsidetests/devicepolicy/Android.mk
+++ b/hostsidetests/devicepolicy/Android.mk
@@ -22,7 +22,17 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := tools-common-prebuilt cts-tradefed tradefed compatibility-host-util
+LOCAL_JAVA_LIBRARIES := \
+    tools-common-prebuilt \
+    cts-tradefed \
+    tradefed \
+    compatibility-host-util
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    truth-host-prebuilt
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    truth-host-prebuilt
 
 LOCAL_CTS_TEST_PACKAGE := android.adminhostside
 
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/AdminReceiver.java b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/AdminReceiver.java
index bf18ebb..ef07632 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/AdminReceiver.java
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/src/com/android/cts/comp/AdminReceiver.java
@@ -37,7 +37,7 @@
         super.onProfileProvisioningComplete(context, intent);
         Log.i(TAG, "onProfileProvisioningComplete");
         // Enabled profile
-        getManager(context).setProfileEnabled(getComponentName(context));
-        getManager(context).setProfileName(getComponentName(context), "Corp owned Managed Profile");
+        getManager(context).setProfileEnabled(getWho(context));
+        getManager(context).setProfileName(getWho(context), "Corp owned Managed Profile");
     }
 }
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
index 1599d60..35cfe5b 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
@@ -35,7 +35,8 @@
     compatibility-device-util \
     ctstestrunner \
     ub-uiautomator \
-    cts-security-test-support-library
+    cts-security-test-support-library \
+    truth-prebuilt
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
     androidx.legacy_legacy-support-v4
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
index 481f821..3f797ce 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
@@ -35,7 +35,8 @@
     compatibility-device-util \
     ctstestrunner \
     ub-uiautomator \
-    cts-security-test-support-library
+    cts-security-test-support-library \
+    truth-prebuilt
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
     androidx.legacy_legacy-support-v4
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk
index 8c6d3fd..2c97495 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk
@@ -35,7 +35,8 @@
     compatibility-device-util \
     ctstestrunner \
     ub-uiautomator \
-    cts-security-test-support-library
+    cts-security-test-support-library \
+    truth-prebuilt
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
     androidx.legacy_legacy-support-v4
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccessibilityServicesTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccessibilityServicesTest.java
new file mode 100644
index 0000000..5647f78
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccessibilityServicesTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.deviceandprofileowner;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ComponentName;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class AccessibilityServicesTest extends BaseDeviceAdminTest {
+    private final ComponentName badAdmin = new ComponentName("com.foo.bar", ".BazQuxReceiver");
+
+    public void testPermittedAccessibilityServices() {
+        // All accessibility services are allowed.
+        mDevicePolicyManager.setPermittedAccessibilityServices(ADMIN_RECEIVER_COMPONENT, null);
+        assertThat(mDevicePolicyManager.
+                getPermittedAccessibilityServices(ADMIN_RECEIVER_COMPONENT))
+                .isNull();
+
+        // Only system accessibility services are allowed.
+        mDevicePolicyManager.setPermittedAccessibilityServices(ADMIN_RECEIVER_COMPONENT,
+                new ArrayList<>());
+        assertThat(mDevicePolicyManager.
+                getPermittedAccessibilityServices(ADMIN_RECEIVER_COMPONENT))
+                .isEmpty();
+
+        // Some random services.
+        final List<String> packages = Arrays.asList("com.google.pkg.one", "com.google.pkg.two");
+        mDevicePolicyManager.setPermittedAccessibilityServices(ADMIN_RECEIVER_COMPONENT, packages);
+        assertThat(mDevicePolicyManager.
+                getPermittedAccessibilityServices(ADMIN_RECEIVER_COMPONENT))
+                .containsExactlyElementsIn(packages);
+    }
+
+    public void testPermittedAccessibilityServicesThrowsIfWrongAdmin() {
+        try {
+            mDevicePolicyManager.setPermittedAccessibilityServices(badAdmin, null);
+            fail("setPermittedAccessibilityServices didn't throw when passed invalid admin");
+        } catch (SecurityException expected) {
+        }
+        try {
+            mDevicePolicyManager.getPermittedAccessibilityServices(badAdmin);
+            fail("getPermittedAccessibilityServices didn't throw when passed invalid admin");
+        } catch (SecurityException expected) {
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/InputMethodsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/InputMethodsTest.java
new file mode 100644
index 0000000..ed5047c
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/InputMethodsTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.deviceandprofileowner;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ComponentName;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class InputMethodsTest extends BaseDeviceAdminTest {
+    private final ComponentName badAdmin = new ComponentName("com.foo.bar", ".BazQuxReceiver");
+
+    public void testPermittedInputMethods() {
+        // All input methods are allowed.
+        mDevicePolicyManager.setPermittedInputMethods(ADMIN_RECEIVER_COMPONENT, null);
+        assertThat(
+                mDevicePolicyManager.getPermittedInputMethods(ADMIN_RECEIVER_COMPONENT)).isNull();
+
+        // Only system input methods are allowed.
+        mDevicePolicyManager.setPermittedInputMethods(ADMIN_RECEIVER_COMPONENT, new ArrayList<>());
+        assertThat(
+                mDevicePolicyManager.getPermittedInputMethods(ADMIN_RECEIVER_COMPONENT)).isEmpty();
+
+        // Some random methods.
+        final List<String> packages = Arrays.asList("com.google.pkg.one", "com.google.pkg.two");
+        mDevicePolicyManager.setPermittedInputMethods(ADMIN_RECEIVER_COMPONENT, packages);
+        assertThat(
+                mDevicePolicyManager.getPermittedInputMethods(ADMIN_RECEIVER_COMPONENT))
+                .containsExactlyElementsIn(packages);
+    }
+
+    public void testPermittedInputMethodsThrowsIfWrongAdmin() {
+        try {
+            mDevicePolicyManager.setPermittedInputMethods(badAdmin, null);
+            fail("setPermittedInputMethods didn't throw when passed invalid admin");
+        } catch (SecurityException expected) {
+        }
+        try {
+            mDevicePolicyManager.getPermittedInputMethods(badAdmin);
+            fail("getPermittedInputMethods didn't throw when passed invalid admin");
+        } catch (SecurityException expected) {
+        }
+    }
+}
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 e727d56..a4c8f21 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
@@ -15,6 +15,8 @@
  */
 package com.android.cts.deviceowner;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import android.app.admin.ConnectEvent;
 import android.app.admin.DnsEvent;
 import android.app.admin.NetworkEvent;
@@ -22,8 +24,8 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.os.Parcel;
 import android.support.test.InstrumentationRegistry;
-import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 import android.util.Log;
 
 import java.io.BufferedReader;
@@ -38,10 +40,13 @@
 import java.net.Socket;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
+
 public class NetworkLoggingTest extends BaseDeviceOwnerTest {
 
     private static final String TAG = "NetworkLoggingTest";
@@ -193,6 +198,80 @@
         verifyNetworkLogs(mNetworkEvents, eventsExpected);
     }
 
+    private void verifyDnsEvent(DnsEvent dnsEvent) {
+        // 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])) {
+            fail("A hostname that was looked-up when network logging was disabled"
+                    + " was logged.");
+        }
+
+        // Verify that as many IP addresses were logged as were reported (max 10).
+        final List<InetAddress> ips = dnsEvent.getInetAddresses();
+        assertThat(ips.size()).isAtMost(MAX_IP_ADDRESSES_LOGGED);
+        final int expectedAddressCount = Math.min(MAX_IP_ADDRESSES_LOGGED,
+                dnsEvent.getTotalResolvedAddressCount());
+        assertThat(expectedAddressCount).isEqualTo(ips.size());
+
+        // Verify the IP addresses are valid IPv4 or IPv6 addresses.
+        for (final InetAddress ipAddress : ips) {
+            assertTrue(isIpv4OrIpv6Address(ipAddress));
+        }
+
+        //Verify writeToParcel.
+        Parcel parcel = Parcel.obtain();
+        try {
+            dnsEvent.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            final DnsEvent dnsEventOut = DnsEvent.CREATOR.createFromParcel(parcel);
+            assertThat(dnsEventOut).isNotNull();
+            verifyDnsEventsEqual(dnsEvent, dnsEventOut);
+        } finally {
+            parcel.recycle();
+        }
+    }
+
+    private void verifyDnsEventsEqual(DnsEvent event1, DnsEvent event2) {
+        assertThat(event1.getHostname()).isEqualTo(event2.getHostname());
+        assertThat(new HashSet<InetAddress>(event1.getInetAddresses())).isEqualTo(
+                        new HashSet<InetAddress>(event2.getInetAddresses()));
+        assertThat(event1.getTotalResolvedAddressCount()).isEqualTo(
+                event2.getTotalResolvedAddressCount());
+        assertThat(event1.getPackageName()).isEqualTo(event2.getPackageName());
+        assertThat(event1.getTimestamp()).isEqualTo(event2.getTimestamp());
+        assertThat(event1.getId()).isEqualTo(event2.getId());
+    }
+
+    private void verifyConnectEvent(ConnectEvent connectEvent) {
+        // Verify the IP address is a valid IPv4 or IPv6 address.
+        final InetAddress ip = connectEvent.getInetAddress();
+        assertThat(isIpv4OrIpv6Address(ip)).isTrue();
+
+        // Verify that the port is a valid port.
+        assertThat(connectEvent.getPort()).isAtLeast(0);
+        assertThat(connectEvent.getPort()).isAtMost(65535);
+
+        // Verify writeToParcel.
+        Parcel parcel = Parcel.obtain();
+        try {
+            connectEvent.writeToParcel(parcel, 0);
+            parcel.setDataPosition(0);
+            final ConnectEvent connectEventOut = ConnectEvent.CREATOR.createFromParcel(parcel);
+            assertThat(connectEventOut).isNotNull();
+            verifyConnectEventsEqual(connectEvent, connectEventOut);
+        } finally {
+             parcel.recycle();
+        }
+    }
+
+    private void verifyConnectEventsEqual(ConnectEvent event1, ConnectEvent event2) {
+        assertThat(event1.getInetAddress()).isEqualTo(event2.getInetAddress());
+        assertThat(event1.getPort()).isEqualTo(event2.getPort());
+        assertThat(event1.getPackageName()).isEqualTo(event2.getPackageName());
+        assertThat(event1.getTimestamp()).isEqualTo(event2.getTimestamp());
+        assertThat(event1.getId()).isEqualTo(event2.getId());
+    }
+
     private void verifyNetworkLogs(List<NetworkEvent> networkEvents, int eventsExpected) {
         // allow a batch to be slightly smaller or larger.
         assertTrue(Math.abs(eventsExpected - networkEvents.size()) <= 50);
@@ -216,35 +295,18 @@
                 ctsPackageNameCounter++;
                 if (currentEvent instanceof DnsEvent) {
                     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])) {
-                        fail("A hostname that was looked-up when network logging was disabled"
-                                + " was logged.");
-                    }
-                    // count the frequencies of LOGGED_URLS_LIST's hostnames that were looked up
+                    // Mark which addresses from LOGGED_URLS_LIST were visited.
                     for (int j = 0; j < LOGGED_URLS_LIST.length; j++) {
                         if (dnsEvent.getHostname().contains(LOGGED_URLS_LIST[j])) {
                             visited[j] = true;
                             break;
                         }
                     }
-                    // verify that as many IP addresses were logged as were reported (max 10)
-                    final List<InetAddress> ips = dnsEvent.getInetAddresses();
-                    assertTrue(ips.size() <= MAX_IP_ADDRESSES_LOGGED);
-                    final int expectedAddressCount = Math.min(MAX_IP_ADDRESSES_LOGGED,
-                            dnsEvent.getTotalResolvedAddressCount());
-                    assertEquals(expectedAddressCount, ips.size());
-                    // verify the IP addresses are valid IPv4 or IPv6 addresses
-                    for (final InetAddress ipAddress : ips) {
-                        assertTrue(isIpv4OrIpv6Address(ipAddress));
-                    }
+
+                    verifyDnsEvent(dnsEvent);
                 } else if (currentEvent instanceof ConnectEvent) {
                     final ConnectEvent connectEvent = (ConnectEvent) currentEvent;
-                    // verify the IP address is a valid IPv4 or IPv6 address
-                    assertTrue(isIpv4OrIpv6Address(connectEvent.getInetAddress()));
-                    // verify that the port is a valid port
-                    assertTrue(connectEvent.getPort() >= 0 && connectEvent.getPort() <= 65535);
+                    verifyConnectEvent(connectEvent);
                 } else {
                     fail("An unknown NetworkEvent type logged: "
                             + currentEvent.getClass().getName());
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
index 6a02fd1..1f990f4 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
@@ -33,7 +33,8 @@
 	compatibility-device-util \
 	ub-uiautomator \
 	android-support-test \
-	guava
+	guava \
+	truth-prebuilt
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
     androidx.legacy_legacy-support-v4
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
index 3cb0bce..58e232b 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -191,6 +191,13 @@
           </intent-filter>
         </receiver>
 
+        <receiver android:name=".WipeDataReceiver">
+            <intent-filter>
+                <action android:name="com.android.cts.managedprofile.WIPE_DATA" />
+                <action android:name="com.android.cts.managedprofile.WIPE_DATA_WITH_REASON" />
+            </intent-filter>
+        </receiver>
+
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml b/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml
index 30538af..b42c966 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml
@@ -19,5 +19,7 @@
         <limit-password />
         <disable-keyguard-features/>
         <force-lock />
+        <expire-password />
+        <watch-login />
     </uses-policies>
 </device-admin>
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/DevicePolicyManagerParentSupportTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/DevicePolicyManagerParentSupportTest.java
new file mode 100644
index 0000000..9bd721f
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/DevicePolicyManagerParentSupportTest.java
@@ -0,0 +1,151 @@
+package com.android.cts.managedprofile;
+
+import static android.app.admin.DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.os.PersistableBundle;
+
+/**
+ * Tests that the {@link DevicePolicyManager} APIs that should work for {@link
+ * DevicePolicyManager#getParentProfileInstance(ComponentName)} are supported.
+ *
+ * <p>Minimum restriction APIs are already tested by {@link PasswordMinimumRestrictionsTest}.
+ */
+public class DevicePolicyManagerParentSupportTest extends BaseManagedProfileTest {
+    private static final ComponentName FAKE_COMPONENT = new ComponentName(
+            FakeComponent.class.getPackage().getName(), FakeComponent.class.getName());
+
+    public void testSetAndGetPasswordQuality_onParent() {
+        mParentDevicePolicyManager.setPasswordQuality(
+                ADMIN_RECEIVER_COMPONENT, PASSWORD_QUALITY_NUMERIC_COMPLEX);
+        final int actualPasswordQuality =
+                mParentDevicePolicyManager.getPasswordQuality(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualPasswordQuality).isEqualTo(PASSWORD_QUALITY_NUMERIC_COMPLEX);
+    }
+
+    public void testSetAndGetPasswordHistoryLength_onParent() {
+        final int passwordHistoryLength = 5;
+
+        mParentDevicePolicyManager.setPasswordHistoryLength(
+                ADMIN_RECEIVER_COMPONENT, passwordHistoryLength);
+        final int actualPasswordHistoryLength =
+                mParentDevicePolicyManager.getPasswordHistoryLength(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualPasswordHistoryLength).isEqualTo(passwordHistoryLength);
+    }
+
+    public void testSetAndGetPasswordExpirationTimeout_onParent() {
+        final int passwordExpirationTimeout = 432000000;
+
+        mParentDevicePolicyManager.setPasswordExpirationTimeout(
+                ADMIN_RECEIVER_COMPONENT, passwordExpirationTimeout);
+        final long actualPasswordExpirationTimeout =
+                mParentDevicePolicyManager.getPasswordExpirationTimeout(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualPasswordExpirationTimeout).isEqualTo(passwordExpirationTimeout);
+    }
+
+    public void testGetPasswordExpiration_onParent() {
+        final long passwordExpirationTimeout = 432000000;
+        final long currentTime = System.currentTimeMillis();
+
+        mParentDevicePolicyManager.setPasswordExpirationTimeout(
+                ADMIN_RECEIVER_COMPONENT, passwordExpirationTimeout);
+        final long actualPasswordExpiration =
+                mParentDevicePolicyManager.getPasswordExpiration(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualPasswordExpiration).isAtLeast(passwordExpirationTimeout + currentTime);
+    }
+
+    public void testGetMaximumPasswordLength_onParent() {
+        final int actualMaximumPasswordLength =
+                mParentDevicePolicyManager.getPasswordMaximumLength(
+                        PASSWORD_QUALITY_NUMERIC_COMPLEX);
+        assertThat(actualMaximumPasswordLength).isGreaterThan(0);
+    }
+
+    public void testIsActivePasswordSufficient_onParent_isSupported() {
+        setPasswordQuality(PASSWORD_QUALITY_NUMERIC_COMPLEX);
+        assertThat(mParentDevicePolicyManager.isActivePasswordSufficient()).isFalse();
+    }
+
+    private void setPasswordQuality(int quality) {
+        mParentDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT, quality);
+    }
+
+    public void testGetCurrentFailedPasswordAttempts_onParent_isSupported() {
+        assertThat(mParentDevicePolicyManager.getCurrentFailedPasswordAttempts()).isEqualTo(0);
+    }
+
+    public void testSetAndGetMaximumFailedPasswordsForWipe_onParent() {
+        final int maximumFailedPasswordsForWipe = 15;
+
+        mParentDevicePolicyManager.setMaximumFailedPasswordsForWipe(
+                ADMIN_RECEIVER_COMPONENT, maximumFailedPasswordsForWipe);
+        final int actualMaximumFailedPasswordsForWipe =
+                mParentDevicePolicyManager.getMaximumFailedPasswordsForWipe(
+                        ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualMaximumFailedPasswordsForWipe).isEqualTo(maximumFailedPasswordsForWipe);
+    }
+
+    public void testSetAndGetMaximumTimeToLock_onParent() {
+        final int maximumTimeToLock = 6000;
+
+        mParentDevicePolicyManager.setMaximumTimeToLock(
+                ADMIN_RECEIVER_COMPONENT, maximumTimeToLock);
+        final long actualMaximumTimeToLock =
+                mParentDevicePolicyManager.getMaximumTimeToLock(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualMaximumTimeToLock).isEqualTo(maximumTimeToLock);
+    }
+
+    public void testLockNow_onParent_isSupported() {
+        mParentDevicePolicyManager.lockNow();
+        // Will fail if a SecurityException is thrown.
+    }
+
+    public void testSetAndGetKeyguardDisabledFeatures_onParent() {
+        mParentDevicePolicyManager.setKeyguardDisabledFeatures(
+                ADMIN_RECEIVER_COMPONENT, KEYGUARD_DISABLE_TRUST_AGENTS);
+        long actualKeyguardDisabledFeatures =
+                mParentDevicePolicyManager.getKeyguardDisabledFeatures(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualKeyguardDisabledFeatures).isEqualTo(KEYGUARD_DISABLE_TRUST_AGENTS);
+    }
+
+    public void testSetAndGetTrustAgentConfiguration_onParent() {
+        final PersistableBundle configuration = new PersistableBundle();
+        final String key = "key";
+        final String value = "value";
+        configuration.putString(key, value);
+
+        mParentDevicePolicyManager.setTrustAgentConfiguration(
+                ADMIN_RECEIVER_COMPONENT, FAKE_COMPONENT, configuration);
+        final PersistableBundle actualConfiguration =
+                mParentDevicePolicyManager.getTrustAgentConfiguration(
+                        ADMIN_RECEIVER_COMPONENT, FAKE_COMPONENT).get(0);
+
+        assertThat(actualConfiguration.get(key)).isEqualTo(value);
+    }
+
+    public void testSetAndGetRequiredStrongAuthTimeout_onParent() {
+        final int requiredStrongAuthTimeout = 4600000;
+
+        mParentDevicePolicyManager.setRequiredStrongAuthTimeout(
+                ADMIN_RECEIVER_COMPONENT, requiredStrongAuthTimeout);
+        final long actualRequiredStrongAuthTimeout =
+                mParentDevicePolicyManager.getRequiredStrongAuthTimeout(ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualRequiredStrongAuthTimeout).isEqualTo(requiredStrongAuthTimeout);
+    }
+
+    public abstract class FakeComponent extends BroadcastReceiver {}
+}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java
index 6986c39..c89ef13 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java
@@ -15,13 +15,8 @@
  */
 package com.android.cts.managedprofile;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.UiAutomation;
 import android.app.admin.DevicePolicyManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
@@ -32,15 +27,19 @@
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
 import android.support.test.uiautomator.UiDevice;
-import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 import android.util.Log;
 
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
+
+import com.google.common.collect.ImmutableList;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
 import java.io.IOException;
 import java.util.Collections;
+import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -107,16 +106,16 @@
         toggleNotificationListener(true);
 
         sendProfileNotification();
-        assertTrue(mReceiver.waitForNotificationPostedReceived());
+        assertThat(mReceiver.waitForNotificationPostedReceived()).isTrue();
         cancelProfileNotification();
-        assertTrue(mReceiver.waitForNotificationRemovedReceived());
+        assertThat(mReceiver.waitForNotificationRemovedReceived()).isTrue();
 
         mReceiver.reset();
 
         sendPersonalNotification();
-        assertTrue(mReceiver.waitForNotificationPostedReceived());
+        assertThat(mReceiver.waitForNotificationPostedReceived()).isTrue();
         cancelPersonalNotification();
-        assertTrue(mReceiver.waitForNotificationRemovedReceived());
+        assertThat(mReceiver.waitForNotificationRemovedReceived()).isTrue();
     }
 
     @Test
@@ -125,17 +124,29 @@
 
         sendProfileNotification();
         // Don't see notification or cancellation from work profile.
-        assertFalse(mReceiver.waitForNotificationPostedReceived());
+        assertThat(mReceiver.waitForNotificationPostedReceived()).isFalse();
         cancelProfileNotification();
-        assertFalse(mReceiver.waitForNotificationRemovedReceived());
+        assertThat(mReceiver.waitForNotificationRemovedReceived()).isFalse();
 
         mReceiver.reset();
 
         // Do see the one from the personal side.
         sendPersonalNotification();
-        assertTrue(mReceiver.waitForNotificationPostedReceived());
+        assertThat(mReceiver.waitForNotificationPostedReceived()).isTrue();
         cancelPersonalNotification();
-        assertTrue(mReceiver.waitForNotificationRemovedReceived());
+        assertThat(mReceiver.waitForNotificationRemovedReceived()).isTrue();
+    }
+
+    @Test
+    public void testSetAndGetPermittedCrossProfileNotificationListeners() {
+        List<String> packageList = ImmutableList.of("package1", "package2");
+
+        mDpm.setPermittedCrossProfileNotificationListeners(
+                BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, packageList);
+        List<String> actualPackageList = mDpm.getPermittedCrossProfileNotificationListeners(
+                BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT);
+
+        assertThat(actualPackageList).isEqualTo(packageList);
     }
 
     private void cancelProfileNotification() throws IOException {
@@ -170,7 +181,7 @@
                 + testListener);
         Log.i(TAG, "Toggled notification listener state" + testListener + " to state " + enable);
         if (enable) {
-            assertTrue(mReceiver.waitForListenerConnected());
+            assertThat(mReceiver.waitForListenerConnected()).isTrue();
         }
     }
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PasswordMinimumRestrictionsTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PasswordMinimumRestrictionsTest.java
index 4f94674..8b7d16b 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PasswordMinimumRestrictionsTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PasswordMinimumRestrictionsTest.java
@@ -25,6 +25,7 @@
 import java.util.ArrayList;
 import java.util.List;
 
+/** Tests minimum password restriction APIs, including on parent profile instances. */
 public class PasswordMinimumRestrictionsTest extends BaseManagedProfileTest {
 
     private static final int TEST_PASSWORD_LENGTH = 5;
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataReceiver.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataReceiver.java
new file mode 100644
index 0000000..0abea7d
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataReceiver.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.managedprofile;
+
+import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+/**
+ * Invoke wipeData(), optionally including a reason. This is used by host side tests to destroy the
+ * work profile. The call is triggered via a broadcast instead of run as a normal test case, since
+ * the test process will be killed after calling wipeData() which will result in a test failure if
+ * this were run as a test case.
+ */
+public class WipeDataReceiver extends BroadcastReceiver {
+
+    private static final String ACTION_WIPE_DATA = "com.android.cts.managedprofile.WIPE_DATA";
+    private static final String ACTION_WIPE_DATA_WITH_REASON =
+            "com.android.cts.managedprofile.WIPE_DATA_WITH_REASON";
+    private static final String TEST_WIPE_DATA_REASON = "cts test for WipeDataWithReason";
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        final DevicePolicyManager dpm = context.getSystemService(DevicePolicyManager.class);
+        if (ACTION_WIPE_DATA.equals(intent.getAction())) {
+            dpm.wipeData(0);
+        } else if (ACTION_WIPE_DATA_WITH_REASON.equals(intent.getAction())) {
+            dpm.wipeData(0, TEST_WIPE_DATA_REASON);
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerHostSideTransferTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerHostSideTransferTest.java
index bd773e7..997b831 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerHostSideTransferTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerHostSideTransferTest.java
@@ -15,6 +15,10 @@
             "com.android.cts.transferownerincoming";
     protected static final String TRANSFER_OWNER_INCOMING_APK = "CtsTransferOwnerIncomingApp.apk";
     protected static final String INVALID_TARGET_APK = "CtsIntentReceiverApp.apk";
+    protected static final String TRANSFER_PROFILE_OWNER_OUTGOING_TEST =
+        "com.android.cts.transferowner.TransferProfileOwnerOutgoingTest";
+    protected static final String TRANSFER_PROFILE_OWNER_INCOMING_TEST =
+        "com.android.cts.transferowner.TransferProfileOwnerIncomingTest";
 
     protected int mUserId;
     protected String mOutgoingTestClassName;
@@ -204,6 +208,26 @@
             "testAdminServiceIsBound", mUserId);
     }
 
+    protected void setSameAffiliationId(int profileUserId, String testClassName)
+        throws Exception {
+        runDeviceTestsAsUser(TRANSFER_OWNER_OUTGOING_PKG,
+            testClassName,
+            "testSetAffiliationId1", mPrimaryUserId);
+        runDeviceTestsAsUser(TRANSFER_OWNER_OUTGOING_PKG,
+            testClassName,
+            "testSetAffiliationId1", profileUserId);
+    }
+
+    protected void assertAffiliationIdsAreIntact(int profileUserId,
+        String testClassName) throws Exception {
+        runDeviceTestsAsUser(TRANSFER_OWNER_INCOMING_PKG,
+            testClassName,
+            "testIsAffiliationId1", mPrimaryUserId);
+        runDeviceTestsAsUser(TRANSFER_OWNER_INCOMING_PKG,
+            testClassName,
+            "testIsAffiliationId1", profileUserId);
+    }
+
     /* TODO: Add tests for:
     * 1. passwordOwner
     *
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index fbe75d2..c2f8ada 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -28,7 +28,6 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
-import java.util.Map;
 
 /**
  * Set of tests for use cases that apply to profile and device owner.
@@ -915,6 +914,22 @@
         }
     }
 
+    public void testPermittedAccessibilityServices() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+
+        executeDeviceTestClass(".AccessibilityServicesTest");
+    }
+
+    public void testPermittedInputMethods() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+
+        executeDeviceTestClass(".InputMethodsTest");
+    }
+
     /**
      * Executes a test class on device. Prior to running, turn off background data usage
      * restrictions, and restore the original restrictions after the test.
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java
new file mode 100644
index 0000000..960fbb2
--- /dev/null
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DevicePlusProfileOwnerHostSideTransferTest.java
@@ -0,0 +1,45 @@
+package com.android.cts.devicepolicy;
+
+import android.util.Log;
+
+/**
+ * Tests the DPC transfer functionality for COMP mode - managed profile on top of a device owner.
+ * Testing is done by having two dummy DPCs, CtsTransferOwnerOutgoingApp and
+ * CtsTransferOwnerIncomingApp. The former is the current DPC and the latter will be the new DPC
+ * after transfer. In order to run the tests from the correct process, first we setup some
+ * policies in the client side in CtsTransferOwnerOutgoingApp and then we verify the policies are
+ * still there in CtsTransferOwnerIncomingApp. Note that these tests are run on the profile owner
+ * user.
+ */
+public class DevicePlusProfileOwnerHostSideTransferTest
+    extends DeviceAndProfileOwnerHostSideTransferTest {
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        // We need managed users to be supported in order to create a profile of the user owner.
+        mHasFeature &= hasDeviceFeature("android.software.managed_users");
+        if (mHasFeature) {
+            installAppAsUser(TRANSFER_OWNER_OUTGOING_APK, mPrimaryUserId);
+            // First set up the device owner.
+            if (setDeviceOwner(TRANSFER_OWNER_OUTGOING_TEST_RECEIVER, mPrimaryUserId,
+                false)) {
+                mOutgoingTestClassName = TRANSFER_PROFILE_OWNER_OUTGOING_TEST;
+                mIncomingTestClassName = TRANSFER_PROFILE_OWNER_INCOMING_TEST;
+
+                // And then set up the managed profile on top of it.
+                final int profileUserId = setupManagedProfileOnDeviceOwner(
+                    TRANSFER_OWNER_OUTGOING_APK, TRANSFER_OWNER_OUTGOING_TEST_RECEIVER);
+                setSameAffiliationId(profileUserId, TRANSFER_PROFILE_OWNER_OUTGOING_TEST);
+
+                installAppAsUser(TRANSFER_OWNER_INCOMING_APK, mPrimaryUserId);
+                installAppAsUser(TRANSFER_OWNER_INCOMING_APK, profileUserId);
+                mUserId = profileUserId;
+            } else {
+                removeAdmin(TRANSFER_OWNER_OUTGOING_TEST_RECEIVER, mUserId);
+                getDevice().uninstallPackage(TRANSFER_OWNER_OUTGOING_PKG);
+                fail("Failed to set device owner");
+            }
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 1548d7f..d1db198 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -160,11 +160,7 @@
             return;
         }
         assertTrue(listUsers().contains(mProfileUserId));
-        runDeviceTestsAsUser(
-                MANAGED_PROFILE_PKG,
-                ".WipeDataTest",
-                "testWipeDataWithReason",
-                mProfileUserId);
+        sendWipeProfileBroadcast("com.android.cts.managedprofile.WIPE_DATA_WITH_REASON");
         // Note: the managed profile is removed by this test, which will make removeUserCommand in
         // tearDown() to complain, but that should be OK since its result is not asserted.
         assertUserGetsRemoved(mProfileUserId);
@@ -186,14 +182,19 @@
             return;
         }
         assertTrue(listUsers().contains(mProfileUserId));
-        runDeviceTestsAsUser(
-                MANAGED_PROFILE_PKG, ".WipeDataTest",
-                "testWipeData", mProfileUserId);
+        sendWipeProfileBroadcast("com.android.cts.managedprofile.WIPE_DATA");
         // Note: the managed profile is removed by this test, which will make removeUserCommand in
         // tearDown() to complain, but that should be OK since its result is not asserted.
         assertUserGetsRemoved(mProfileUserId);
     }
 
+    private void sendWipeProfileBroadcast(String action) throws Exception {
+        final String cmd = "am broadcast --receiver-foreground --user " + mProfileUserId
+            + " -a " + action
+            + " com.android.cts.managedprofile/.WipeDataReceiver";
+        getDevice().executeShellCommand(cmd);
+    }
+
     public void testLockNowWithKeyEviction() throws Exception {
         if (!mHasFeature || !mSupportsFbe) {
             return;
@@ -599,6 +600,18 @@
                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
     }
 
+    public void testCrossProfileNotificationListeners_setAndGet() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        installAppAsUser(NOTIFICATION_APK, mProfileUserId);
+        installAppAsUser(NOTIFICATION_APK, mParentUserId);
+
+        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
+                "testSetAndGetPermittedCrossProfileNotificationListeners", mProfileUserId,
+                Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
+    }
+
     public void testCrossProfileCopyPaste() throws Exception {
         if (!mHasFeature) {
             return;
@@ -837,6 +850,14 @@
                 mProfileUserId);
     }
 
+    public void testDevicePolicyManagerParentSupport() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        runDeviceTestsAsUser(
+                MANAGED_PROFILE_PKG, ".DevicePolicyManagerParentSupportTest", mProfileUserId);
+    }
+
     public void testBluetoothContactSharingDisabled() throws Exception {
         if (!mHasFeature) {
             return;
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerHostSideTransferTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerHostSideTransferTest.java
index 7aefc33..fa0e60b 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerHostSideTransferTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerHostSideTransferTest.java
@@ -100,24 +100,4 @@
                 "testTransferAffiliatedProfileOwnershipCompleteCallbackIsCalled",
                 mUserId);
     }
-
-    private void assertAffiliationIdsAreIntact(int profileUserId,
-            String testClassName) throws Exception {
-        runDeviceTestsAsUser(TRANSFER_OWNER_INCOMING_PKG,
-                testClassName,
-                "testIsAffiliationId1", mPrimaryUserId);
-        runDeviceTestsAsUser(TRANSFER_OWNER_INCOMING_PKG,
-                testClassName,
-                "testIsAffiliationId1", profileUserId);
-    }
-
-    private void setSameAffiliationId(int profileUserId, String testClassName)
-            throws Exception {
-        runDeviceTestsAsUser(TRANSFER_OWNER_OUTGOING_PKG,
-                testClassName,
-                "testSetAffiliationId1", mPrimaryUserId);
-        runDeviceTestsAsUser(TRANSFER_OWNER_OUTGOING_PKG,
-                testClassName,
-                "testSetAffiliationId1", profileUserId);
-    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
index 01e55fe..5317ecb 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
@@ -16,14 +16,6 @@
 
 package com.android.cts.devicepolicy;
 
-import android.platform.test.annotations.RequiresDevice;
-
-import com.android.ddmlib.Log.LogLevel;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.log.LogUtil.CLog;
-
-import junit.framework.AssertionFailedError;
-
 /**
  * Set of tests for device owner use cases that also apply to profile owners.
  * Tests that should be run identically in both cases are added in DeviceAndProfileOwnerTest.
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
index b39e1ad..ba30f25 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
@@ -22,7 +22,7 @@
  */
 public class MixedManagedProfileOwnerTest extends DeviceAndProfileOwnerTest {
 
-    protected static final String CLEAR_PROFILE_OWNER_NEGATIVE_TEST_CLASS =
+    private static final String CLEAR_PROFILE_OWNER_NEGATIVE_TEST_CLASS =
             DEVICE_ADMIN_PKG + ".ClearProfileOwnerNegativeTest";
 
     private int mParentUserId = -1;
@@ -170,4 +170,11 @@
     public void testSetSystemSetting() {
         // Managed profile owner cannot set currently whitelisted system settings.
     }
+
+    public void testCannotClearProfileOwner() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        runDeviceTestsAsUser(DEVICE_ADMIN_PKG, CLEAR_PROFILE_OWNER_NEGATIVE_TEST_CLASS, mUserId);
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerHostSideTransferTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerHostSideTransferTest.java
index 5143fb1..ca081fc 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerHostSideTransferTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerHostSideTransferTest.java
@@ -24,10 +24,6 @@
  */
 public class MixedProfileOwnerHostSideTransferTest extends
         DeviceAndProfileOwnerHostSideTransferTest {
-    private static final String TRANSFER_PROFILE_OWNER_OUTGOING_TEST =
-            "com.android.cts.transferowner.TransferProfileOwnerOutgoingTest";
-    private static final String TRANSFER_PROFILE_OWNER_INCOMING_TEST =
-            "com.android.cts.transferowner.TransferProfileOwnerIncomingTest";
 
     @Override
     protected void setUp() throws Exception {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java
index 803cf36..e1d50bd 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java
@@ -16,8 +16,6 @@
 
 package com.android.cts.devicepolicy;
 
-import android.platform.test.annotations.RequiresDevice;
-
 /**
  * Set of tests for pure (non-managed) profile owner use cases that also apply to device owners.
  * Tests that should be run identically in both cases are added in DeviceAndProfileOwnerTest.
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTestApi25.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTestApi25.java
index b044441..0dcb82a 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTestApi25.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTestApi25.java
@@ -16,8 +16,6 @@
 
 package com.android.cts.devicepolicy;
 
-import android.platform.test.annotations.RequiresDevice;
-
 /**
  * Set of tests for pure (non-managed) profile owner use cases that also apply to device owners.
  * Tests that should be run identically in both cases are added in DeviceAndProfileOwnerTestApi25.
diff --git a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
index 4454591..5237de9 100644
--- a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
@@ -169,7 +169,7 @@
         // valid ranges.
         assertTrue(summary.getJankyFrames() <= summary.getTotalFrames());
         assertTrue(summary.getMissedVsyncCount() <= summary.getJankyFrames());
-        assertTrue(summary.getHighInputLatencyCount() <= summary.getJankyFrames());
+        assertTrue(summary.getHighInputLatencyCount() <= summary.getTotalFrames());
         assertTrue(summary.getSlowUiThreadCount() <= summary.getJankyFrames());
         assertTrue(summary.getSlowBitmapUploadCount() <= summary.getJankyFrames());
         assertTrue(summary.getSlowDrawCount() <= summary.getJankyFrames());
diff --git a/hostsidetests/security/AndroidTest.xml b/hostsidetests/security/AndroidTest.xml
index 78aa311..6645dd5 100755
--- a/hostsidetests/security/AndroidTest.xml
+++ b/hostsidetests/security/AndroidTest.xml
@@ -49,6 +49,11 @@
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
         <option name="push" value="CVE-2016-2460->/data/local/tmp/CVE-2016-2460" />
 
+        <!--__________________-->
+        <!-- Bulletin 2016-07 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-3818->/data/local/tmp/CVE-2016-3818" />
+
         <!-- Bulletin 2016-09 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
         <option name="push" value="CVE-2016-2471->/data/local/tmp/CVE-2016-2471" />
diff --git a/hostsidetests/security/securityPatch/CVE-2016-3818/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-3818/Android.mk
new file mode 100755
index 0000000..0fe16b7
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2016-3818/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2018 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2016-3818
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS += -Wall -Werror
+LOCAL_LDFLAGS += -fPIE -pie
+LOCAL_LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-3818/poc.c b/hostsidetests/security/securityPatch/CVE-2016-3818/poc.c
new file mode 100644
index 0000000..4a204fc
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2016-3818/poc.c
@@ -0,0 +1,55 @@
+/**
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define _GNU_SOURCE
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+int main(void) {
+  struct rlimit rlim;
+  size_t i;
+
+  int result = getrlimit(RLIMIT_AS, &rlim);
+  printf("%lu\n", rlim.rlim_cur);
+  printf("%lu\n", rlim.rlim_max);
+
+  rlim.rlim_cur = 384 * 1024 * 1024;
+  result = setrlimit(RLIMIT_AS, &rlim);
+
+  /*
+   * Issue exists only in kitkat. It passes in
+   * android M onwards. In failure scenario, device reboots.
+   */
+  size_t to_alloc = 1.6 * 1024 * 1024 * 1024;
+  char *mem = (char *)malloc(to_alloc);
+
+  printf("%p\n", mem);
+  if (mem) {
+    for (i = 0; i < to_alloc; i++) {
+      mem[i] = 0;
+    }
+    printf("filled\n");
+  }
+
+  free(mem);
+  return 0;
+}
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_07.java b/hostsidetests/security/src/android/security/cts/Poc16_07.java
new file mode 100644
index 0000000..2601d43
--- /dev/null
+++ b/hostsidetests/security/src/android/security/cts/Poc16_07.java
@@ -0,0 +1,29 @@
+/**
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+
+@SecurityTest
+public class Poc16_07 extends SecurityTestCase {
+    /**
+     *  b/28740702
+     */
+    @SecurityTest
+    public void testPocCVE_2016_3818() throws Exception {
+        AdbUtils.runPoc("CVE-2016-3818", getDevice(), 60);
+    }
+}
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
index d0bab51..5888273 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
@@ -2970,162 +2970,6 @@
     }
 
     @MediumTest
-    public void testActionNextAndPreviousAtGranularityPageOverText() throws Exception {
-        final EditText editText = (EditText) getActivity().findViewById(R.id.edit);
-
-        getInstrumentation().runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.setVisibility(View.VISIBLE);
-                editText.setText(getString(R.string.android_wiki));
-                Selection.removeSelection(editText.getText());
-            }
-        });
-
-        final AccessibilityNodeInfo text = getInstrumentation().getUiAutomation()
-               .getRootInActiveWindow().findAccessibilityNodeInfosByText(getString(
-                       R.string.android_wiki)).get(0);
-
-        final int granularities = text.getMovementGranularities();
-        assertEquals(granularities, AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
-
-        final Bundle arguments = new Bundle();
-        arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
-                AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
-
-        // Move forward a few pages
-        for (int i = 0; i < CHARACTER_INDICES_OF_PAGE_START.length - 1; i++) {
-            AccessibilityEvent event = performMovementActionAndGetEvent(
-                    text,
-                    AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
-                    AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE,
-                    false);
-            assertEquals(event.getClassName(), EditText.class.getName());
-            assertTrue("Event should contain text", event.getText().size() > 0);
-            assertTrue("Event text doesn't match. Expected: " + getString(R.string.android_wiki)
-                    + ". Received:" + event.getText().get(0),
-                    TextUtils.equals(event.getText().get(0), getString(R.string.android_wiki)));
-            assertEquals("Event from should be start of text skipped.",
-                    CHARACTER_INDICES_OF_PAGE_START[i], event.getFromIndex());
-            assertEquals("Event to should be end of text skipped.",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1], event.getToIndex());
-            // Verify the selection position has changed.
-            assertEquals("Event selection start should match position it moved to.",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1],
-                    Selection.getSelectionStart(editText.getText()));
-            assertEquals("Event selection end should match position it moved to.",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1],
-                    Selection.getSelectionEnd(editText.getText()));
-        }
-
-        // Move back to the beginning
-        for (int i = CHARACTER_INDICES_OF_PAGE_START.length - 2; i >= 0; i--) {
-            AccessibilityEvent event = performMovementActionAndGetEvent(
-                    text,
-                    AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
-                    AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE,
-                    false);
-            assertEquals(event.getClassName(), EditText.class.getName());
-            assertTrue("Event should contain text", event.getText().size() > 0);
-            assertTrue("Event text doesn't match. Expected: " + getString(R.string.android_wiki)
-                            + ". Received:" + event.getText().get(0),
-                    TextUtils.equals(event.getText().get(0), getString(R.string.android_wiki)));
-            assertEquals("Event from should be start of text skipped.",
-                    CHARACTER_INDICES_OF_PAGE_START[i], event.getFromIndex());
-            assertEquals("Event to should be end of text skipped.",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1], event.getToIndex());
-            // Verify the selection position has changed.
-            assertEquals("Event selection start should match position it moved to.",
-                    CHARACTER_INDICES_OF_PAGE_START[i],
-                    Selection.getSelectionStart(editText.getText()));
-            assertEquals("Event selection end should match position it moved to.",
-                    CHARACTER_INDICES_OF_PAGE_START[i],
-                    Selection.getSelectionEnd(editText.getText()));
-        }
-    }
-
-    @MediumTest
-    public void testActionNextAndPreviousAtGranularityPageOverTextExtend() throws Exception {
-        final EditText editText = (EditText) getActivity().findViewById(R.id.edit);
-
-        getInstrumentation().runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.setVisibility(View.VISIBLE);
-                editText.setText(getString(R.string.android_wiki));
-                Selection.removeSelection(editText.getText());
-            }
-        });
-
-        final AccessibilityNodeInfo text = getInstrumentation().getUiAutomation()
-               .getRootInActiveWindow().findAccessibilityNodeInfosByText(getString(
-                       R.string.android_wiki)).get(0);
-
-        final int granularities = text.getMovementGranularities();
-        assertEquals(granularities, AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH
-                | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
-
-        final Bundle arguments = new Bundle();
-        arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
-                AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
-
-        // Move forward a few pages
-        for (int i = 0; i < CHARACTER_INDICES_OF_PAGE_START.length - 1; i++) {
-            AccessibilityEvent event = performMovementActionAndGetEvent(
-                    text,
-                    AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
-                    AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE,
-                    true);
-            assertEquals(event.getClassName(), EditText.class.getName());
-            assertTrue("Event should contain text", event.getText().size() > 0);
-            assertTrue("Event text doesn't match. Expected: " + getString(R.string.android_wiki)
-                            + ". Received:" + event.getText().get(0),
-                    TextUtils.equals(event.getText().get(0), getString(R.string.android_wiki)));
-            assertEquals("Event from should be start of text skipped",
-                    CHARACTER_INDICES_OF_PAGE_START[i], event.getFromIndex());
-            assertEquals("Event to should be end of text skipped",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1], event.getToIndex());
-            // Verify the selection position has changed.
-            assertEquals("Event selection start should stay at beginning",
-                    0, Selection.getSelectionStart(editText.getText()));
-            assertEquals("Event selection end should match current position",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1],
-                    Selection.getSelectionEnd(editText.getText()));
-        }
-
-        // Move back to the beginning
-        for (int i = CHARACTER_INDICES_OF_PAGE_START.length - 2; i >= 0; i--) {
-            AccessibilityEvent event = performMovementActionAndGetEvent(
-                    text,
-                    AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
-                    AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE,
-                    true);
-            assertEquals(event.getClassName(), EditText.class.getName());
-            assertTrue("Event should contain text", event.getText().size() > 0);
-            assertTrue("Event text doesn't match. Expected: " + getString(R.string.android_wiki)
-                            + ". Received:" + event.getText().get(0),
-                    TextUtils.equals(event.getText().get(0), getString(R.string.android_wiki)));
-            assertEquals("Event from should be start of text skipped",
-                    CHARACTER_INDICES_OF_PAGE_START[i], event.getFromIndex());
-            assertEquals("Event to should be end of text skipped",
-                    CHARACTER_INDICES_OF_PAGE_START[i + 1], event.getToIndex());
-            // Verify the selection position has changed.
-            assertEquals("Event selection start should stay at beginning",
-                    0, Selection.getSelectionStart(editText.getText()));
-            assertEquals("Event selection end should match current position",
-                    CHARACTER_INDICES_OF_PAGE_START[i],
-                    Selection.getSelectionEnd(editText.getText()));
-        }
-    }
-
-    @MediumTest
     public void testActionNextAndPreviousAtGranularityParagraphOverText() throws Exception {
         final TextView textView = (TextView) getActivity().findViewById(R.id.edit);
 
diff --git a/tests/admin/Android.mk b/tests/admin/Android.mk
index bd5346d..4457b41 100644
--- a/tests/admin/Android.mk
+++ b/tests/admin/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
-    ctstestrunner mockito-target-minus-junit4
+    ctstestrunner mockito-target-minus-junit4 truth-prebuilt
 
 LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
 
diff --git a/tests/admin/app/AndroidManifest.xml b/tests/admin/app/AndroidManifest.xml
index 0307487..1d901a2 100644
--- a/tests/admin/app/AndroidManifest.xml
+++ b/tests/admin/app/AndroidManifest.xml
@@ -67,6 +67,24 @@
             </intent-filter>
         </receiver>
 
+        <receiver android:name="android.admin.app.CtsDeviceAdminReceiverVisible"
+                  android:permission="android.permission.BIND_DEVICE_ADMIN">
+            <meta-data android:name="android.app.device_admin"
+                       android:resource="@xml/device_admin_visible" />
+            <intent-filter>
+                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
+            </intent-filter>
+        </receiver>
+
+        <receiver android:name="android.admin.app.CtsDeviceAdminReceiverInvisible"
+                  android:permission="android.permission.BIND_DEVICE_ADMIN">
+            <meta-data android:name="android.app.device_admin"
+                       android:resource="@xml/device_admin_invisible" />
+            <intent-filter>
+                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
+            </intent-filter>
+        </receiver>
+
         <!-- Device Admin that needs to be in the deactivated state in order
              for tests to pass. -->
         <receiver android:name="android.admin.app.CtsDeviceAdminDeactivatedReceiver"
diff --git a/tests/admin/app/res/xml/device_admin_invisible.xml b/tests/admin/app/res/xml/device_admin_invisible.xml
new file mode 100644
index 0000000..6af5a60
--- /dev/null
+++ b/tests/admin/app/res/xml/device_admin_invisible.xml
@@ -0,0 +1,24 @@
+<!--
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false">
+    <support-transfer-ownership />
+    <uses-policies>
+        <limit-password />
+        <reset-password />
+        <wipe-data />
+    </uses-policies>
+</device-admin>
diff --git a/tests/admin/app/res/xml/device_admin_visible.xml b/tests/admin/app/res/xml/device_admin_visible.xml
new file mode 100644
index 0000000..5d37a95
--- /dev/null
+++ b/tests/admin/app/res/xml/device_admin_visible.xml
@@ -0,0 +1,24 @@
+<!--
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="true">
+    <support-transfer-ownership />
+    <uses-policies>
+        <limit-password />
+        <reset-password />
+        <wipe-data />
+    </uses-policies>
+</device-admin>
diff --git a/tests/admin/app/src/android/admin/app/CtsDeviceAdminReceiverInvisible.java b/tests/admin/app/src/android/admin/app/CtsDeviceAdminReceiverInvisible.java
new file mode 100644
index 0000000..05f9426
--- /dev/null
+++ b/tests/admin/app/src/android/admin/app/CtsDeviceAdminReceiverInvisible.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.admin.app;
+
+import android.app.admin.DeviceAdminReceiver;
+
+public class CtsDeviceAdminReceiverInvisible extends DeviceAdminReceiver {
+}
diff --git a/tests/admin/app/src/android/admin/app/CtsDeviceAdminReceiverVisible.java b/tests/admin/app/src/android/admin/app/CtsDeviceAdminReceiverVisible.java
new file mode 100644
index 0000000..9bf440a
--- /dev/null
+++ b/tests/admin/app/src/android/admin/app/CtsDeviceAdminReceiverVisible.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.admin.app;
+
+import android.app.admin.DeviceAdminReceiver;
+
+public class CtsDeviceAdminReceiverVisible extends DeviceAdminReceiver {
+}
diff --git a/tests/admin/src/android/admin/cts/DeviceAdminInfoTest.java b/tests/admin/src/android/admin/cts/DeviceAdminInfoTest.java
index 1790503..a0533cd 100644
--- a/tests/admin/src/android/admin/cts/DeviceAdminInfoTest.java
+++ b/tests/admin/src/android/admin/cts/DeviceAdminInfoTest.java
@@ -16,8 +16,11 @@
 
 package android.admin.cts;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import android.app.admin.DeviceAdminInfo;
 import android.content.ComponentName;
+import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.test.AndroidTestCase;
@@ -60,6 +63,16 @@
         return new ComponentName("android.admin.app", "android.admin.app.CtsDeviceAdminProfileOwner");
     }
 
+    static ComponentName getVisibleComponent() {
+        return new ComponentName(
+                "android.admin.app", "android.admin.app.CtsDeviceAdminReceiverVisible");
+    }
+
+    static ComponentName getInvisibleComponent() {
+        return new ComponentName(
+                "android.admin.app", "android.admin.app.CtsDeviceAdminReceiverInvisible");
+    }
+
     public void testDeviceAdminInfo() throws Exception {
         if (!mDeviceAdmin) {
             Log.w(TAG, "Skipping testDeviceAdminInfo");
@@ -70,27 +83,27 @@
                 PackageManager.GET_META_DATA);
 
         DeviceAdminInfo info = new DeviceAdminInfo(mContext, resolveInfo);
-        assertEquals(mComponent, info.getComponent());
-        assertEquals(mComponent.getPackageName(), info.getPackageName());
-        assertEquals(mComponent.getClassName(), info.getReceiverName());
+        assertThat(mComponent).isEqualTo(info.getComponent());
+        assertThat(mComponent.getPackageName()).isEqualTo(info.getPackageName());
+        assertThat(mComponent.getClassName()).isEqualTo(info.getReceiverName());
 
-        assertFalse(info.supportsTransferOwnership());
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA));
+        assertThat(info.supportsTransferOwnership()).isFalse();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK)).isTrue();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD)).isTrue();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD)).isTrue();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN)).isTrue();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA)).isTrue();
 
-        assertEquals("force-lock",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK));
-        assertEquals("limit-password",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
-        assertEquals("reset-password",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD));
-        assertEquals("watch-login",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN));
-        assertEquals("wipe-data",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA));
+        assertThat("force-lock")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK));
+        assertThat("limit-password")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
+        assertThat("reset-password")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD));
+        assertThat("watch-login")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN));
+        assertThat("wipe-data")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA));
     }
 
     public void testDeviceAdminInfo2() throws Exception {
@@ -103,27 +116,27 @@
                 PackageManager.GET_META_DATA);
 
         DeviceAdminInfo info = new DeviceAdminInfo(mContext, resolveInfo);
-        assertEquals(mSecondComponent, info.getComponent());
-        assertEquals(mSecondComponent.getPackageName(), info.getPackageName());
-        assertEquals(mSecondComponent.getClassName(), info.getReceiverName());
+        assertThat(mSecondComponent).isEqualTo(info.getComponent());
+        assertThat(mSecondComponent.getPackageName()).isEqualTo(info.getPackageName());
+        assertThat(mSecondComponent.getClassName()).isEqualTo(info.getReceiverName());
 
-        assertFalse(info.supportsTransferOwnership());
-        assertFalse(info.usesPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD));
-        assertFalse(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN));
-        assertTrue(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA));
+        assertThat(info.supportsTransferOwnership()).isFalse();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK)).isFalse();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD)).isTrue();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD)).isTrue();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN)).isFalse();
+        assertThat(info.usesPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA)).isTrue();
 
-        assertEquals("force-lock",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK));
-        assertEquals("limit-password",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
-        assertEquals("reset-password",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD));
-        assertEquals("watch-login",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN));
-        assertEquals("wipe-data",
-                info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA));
+        assertThat("force-lock")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_FORCE_LOCK));
+        assertThat("limit-password")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
+        assertThat("reset-password")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_RESET_PASSWORD));
+        assertThat("watch-login")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WATCH_LOGIN));
+        assertThat("wipe-data")
+                .isEqualTo(info.getTagForPolicy(DeviceAdminInfo.USES_POLICY_WIPE_DATA));
     }
 
     public void testDeviceAdminInfo3() throws Exception {
@@ -136,6 +149,66 @@
                 PackageManager.GET_META_DATA);
 
         DeviceAdminInfo info = new DeviceAdminInfo(mContext, resolveInfo);
-        assertTrue(info.supportsTransferOwnership());
+        assertThat(info.supportsTransferOwnership()).isTrue();
+    }
+
+    public void testDescribeContents_returnsAtLeastZero() throws Exception {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testDescribeContents_returnsAtLeastZero");
+            return;
+        }
+
+        assertThat(buildDeviceAdminInfo(buildActivityInfo()).describeContents()).isAtLeast(0);
+    }
+
+    public void testGetActivityInfo_returnsActivityInfo() throws Exception {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testGetActivityInfo_returnsActivityInfo");
+            return;
+        }
+        ActivityInfo activityInfo = buildActivityInfo();
+        DeviceAdminInfo deviceAdminInfo = buildDeviceAdminInfo(activityInfo);
+
+        assertThat(deviceAdminInfo.getActivityInfo()).isEqualTo(activityInfo);
+    }
+
+    public void testIsVisible_visibleComponent_returnsTrue() throws Exception {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testIsVisible_visibleComponent_returnsTrue");
+            return;
+        }
+        ActivityInfo activityInfo = buildActivityInfo(getVisibleComponent());
+        DeviceAdminInfo deviceAdminInfo = buildDeviceAdminInfo(activityInfo);
+
+        assertThat(deviceAdminInfo.isVisible()).isTrue();
+    }
+
+    public void testIsVisible_invisibleComponent_returnsFalse() throws Exception {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testIsVisible_invisibleComponent_returnsFalse");
+            return;
+        }
+        ActivityInfo activityInfo = buildActivityInfo(getInvisibleComponent());
+        DeviceAdminInfo deviceAdminInfo = buildDeviceAdminInfo(activityInfo);
+
+        assertThat(deviceAdminInfo.isVisible()).isFalse();
+    }
+
+    private DeviceAdminInfo buildDeviceAdminInfo(ActivityInfo activityInfo) throws Exception {
+        return new DeviceAdminInfo(mContext, buildResolveInfo(activityInfo));
+    }
+
+    private ResolveInfo buildResolveInfo(ActivityInfo activityInfo) {
+        ResolveInfo resolveInfo = new ResolveInfo();
+        resolveInfo.activityInfo = activityInfo;
+        return resolveInfo;
+    }
+
+    private ActivityInfo buildActivityInfo() throws Exception {
+        return buildActivityInfo(mThirdComponent);
+    }
+
+    private ActivityInfo buildActivityInfo(ComponentName componentName) throws Exception {
+        return mPackageManager.getReceiverInfo(componentName, PackageManager.GET_META_DATA);
     }
 }
diff --git a/tests/admin/src/android/admin/cts/DeviceAdminReceiverTest.java b/tests/admin/src/android/admin/cts/DeviceAdminReceiverTest.java
index 4888476..0407811 100644
--- a/tests/admin/src/android/admin/cts/DeviceAdminReceiverTest.java
+++ b/tests/admin/src/android/admin/cts/DeviceAdminReceiverTest.java
@@ -16,10 +16,12 @@
 
 package android.admin.cts;
 
+import static android.app.admin.DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING;
 import static android.app.admin.DeviceAdminReceiver.ACTION_PASSWORD_CHANGED;
 import static android.app.admin.DeviceAdminReceiver.ACTION_PASSWORD_FAILED;
 import static android.app.admin.DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED;
 import static android.app.admin.DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING;
+import static android.app.admin.DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE;
 
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.argThat;
@@ -209,6 +211,34 @@
                 eq(NETWORK_LOGS_TOKEN), eq(NETWORK_LOGS_COUNT));
     }
 
+    @Presubmit
+    public void testOnReceive_enterLockTaskWithoutPackage_callsCallback() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testOnReceive_enterLockTask_callsCallback");
+            return;
+        }
+        final Intent intent = new Intent(ACTION_LOCK_TASK_ENTERING);
+
+        mReceiver.onReceive(mContext, intent);
+
+        verify(mReceiver).onLockTaskModeEntering(mContext, intent, null);
+    }
+
+    @Presubmit
+    public void testOnReceive_enterLockTaskWithPackage_callsCallback() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testOnReceive_enterLockTask_callsCallback");
+            return;
+        }
+        final Intent intent = new Intent(ACTION_LOCK_TASK_ENTERING);
+        final String pkg = "pkg";
+        intent.putExtra(EXTRA_LOCK_TASK_PACKAGE, pkg);
+
+        mReceiver.onReceive(mContext, intent);
+
+        verify(mReceiver).onLockTaskModeEntering(mContext, intent, pkg);
+    }
+
     private Intent actionEq(final String expected) {
         return argThat(x -> expected.equals(x.getAction()));
     }
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 9a4e42c..98fa7af 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -2476,6 +2476,12 @@
                 // Skip unknown templates here
         }
 
+        // Check distortion correction mode
+        if (mStaticInfo.isDistortionCorrectionSupported()) {
+            mCollector.expectKeyValueNotEquals(request, DISTORTION_CORRECTION_MODE,
+                    CaptureRequest.DISTORTION_CORRECTION_MODE_OFF);
+        }
+
         // TODO: use the list of keys from CameraCharacteristics to avoid expecting
         //       keys which are not available by this CameraDevice.
     }
diff --git a/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java b/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java
index c4174ca..4146333 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CaptureResultTest.java
@@ -26,6 +26,7 @@
 import android.hardware.camera2.TotalCaptureResult;
 import android.media.Image;
 import android.media.ImageReader;
+import android.os.Build;
 import android.os.SystemClock;
 import android.platform.test.annotations.AppModeFull;
 import android.util.Pair;
@@ -473,6 +474,10 @@
                         errorCollector.expectEquals(msg,
                                 requestBuilder.get(CaptureRequest.STATISTICS_OIS_DATA_MODE),
                                 result.get(CaptureResult.STATISTICS_OIS_DATA_MODE));
+                    } else if (key.equals(CaptureResult.DISTORTION_CORRECTION_MODE)) {
+                         errorCollector.expectEquals(msg,
+                                requestBuilder.get(CaptureRequest.DISTORTION_CORRECTION_MODE),
+                                result.get(CaptureResult.DISTORTION_CORRECTION_MODE));
                     } else {
                         // Only do non-null check for the rest of keys.
                         errorCollector.expectKeyValueNotNull(failMsg, result, key);
@@ -552,23 +557,9 @@
         }
 
         //Keys for lens distortion correction
-        boolean distortionCorrectionSupported = false;
-        int[] distortionModes = staticInfo.getCharacteristics().get(
-                CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES);
-        if (distortionModes == null) {
+        boolean distortionCorrectionSupported = staticInfo.isDistortionCorrectionSupported();
+        if (!distortionCorrectionSupported) {
             waiverKeys.add(CaptureResult.DISTORTION_CORRECTION_MODE);
-        } else {
-            boolean gotNonOff = false;
-            for (int mode : distortionModes) {
-                if (mode != CaptureRequest.DISTORTION_CORRECTION_MODE_OFF) {
-                    gotNonOff = true;
-                    distortionCorrectionSupported = true;
-                    break;
-                }
-            }
-            if (!gotNonOff) {
-                waiverKeys.add(CaptureResult.DISTORTION_CORRECTION_MODE);
-            }
         }
 
         // These keys must present on either DEPTH or distortion correction devices
@@ -578,9 +569,16 @@
             waiverKeys.add(CaptureResult.LENS_INTRINSIC_CALIBRATION);
             waiverKeys.add(CaptureResult.LENS_RADIAL_DISTORTION);
             waiverKeys.add(CaptureResult.LENS_DISTORTION);
+        } else {
+            // Radial distortion doesn't need to be present for new devices, or old devices that
+            // opt in the new lens distortion tag.
+            CameraCharacteristics c = staticInfo.getCharacteristics();
+            if (Build.VERSION.FIRST_SDK_INT > Build.VERSION_CODES.O_MR1 ||
+                    c.get(CameraCharacteristics.LENS_DISTORTION) != null) {
+                waiverKeys.add(CaptureResult.LENS_RADIAL_DISTORTION);
+            }
         }
 
-
         // Waived if RAW output is not supported
         int[] outputFormats = staticInfo.getAvailableFormats(
                 StaticMetadata.StreamDirection.Output);
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index 22851e6..7476747 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -885,8 +885,34 @@
             Integer poseReference = c.get(CameraCharacteristics.LENS_POSE_REFERENCE);
             float[] cameraIntrinsics = c.get(CameraCharacteristics.LENS_INTRINSIC_CALIBRATION);
             float[] distortion = getLensDistortion(c);
+            Size pixelArraySize = c.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);
             Rect precorrectionArray = c.get(
                 CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
+            Rect activeArray = c.get(
+                CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
+
+            // Verify pre-correction array encloses active array
+            mCollector.expectTrue("preCorrectionArray [" + precorrectionArray.left + ", " +
+                    precorrectionArray.top + ", " + precorrectionArray.right + ", " +
+                    precorrectionArray.bottom + "] does not enclose activeArray[" +
+                    activeArray.left + ", " + activeArray.top + ", " + activeArray.right +
+                    ", " + activeArray.bottom,
+                    precorrectionArray.contains(activeArray.left, activeArray.top) &&
+                    precorrectionArray.contains(activeArray.right-1, activeArray.bottom-1));
+
+            // Verify pixel array encloses pre-correction array
+            mCollector.expectTrue("preCorrectionArray [" + precorrectionArray.left + ", " +
+                    precorrectionArray.top + ", " + precorrectionArray.right + ", " +
+                    precorrectionArray.bottom + "] isn't enclosed by pixelArray[" +
+                    pixelArraySize.getWidth() + ", " + pixelArraySize.getHeight() + "]",
+                    precorrectionArray.left >= 0 &&
+                    precorrectionArray.left < pixelArraySize.getWidth() &&
+                    precorrectionArray.right > 0 &&
+                    precorrectionArray.right <= pixelArraySize.getWidth() &&
+                    precorrectionArray.top >= 0 &&
+                    precorrectionArray.top < pixelArraySize.getHeight() &&
+                    precorrectionArray.bottom > 0 &&
+                    precorrectionArray.bottom <= pixelArraySize.getHeight());
 
             if (supportDepth) {
                 mCollector.expectTrue("Supports DEPTH_OUTPUT but does not support DEPTH16",
diff --git a/tests/camera/src/android/hardware/cts/CameraTest.java b/tests/camera/src/android/hardware/cts/CameraTest.java
index 9efccf1..81b42ef 100644
--- a/tests/camera/src/android/hardware/cts/CameraTest.java
+++ b/tests/camera/src/android/hardware/cts/CameraTest.java
@@ -194,6 +194,13 @@
      * Terminates the message looper thread.
      */
     private void terminateMessageLooper() throws Exception {
+        terminateMessageLooper(false);
+    }
+
+    /*
+     * Terminates the message looper thread, optionally allowing evict error
+     */
+    private void terminateMessageLooper(boolean allowEvict) throws Exception {
         mLooper.quit();
         // Looper.quit() is asynchronous. The looper may still has some
         // preview callbacks in the queue after quit is called. The preview
@@ -203,7 +210,13 @@
         mLooper.getThread().join();
         mCamera.release();
         mCamera = null;
-        assertEquals("Got camera error callback.", NO_ERROR, mCameraErrorCode);
+        if (allowEvict) {
+            assertTrue("Got unexpected camera error callback.",
+                    (NO_ERROR == mCameraErrorCode ||
+                    Camera.CAMERA_ERROR_EVICTED == mCameraErrorCode));
+        } else {
+            assertEquals("Got camera error callback.", NO_ERROR, mCameraErrorCode);
+        }
     }
 
     // Align 'x' to 'to', which should be a power of 2
@@ -2501,7 +2514,7 @@
         mCamera.stopPreview();
 
         firstLooper.quit();
-        terminateMessageLooper();
+        terminateMessageLooper(true/*allowEvict*/);
     }
 
     // This callback just signals on the condition variable, making it useful for checking that
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 0d0e592..646dfe7 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -2357,6 +2357,26 @@
     }
 
     /**
+     * Check if distortion correction is supported.
+     */
+    public boolean isDistortionCorrectionSupported() {
+        boolean distortionCorrectionSupported = false;
+        int[] distortionModes = mCharacteristics.get(
+                CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES);
+        if (distortionModes == null) {
+            return false;
+        }
+
+        for (int mode : distortionModes) {
+            if (mode != CaptureRequest.DISTORTION_CORRECTION_MODE_OFF) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    /**
      * Get the value in index for a fixed-size array from a given key.
      *
      * <p>If the camera device is incorrectly reporting values, log a warning and return
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index c812e91..f82e43f 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -379,4 +379,8 @@
             assertCanBeHandled(new Intent(Settings.ACTION_NFC_PAYMENT_SETTINGS));
         }
     }
+
+    public void testPowerUsageSummarySettings() {
+        assertCanBeHandled(new Intent(Intent.ACTION_POWER_USAGE_SUMMARY));
+    }
 }
diff --git a/tests/tests/graphics/AndroidManifest.xml b/tests/tests/graphics/AndroidManifest.xml
index dd80315..76552a1 100644
--- a/tests/tests/graphics/AndroidManifest.xml
+++ b/tests/tests/graphics/AndroidManifest.xml
@@ -38,7 +38,6 @@
 
         <activity android:name="android.graphics.cts.VulkanPreTransformCtsActivity"
             android:label="VulkanPreTransformCtsActivity"
-            android:screenOrientation="landscape"
             android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
         </activity>
 
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
index 591c280..4b9aa0e 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
@@ -17,11 +17,15 @@
 package android.graphics.cts;
 
 import android.app.Activity;
+import android.content.Context;
+import android.content.pm.ActivityInfo;
 import android.content.res.AssetManager;
+import android.content.res.Configuration;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.Surface;
 import android.view.SurfaceView;
+import android.view.WindowManager;
 
 /**
  * Activity for VulkanPreTransformTest.
@@ -33,19 +37,51 @@
 
     private static final String TAG = VulkanPreTransformCtsActivity.class.getSimpleName();
 
+    private static boolean sOrientationRequested = false;
+    private static boolean sClockwiseRotation = false;
+
     protected Surface mSurface;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         Log.d(TAG, "onCreate!");
+        setActivityOrientation();
         setContentView(R.layout.vulkan_pretransform_layout);
         SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
         mSurface = surfaceView.getHolder().getSurface();
     }
 
+    private void setActivityOrientation() {
+        if (sOrientationRequested) {
+            // it might be called again because changing the orientation kicks off onCreate again!.
+            return;
+        }
+
+        if (((WindowManager) getSystemService(Context.WINDOW_SERVICE))
+                        .getDefaultDisplay()
+                        .getRotation()
+                != Surface.ROTATION_0) {
+            throw new RuntimeException("Display not in natural orientation");
+        }
+
+        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
+            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+            sClockwiseRotation = true;
+        } else {
+            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+        }
+        sOrientationRequested = true;
+    }
+
+    public boolean getRotation() {
+        return sClockwiseRotation;
+    }
+
     public void testVulkanPreTransform(boolean setPreTransform) {
         nCreateNativeTest(getAssets(), mSurface, setPreTransform);
+        sOrientationRequested = false;
+        sClockwiseRotation = false;
     }
 
     private static native void nCreateNativeTest(
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
index c220867..7b87948 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
@@ -38,10 +38,11 @@
 import org.junit.runner.RunWith;
 
 /*
- * This test case runs in landscape mode
- *
  * testVulkanPreTransformSetToMatchCurrentTransform()
  *
+ *   This test case runs in landscape mode for portrait device (default orientation is portrait),
+ *   the result is 90 degree CCW rotation.
+ *
  *      Buffer          ExpectedScreen
  *      ---------       ---------------
  *      | R | G |       | GGGG | YYYY |
@@ -49,6 +50,18 @@
  *      | B | Y |       | RRRR | BBBB |
  *      ---------       ---------------
  *
+ *   This test case runs in portrait mode for landscape device (default orientation is landscape),
+ *   the result is 90 degree CW rotation.
+ *
+ *      Buffer          ExpectedScreen
+ *      ---------       -----------
+ *      | R | G |       | BB | RR |
+ *      ---------       | BB | RR |
+ *      | B | Y |       -----------
+ *      ---------       | YY | GG |
+ *                      | YY | GG |
+ *                      -----------
+ *
  * testVulkanPreTransformNotSetToMatchCurrentTransform()
  *
  *      Buffer          ExpectedScreen
@@ -126,11 +139,19 @@
         int width = bitmap.getWidth();
         int height = bitmap.getHeight();
         int diff = 0;
-        if (setPreTransform) {
+        boolean clockwiseRotation = sActivity.getRotation();
+        if (setPreTransform && !clockwiseRotation) {
+            // app orientation landscape
             diff += pixelDiff(bitmap.getPixel(0, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 0, 255);
+        } else if (setPreTransform && clockwiseRotation) {
+            // app orientation portrait
+            diff += pixelDiff(bitmap.getPixel(0, 0), 0, 0, 255);
+            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 0, 0);
+            diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 255, 0);
         } else {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 255, 0);
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
index de0d441..643fd75 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
+++ b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
@@ -48,6 +48,8 @@
 static const std::string kProductLibraryPath = "/product/lib";
 #endif
 
+static const std::string kWebViewPlatSupportLib = "libwebviewchromium_plat_support.so";
+
 // This is not the complete list - just a small subset
 // of the libraries that should reside in /system/lib
 // for app-compatibility reasons.
@@ -117,6 +119,12 @@
     error = dlerror();
   }
 
+  if (android::base::EndsWith(path, '/' + kWebViewPlatSupportLib)) {
+    // Don't try to load this library from Java. Otherwise, the lib is initialized via
+    // JNI_OnLoad and it fails since WebView is not loaded in this test process.
+    return error;
+  }
+
   // try to load the same lib using System.load() in Java to see if it gives consistent
   // result with dlopen.
   static jmethodID load_library = env->GetStaticMethodID(clazz, "loadSharedLibrary",
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index 31d9844..3b3c972 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -225,11 +225,6 @@
 
     private static boolean loadSharedLibrary(String libFilePath) {
         String baseName = new File(libFilePath).getName();
-        if (baseName.equals(WEBVIEW_PLAT_SUPPORT_LIB)) {
-          // Don't try to load this library from Java. Otherwise, the lib is initialized via
-          // JNI_OnLoad and it fails since WebView is not loaded in this test process.
-          return true;
-        }
         try {
             System.load(libFilePath);
             // Also ensure that the lib is also accessible via its libname.
diff --git a/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java b/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java
index 1cb02d4..216989f 100644
--- a/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java
@@ -20,7 +20,9 @@
 import android.location.GnssMeasurementsEvent;
 import android.util.Log;
 
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 /**
  * Test the {@link GnssMeasurement} values.
@@ -31,8 +33,8 @@
  * 3. Wait for {@link #LOCATION_TO_COLLECT_COUNT} locations.
  *          3.1 Confirm locations have been found.
  * 4. Check {@link GnssMeasurementsEvent} status: if the status is not
- *    {@link GnssMeasurementsEvent#STATUS_READY}, the test will be skipped because one of the
- *    following reasons:
+ *    {@link GnssMeasurementsEvent.Callback#STATUS_READY}, the test will be skipped because
+ *    one of the following reasons:
  *          4.1 the device does not support the GPS feature,
  *          4.2 GPS Location is disabled in the device and this is CTS (non-verifier)
  *  5. Verify {@link GnssMeasurement}s (all mandatory fields), the test will fail if any of the
@@ -42,15 +44,19 @@
 
     private static final String TAG = "GnssMeasValuesTest";
     private static final int LOCATION_TO_COLLECT_COUNT = 5;
+    private static final int YEAR_2017 = 2017;
 
     private TestGnssMeasurementListener mMeasurementListener;
     private TestLocationListener mLocationListener;
+    // Store list of Satellites including Gnss Band, constellation & SvId
+    private Set<String> mGnssMeasSvStringIds;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
 
         mTestLocationManager = new TestLocationManager(getContext());
+        mGnssMeasSvStringIds = new HashSet<>();
     }
 
     @Override
@@ -73,7 +79,7 @@
     public void testListenForGnssMeasurements() throws Exception {
         // Checks if GPS hardware feature is present, skips test (pass) if not,
         // and hard asserts that Location/GPS (Provider) is turned on if is Cts Verifier.
-       if (!TestMeasurementUtil.canTestRunOnCurrentDevice(mTestLocationManager,
+        if (!TestMeasurementUtil.canTestRunOnCurrentDevice(mTestLocationManager,
                 TAG, MIN_HARDWARE_YEAR_MEASUREMENTS_REQUIRED, isCtsVerifierTest())) {
             return;
         }
@@ -84,12 +90,19 @@
         mMeasurementListener = new TestGnssMeasurementListener(TAG);
         mTestLocationManager.registerGnssMeasurementCallback(mMeasurementListener);
 
+        // Register a status callback to enable checking Svs across status & measurements.
+        // Count in status callback is not important as this test is pass/fail based on
+        // measurement count, not status count.
+        TestGnssStatusCallback gnssStatusCallback = new TestGnssStatusCallback(TAG, 0);
+        mTestLocationManager.registerGnssStatusCallback(gnssStatusCallback);
+
         boolean success = mLocationListener.await();
         SoftAssert.failOrWarning(isMeasurementTestStrict(),
                 "Time elapsed without getting enough location fixes."
                         + " Possibly, the test has been run deep indoors."
                         + " Consider retrying test outdoors.",
                 success);
+        mTestLocationManager.unregisterGnssStatusCallback(gnssStatusCallback);
 
         Log.i(TAG, "Location status received = " + mLocationListener.isLocationReceived());
 
@@ -123,12 +136,34 @@
                         measurement, softAssert, timeInNs);
                 carrierPhaseQualityPrrFound |=
                         TestMeasurementUtil.gnssMeasurementHasCarrierPhasePrr(measurement);
+                if (measurement.hasCarrierFrequencyHz()) {
+                    mGnssMeasSvStringIds.add(
+                        TestMeasurementUtil.getUniqueSvStringId(measurement.getConstellationType(),
+                            measurement.getSvid(), measurement.getCarrierFrequencyHz()));
+                } else {
+                    mGnssMeasSvStringIds.add(
+                        TestMeasurementUtil.getUniqueSvStringId(measurement.getConstellationType(),
+                            measurement.getSvid()));
+                }
             }
         }
         softAssert.assertOrWarnTrue(isMeasurementTestStrict(),
                 "GNSS Measurements PRRs with Carrier Phase "
                         + "level uncertainties.  If failed, retry near window or outdoors?",
                 carrierPhaseQualityPrrFound);
+        Log.i(TAG, "Meas received for:" + mGnssMeasSvStringIds);
+        Log.i(TAG, "Status Received for:" + gnssStatusCallback.getGnssUsedSvStringIds());
+        if (mTestLocationManager.getLocationManager().getGnssYearOfHardware() >= YEAR_2017) {
+            // Get all SVs marked as USED in GnssStatus. Remove any SV for which measurement
+            // is received. The resulting list should ideally be empty (How can you use a SV
+            // with no measurement). To allow for race condition where the last GNSS Status
+            // has 1 SV with used flag set, but the corresponding measurement has not yet been
+            // received, the check is done as <= 1
+            Set<String> svDiff = gnssStatusCallback.getGnssUsedSvStringIds();
+            svDiff.removeAll(mGnssMeasSvStringIds);
+            softAssert.assertTrue("Used Svs with no Meas: " + (svDiff.isEmpty() ? "None" : svDiff),
+                svDiff.size() <= 1);
+        }
         softAssert.assertAll();
     }
 }
diff --git a/tests/tests/location/src/android/location/cts/GnssStatusTest.java b/tests/tests/location/src/android/location/cts/GnssStatusTest.java
index 003d969..1f7ffa4 100644
--- a/tests/tests/location/src/android/location/cts/GnssStatusTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssStatusTest.java
@@ -8,7 +8,6 @@
     private static final String TAG = "GnssStatusTest";
     private static final int LOCATION_TO_COLLECT_COUNT = 1;
     private static final int STATUS_TO_COLLECT_COUNT = 3;
-    private static final int YEAR_2018 = 2018;
 
   @Override
   protected void setUp() throws Exception {
@@ -108,7 +107,7 @@
       TestMeasurementUtil.validateSvidSub(softAssert, null,
           status.getConstellationType(i),status.getSvid(i));
 
-      // For those function with boolean type return, just simplly call the function
+      // For those function with boolean type return, just simply call the function
       // to make sure those function won't crash, also increase the test coverage.
       Log.i(TAG, "hasAlmanacData: " + status.hasAlmanacData(i));
       Log.i(TAG, "hasEphemerisData: " + status.hasEphemerisData(i));
diff --git a/tests/tests/location/src/android/location/cts/GnssTestCase.java b/tests/tests/location/src/android/location/cts/GnssTestCase.java
index 0258244..508e0da 100644
--- a/tests/tests/location/src/android/location/cts/GnssTestCase.java
+++ b/tests/tests/location/src/android/location/cts/GnssTestCase.java
@@ -15,8 +15,11 @@
  */
 package android.location.cts;
 
+import android.content.pm.PackageManager;
 import android.test.AndroidTestCase;
-import android.util.Log;
+
+import com.android.compatibility.common.util.FeatureUtil;
+import com.android.compatibility.common.util.PropertyUtil;
 
 /**
  * Base Test Case class for all Gnss Tests.
@@ -32,14 +35,16 @@
     protected GnssTestCase() {
     }
 
-    // When CTS testing is run in Verifier mode access to GNSS signals is expected
-    // On devices using newer hardware, GNSS measurement support is required.
-    // Hence when both conditions are true, we can verify stricter tests of functionality
-    // availability.
+    // When using newer hardware, GNSS measurement support is required.
     protected boolean isMeasurementTestStrict() {
+        if (FeatureUtil.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            return false;
+        }
+        if (PropertyUtil.isFactoryROM()) {
+            return true;
+        }
         return ((mTestLocationManager.getLocationManager().getGnssYearOfHardware() >=
-                 MIN_HARDWARE_YEAR_MEASUREMENTS_REQUIRED) &&
-                isCtsVerifierTest());
+                MIN_HARDWARE_YEAR_MEASUREMENTS_REQUIRED));
     }
 
     public void setTestAsCtsVerifierTest(boolean value) {
@@ -49,4 +54,4 @@
     public boolean isCtsVerifierTest() {
         return mCtsVerifierTest;
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java b/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java
index 1b8c3c3..3a64c46 100644
--- a/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java
+++ b/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java
@@ -25,7 +25,6 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
 
 /**
  * Used for receiving GPS satellite measurements from the GPS engine.
@@ -39,7 +38,6 @@
     // Timeout in sec for count down latch wait
     private static final int STATUS_TIMEOUT_IN_SEC = 10;
     private static final int MEAS_TIMEOUT_IN_SEC = 60;
-    private static final int TOW_DECODED_MEASUREMENT_STATE_BIT = 3;
     private static final int C_TO_N0_THRESHOLD_DB_HZ = 18;
     private volatile int mStatus = -1;
 
@@ -89,15 +87,15 @@
                 HashMap<Integer, Integer> constellationEventCount = new HashMap<>();
                 GnssClock gnssClock = event.getClock();
                 if (!gnssClock.hasFullBiasNanos()) {
-                    // If devices does not have FullBiasNanos yet, it will be difficult to check the quality, so await 
-                    // this flag as well.
+                    // If devices does not have FullBiasNanos yet, it will be difficult to check
+                    // the quality, so await this flag as well.
                     return;
                 }
                 for (GnssMeasurement gnssMeasurement : event.getMeasurements()){
                     int constellationType = gnssMeasurement.getConstellationType();
                     // if the measurement's signal level is too small ignore
                     if (gnssMeasurement.getCn0DbHz() < C_TO_N0_THRESHOLD_DB_HZ ||
-                        (gnssMeasurement.getState() & (1L << TOW_DECODED_MEASUREMENT_STATE_BIT)) == 0) {
+                        (gnssMeasurement.getState() & GnssMeasurement.STATE_TOW_DECODED) == 0) {
                         continue;
                     }
                     if (constellationEventCount.containsKey(constellationType)) {
diff --git a/tests/tests/location/src/android/location/cts/TestGnssStatusCallback.java b/tests/tests/location/src/android/location/cts/TestGnssStatusCallback.java
index 38b749f..76c94da 100644
--- a/tests/tests/location/src/android/location/cts/TestGnssStatusCallback.java
+++ b/tests/tests/location/src/android/location/cts/TestGnssStatusCallback.java
@@ -19,10 +19,9 @@
 import android.location.GnssStatus;
 
 import android.util.Log;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
 import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
 
 /**
  * Used for receiving notifications when GNSS status has changed.
@@ -30,7 +29,6 @@
 class TestGnssStatusCallback extends GnssStatus.Callback {
 
     private final String mTag;
-    private volatile boolean mGpsStatusReceived;
     private GnssStatus mGnssStatus = null;
     // Timeout in sec for count down latch wait
     private static final int TIMEOUT_IN_SEC = 90;
@@ -39,8 +37,8 @@
     private final CountDownLatch mLatchTtff;
     private final CountDownLatch mLatchStop;
 
-    // Store list of Prn for Satellites.
-    private List<List<Integer>> mGpsSatellitePrns;
+    // Store list of Satellites including Gnss Band, constellation & SvId
+    private Set<String> mGnssUsedSvStringIds;
 
     TestGnssStatusCallback(String tag, int gpsStatusCountToCollect) {
         this.mTag = tag;
@@ -48,7 +46,7 @@
         mLatchStatus = new CountDownLatch(gpsStatusCountToCollect);
         mLatchTtff = new CountDownLatch(1);
         mLatchStop = new CountDownLatch(1);
-        mGpsSatellitePrns = new ArrayList<List<Integer>>();
+        mGnssUsedSvStringIds = new HashSet<>();
     }
 
     @Override
@@ -73,32 +71,36 @@
     public void onSatelliteStatusChanged(GnssStatus status) {
         Log.i(mTag, "Gnss Status Listener Received Status Update");
         mGnssStatus = status;
+        for (int i = 0; i < status.getSatelliteCount(); i++) {
+            if (!status.usedInFix(i)) {
+                continue;
+            }
+            if (status.hasCarrierFrequencyHz(i)) {
+                mGnssUsedSvStringIds.add(
+                    TestMeasurementUtil.getUniqueSvStringId(status.getConstellationType(i),
+                        status.getSvid(i), status.getCarrierFrequencyHz(i)));
+            } else {
+                mGnssUsedSvStringIds.add(
+                    TestMeasurementUtil.getUniqueSvStringId(status.getConstellationType(i),
+                        status.getSvid(i)));
+            }
+        }
         mLatchStatus.countDown();
     }
 
     /**
-     * Returns the list of PRNs (pseudo-random number) for the satellite.
+     * Returns the list of SV String Ids which were used in fix during the collect
      *
-     * @return list of PRNs number
+     * @return mGnssUsedSvStringIds - Set of SV string Ids
      */
-    public List<List<Integer>> getGpsSatellitePrns() {
-        return mGpsSatellitePrns;
+    public Set<String> getGnssUsedSvStringIds() {
+        return mGnssUsedSvStringIds;
     }
 
     /**
-     * Check if GPS Status is received.
+     * Get GNSS Status.
      *
-     * @return {@code true} if the GPS Status is received and {@code false}
-     *         if GPS Status is not received.
-     */
-    public boolean isGpsStatusReceived() {
-        return mGpsStatusReceived;
-    }
-
-    /**
-     * Get GPS Status.
-     *
-     * @return mGpsStatus GPS Status
+     * @return mGnssStatus GNSS Status
      */
     public GnssStatus getGnssStatus() {
         return mGnssStatus;
diff --git a/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java b/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
index c2541d3..7852361 100644
--- a/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
+++ b/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
@@ -57,6 +57,13 @@
     private static final int YEAR_2017 = 2017;
     private static final int YEAR_2018 = 2018;
 
+    private enum GnssBand {
+        GNSS_L1,
+        GNSS_L2,
+        GNSS_L5,
+        GNSS_E6
+    }
+
     // The valid Gnss navigation message type as listed in
     // android/hardware/libhardware/include/hardware/gps.h
     public static final Set<Integer> GNSS_NAVIGATION_MESSAGE_TYPE =
@@ -334,7 +341,6 @@
     private static void verifySvid(GnssMeasurement measurement, SoftAssert softAssert,
         long timeInNs) {
 
-        String svidLogMessageFormat = "svid: Space Vehicle ID. Constellation type = %s";
         int constellationType = measurement.getConstellationType();
         int svid = measurement.getSvid();
         validateSvidSub(softAssert, timeInNs, constellationType, svid);
@@ -637,7 +643,7 @@
         }
     }
 
-    private static String getReceivedSvTimeNsLogMessage(String constellationType, String state) {
+    private static String getReceivedSvTimeNsLogMessage(String state, String constellationType) {
         return "received_sv_time_ns: Received SV Time-of-Week in ns. Constellation type = "
                 + constellationType + ". State = " + state;
     }
@@ -700,6 +706,34 @@
         }
     }
 
+
+    /**
+     * Get a unique string for the SV including the constellation and the default L1 band.
+     *
+     * @param constellationType Gnss Constellation type
+     * @param svId Gnss Sv Identifier
+     */
+    public static String getUniqueSvStringId(int constellationType, int svId) {
+        return getUniqueSvStringId(constellationType, svId, GnssBand.GNSS_L1);
+    }
+
+    /**
+     * Get a unique string for the SV including the constellation and the band.
+     *
+     * @param constellationType Gnss Constellation type
+     * @param svId Gnss Sv Identifier
+     * @param carrierFrequencyHz Carrier Frequency for Sv in Hz
+     */
+    public static String getUniqueSvStringId(int constellationType, int svId,
+        float carrierFrequencyHz) {
+        return getUniqueSvStringId(constellationType, svId,
+            frequencyToGnssBand(carrierFrequencyHz));
+    }
+
+    private static String getUniqueSvStringId(int constellationType, int svId, GnssBand gnssBand) {
+        return gnssBand.toString() + "." + constellationType + "." + svId;
+    }
+
     /**
      * Assert all mandatory fields in Gnss Navigation Message are in expected range.
      * See mandatory fields in {@code gps.h}.
@@ -788,4 +822,25 @@
 
         return typesStr.length() > 2 ? typesStr.substring(0, typesStr.length() - 2) : "";
     }
+
+    /**
+     * The band information is as of 2018, per http://www.navipedia.net/index.php/GNSS_signal
+     * Bands are combined for simplicity as the constellation is also tracked.
+     *
+     * @param frequencyHz Frequency in Hz
+     * @return GnssBand where the frequency lies.
+     */
+    private static GnssBand frequencyToGnssBand(float frequencyHz) {
+        float frequencyMhz = frequencyHz/1e6F;
+        if (frequencyMhz >= 1151 && frequencyMhz <= 1214) {
+            return GnssBand.GNSS_L5;
+        }
+        if (frequencyMhz > 1214 && frequencyMhz <= 1255) {
+            return GnssBand.GNSS_L2;
+        }
+        if (frequencyMhz > 1255 && frequencyMhz <= 1300) {
+            return GnssBand.GNSS_E6;
+        }
+        return GnssBand.GNSS_L1; // default to L1 band
+    }
 }
diff --git a/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java b/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java
index 1b1e669..2f155d8 100644
--- a/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java
@@ -86,7 +86,6 @@
         "android.intent.action.NETWORK_SET_TIME",
         "android.intent.action.NETWORK_SET_TIMEZONE",
         "com.android.internal.intent.action.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS",
-        "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED",
     };
 
     /**
diff --git a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
index 34b6411..438857d 100644
--- a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
+++ b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
@@ -83,10 +83,10 @@
             {(byte) 0x80, 0x08, 0x00, 0x00, 0x00},
             {(byte) 0xA0, 0x08, 0x00, 0x00, 0x00},
             {(byte) 0x94, 0x08, 0x00, 0x00, 0x00},
-            {0x00, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
-            {(byte) 0x80, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
-            {(byte) 0xA0, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
-            {(byte) 0x94, (byte) 0xC0, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00}
+            {0x00, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
+            {(byte) 0x80, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
+            {(byte) 0xA0, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00},
+            {(byte) 0x94, (byte) 0x0C, 0x00, 0x00, 0x01, (byte) 0xAA, 0x00}
     };
 
     private final static byte[] CHECK_SELECT_P2_APDU = new byte[]{0x00, (byte) 0xF4, 0x00, 0x00};
diff --git a/tests/tests/security/res/raw/cve_2016_3920.mp3 b/tests/tests/security/res/raw/cve_2016_3920.mp3
new file mode 100644
index 0000000..8c2abfc
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2016_3920.mp3
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 07033c7..a588cf0 100755
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -303,6 +303,11 @@
      ***********************************************************/
 
     @SecurityTest
+    public void testStagefright_cve_2016_3920() throws Exception {
+        doStagefrightTest(R.raw.cve_2016_3920);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_68953854() throws Exception {
         doStagefrightTest(R.raw.bug_68953854, 1 * 60 * 1000);
     }
diff --git a/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java b/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java
index 357ffb3..7462566 100755
--- a/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java
+++ b/tests/tests/uiautomation/src/android/app/uiautomation/cts/UiAutomationTest.java
@@ -62,7 +62,6 @@
         grantWriteSecureSettingsPermission(uiAutomation);
     }
 
-    @Presubmit
     public void testWindowContentFrameStats() throws Exception {
         Activity activity = null;
         try {
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
index 422201c..74786e4 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
@@ -542,6 +542,14 @@
             return; // no WebView to run test on
         }
         CountDownLatch hwFence = new CountDownLatch(1);
+        Point[] testPoints = new Point[] {
+            // solid area
+            new Point(0, 0),
+            new Point(0, TEST_HEIGHT - 1),
+            // fade area
+            new Point(0, TEST_HEIGHT - 10),
+            new Point(0, TEST_HEIGHT - 5)
+        };
         createTest()
                 .addLayout(R.layout.test_content_webview, (ViewInitializer) view -> {
                     WebView webview = view.requireViewById(R.id.webview);
@@ -551,16 +559,14 @@
                     webview.setVerticalScrollBarEnabled(false);
                     webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
 
+                    // Adjust Y to match the same gradient percentage, regardless of vertical
+                    // fading edge length.
+                    int verticalFadingEdgeLength = webview.getVerticalFadingEdgeLength();
+                    testPoints[2].y = TEST_HEIGHT - verticalFadingEdgeLength * 10 / 42;
+                    testPoints[3].y = TEST_HEIGHT - verticalFadingEdgeLength * 5 / 42;
                 }, true, hwFence)
                 .runWithVerifier(new SamplePointVerifier(
-                        new Point[] {
-                                // solid area
-                                new Point(0, 0),
-                                new Point(0, TEST_HEIGHT - 1),
-                                // fade area
-                                new Point(0, TEST_HEIGHT - 10),
-                                new Point(0, TEST_HEIGHT - 5)
-                        },
+                        testPoints,
                         new int[] {
                                 Color.BLUE,
                                 Color.WHITE,
@@ -576,6 +582,16 @@
             return; // no WebView to run test on
         }
         CountDownLatch hwFence = new CountDownLatch(1);
+        Point[] testPoints = new Point[] {
+            // solid white area
+            new Point(0, 0),
+            new Point(0, TEST_HEIGHT - 1),
+            // solid blue area
+            new Point(TEST_WIDTH / 2 , 5),
+            // fade area
+            new Point(TEST_WIDTH / 2, TEST_HEIGHT - 10),
+            new Point(TEST_WIDTH / 2, TEST_HEIGHT - 5)
+        };
         createTest()
                 .addLayout(R.layout.circle_clipped_webview, (ViewInitializer) view -> {
                     WebView webview = view.requireViewById(R.id.webview);
@@ -584,19 +600,14 @@
                     webview.setVerticalFadingEdgeEnabled(true);
                     webview.setVerticalScrollBarEnabled(false);
                     webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
-
+                    // Adjust Y to match the same gradient percentage, regardless of vertical
+                    // fading edge length.
+                    int verticalFadingEdgeLength = webview.getVerticalFadingEdgeLength();
+                    testPoints[3].y = TEST_HEIGHT - verticalFadingEdgeLength * 10 / 42;
+                    testPoints[4].y = TEST_HEIGHT - verticalFadingEdgeLength * 5 / 42;
                 }, true, hwFence)
                 .runWithVerifier(new SamplePointVerifier(
-                        new Point[] {
-                                // solid white area
-                                new Point(0, 0),
-                                new Point(0, TEST_HEIGHT - 1),
-                                // solid blue area
-                                new Point(TEST_WIDTH / 2 , 5),
-                                // fade area
-                                new Point(TEST_WIDTH / 2, TEST_HEIGHT - 10),
-                                new Point(TEST_WIDTH / 2, TEST_HEIGHT - 5)
-                        },
+                        testPoints,
                         new int[] {
                                 Color.WHITE,
                                 Color.WHITE,
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java b/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java
index eb5b413..fedf521 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java
@@ -108,7 +108,4 @@
         }.run();
     }
 
-    public void testClone() {
-    }
-
 }