Merge "Workaround to let SettingsUtils handle empty settings values." into qt-dev
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
index ccef312..7f4de46 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
@@ -162,7 +162,6 @@
 
         if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
             forwardedIntentsFromManaged.addAll(Arrays.asList(
-                    new Intent(Intent.ACTION_DIAL).setData(Uri.parse("tel:123")),
                     new Intent("android.intent.action.CALL_EMERGENCY").setData(
                             Uri.parse("tel:123")),
                     new Intent("android.intent.action.CALL_PRIVILEGED").setData(
@@ -188,8 +187,9 @@
                             Uri.parse("mmsto:07700900100?body=Hello%20world")).addCategory(
                             Intent.CATEGORY_BROWSABLE),
                     new Intent(Settings.ACTION_APN_SETTINGS)));
-            notForwardedIntentsFromManaged
-                    .add(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:123")));
+            notForwardedIntentsFromManaged.addAll(Arrays.asList(
+                    new Intent(Intent.ACTION_DIAL).setData(Uri.parse("tel:123")),
+                    new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:123"))));
         }
 
         if (pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java
index 6fb08ff..b671f5f 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java
@@ -43,7 +43,7 @@
     }
 
     /** Make the target device think it's off charger. */
-    public static void runDumpsysBatteryUnplug() throws Exception {
+    public static void runDumpsysBatteryUnplug() {
         SystemUtil.runShellCommandForNoOutput("cmd battery unplug");
 
         Log.d(TAG, "Battery UNPLUGGED");
@@ -68,7 +68,7 @@
     }
 
     /** Reset the effect of all the previous {@code runDumpsysBattery*} call  */
-    public static void runDumpsysBatteryReset() throws Exception {
+    public static void runDumpsysBatteryReset() {
         SystemUtil.runShellCommandForNoOutput(("cmd battery reset"));
 
         Log.d(TAG, "Battery RESET");
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BatteryUtils.java b/common/device-side/util/src/com/android/compatibility/common/util/BatteryUtils.java
index fb979c0..272bc67 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/BatteryUtils.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BatteryUtils.java
@@ -42,7 +42,7 @@
     }
 
     /** Make the target device think it's off charger. */
-    public static void runDumpsysBatteryUnplug() throws Exception {
+    public static void runDumpsysBatteryUnplug() {
         SystemUtil.runShellCommandForNoOutput("cmd battery unplug");
 
         Log.d(TAG, "Battery UNPLUGGED");
@@ -67,7 +67,7 @@
     }
 
     /** Reset the effect of all the previous {@code runDumpsysBattery*} call  */
-    public static void runDumpsysBatteryReset() throws Exception {
+    public static void runDumpsysBatteryReset() {
         SystemUtil.runShellCommandForNoOutput(("cmd battery reset"));
 
         Log.d(TAG, "Battery RESET");
diff --git a/hostsidetests/compilation/app/Android.mk b/hostsidetests/compilation/app/Android.mk
index d9d79d6..4a51a21 100644
--- a/hostsidetests/compilation/app/Android.mk
+++ b/hostsidetests/compilation/app/Android.mk
@@ -21,7 +21,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := 29
 
 LOCAL_PACKAGE_NAME := CtsCompilationApp
 
diff --git a/hostsidetests/compilation/assets/CtsCompilationApp.apk b/hostsidetests/compilation/assets/CtsCompilationApp.apk
index 18c76d3..ba89b24 100644
--- a/hostsidetests/compilation/assets/CtsCompilationApp.apk
+++ b/hostsidetests/compilation/assets/CtsCompilationApp.apk
Binary files differ
diff --git a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java
index 6b8faa9..38fbf56 100644
--- a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java
+++ b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java
@@ -231,20 +231,21 @@
             }
         };
 
-        new AsyncTask<Void, Void, Void>() {
-            @Override
-            protected Void doInBackground(Void... params) {
-                Looper.prepare();
-                locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 990, 0,
-                        locListener);
-                sleep(1_000);
-                locManager.removeUpdates(locListener);
-                latch.countDown();
-                return null;
-            }
-        }.execute();
+        HandlerThread handlerThread = new HandlerThread("doGpsUpdate_bg");
+        handlerThread.start();
+
+        Handler handler = new Handler(handlerThread.getLooper());
+        handler.post(() -> {
+                    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 990, 0,
+                            locListener);
+                    sleep(1_000);
+                    locManager.removeUpdates(locListener);
+                    latch.countDown();
+                });
 
         waitForReceiver(ctx, 59_000, latch, null);
+        handlerThread.quitSafely();
+
         tellHostActionFinished(ACTION_GPS, requestCode);
     }
 
diff --git a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
index 1041638..38b7ccc 100644
--- a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
@@ -20,6 +20,8 @@
 import android.service.GraphicsStatsProto;
 import android.service.GraphicsStatsServiceDumpProto;
 
+import com.android.tradefed.log.LogUtil.CLog;
+
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
@@ -55,6 +57,7 @@
     }
 
     public void testBasicDrawFrame() throws Exception {
+        System.out.println("--------------------------------- testBasicDrawFrame BEGIN");
         GraphicsStatsProto[] results = runDrawTest("testDrawTenFrames");
         GraphicsStatsProto statsBefore = results[0];
         GraphicsStatsProto statsAfter = results[1];
@@ -62,6 +65,11 @@
         GraphicsStatsJankSummaryProto summaryAfter = statsAfter.getSummary();
         assertTrue(summaryAfter.getTotalFrames() > summaryBefore.getTotalFrames());
 
+        System.out.println("summaryBefore: {\n" + summaryBefore + "}");
+        System.out.println("summaryAfter: {\n" + summaryAfter + "}");
+        System.out.println("statsBefore: {\n" + statsBefore + "}");
+        System.out.println("statsAfter: {\n" + statsAfter + "}");
+
         int frameDelta = summaryAfter.getTotalFrames() - summaryBefore.getTotalFrames();
         int jankyDelta = summaryAfter.getJankyFrames() - summaryBefore.getJankyFrames();
         // We expect 11 frames to have been drawn (first frame + the 10 more explicitly requested)
@@ -70,6 +78,7 @@
         int veryJankyDelta = countFramesAbove(statsAfter, 40) - countFramesAbove(statsBefore, 40);
         // The 1st frame could be >40ms, but nothing after that should be
         assertTrue(veryJankyDelta <= 1);
+        System.out.println("--------------------------------- testBasicDrawFrame END");
     }
 
     public void testJankyDrawFrame() throws Exception {
diff --git a/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
index 3463211..67dbdfa 100644
--- a/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
@@ -1183,7 +1183,7 @@
     /* Zygote is always running */
     @CddTest(requirement="9.7")
     public void testZygoteDomain() throws DeviceNotAvailableException {
-        assertDomainN("u:r:zygote:s0", "zygote", "zygote64");
+        assertDomainN("u:r:zygote:s0", "zygote", "zygote64", "usap32", "usap64");
     }
 
     /* Checks drmserver for devices that require it */
diff --git a/hostsidetests/statsd/Android.mk b/hostsidetests/statsd/Android.mk
index af7cb20..f1937de 100644
--- a/hostsidetests/statsd/Android.mk
+++ b/hostsidetests/statsd/Android.mk
@@ -24,7 +24,8 @@
 
 LOCAL_MODULE := CtsStatsdHostTestCases
 
-LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util host-libprotobuf-java-full platformprotos
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util host-libprotobuf-java-full \
+	platformprotos truth-host-prebuilt
 
 LOCAL_COMPATIBILITY_SUPPORT_FILES := \
 	$(foreach file, $(call find-subdir-files, *.pbtxt), $(LOCAL_PATH)/$(file))
diff --git a/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml b/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
index 225e12b..6398bd9 100644
--- a/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
+++ b/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
@@ -61,14 +61,16 @@
             android:label="Lmk Test Activity"
             android:launchMode="singleInstance"
             android:process=":LmkProcess"
+            android:exported="true"
             />
         <activity android:name=".DaveyActivity" android:exported="true" />
         <activity android:name=".HiddenApiUsedActivity" android:exported="true" />
         <activity
-          android:name=".ANRActivity"
-          android:label="ANR Test Activity"
-          android:launchMode="singleInstance"
-          android:process=":ANRProcess"
+            android:name=".ANRActivity"
+            android:label="ANR Test Activity"
+            android:launchMode="singleInstance"
+            android:process=":ANRProcess"
+            android:exported="true"
           />
 
         <service android:name=".StatsdAuthenticator"
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
index 2e65cba..d09175e 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
@@ -269,5 +269,22 @@
         rebootDevice();
         // Wait for 2 mins.
         assertTrue("Device failed to boot", getDevice().waitForBootComplete(120_000));
+        assertTrue("Stats service failed to start", waitForStatsServiceStart(60_000));
+        Thread.sleep(2_000);
+    }
+
+    protected boolean waitForStatsServiceStart(final long waitTime) throws Exception {
+        LogUtil.CLog.i("Waiting %d ms for stats service to start", waitTime);
+        int counter = 1;
+        long startTime = System.currentTimeMillis();
+        while ((System.currentTimeMillis() - startTime) < waitTime) {
+            if ("running".equals(getProperty("init.svc.statsd"))) {
+                return true;
+            }
+            Thread.sleep(Math.min(200 * counter, 2_000));
+            counter++;
+        }
+        LogUtil.CLog.w("Stats service did not start after %d ms", waitTime);
+        return false;
     }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
index d3c546f..f5a6343 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
@@ -15,6 +15,8 @@
  */
 package android.cts.statsd.atom;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import android.os.BatteryPluggedStateEnum;
 import android.os.BatteryStatusEnum;
 import android.platform.test.annotations.RestrictedBuildTest;
@@ -634,11 +636,11 @@
         turnOnAirplaneMode();
         turnOffAirplaneMode();
         // wait for long enough for device to restore connection
-        Thread.sleep(10_000);
+        Thread.sleep(13_000);
 
         List<EventMetricData> data = getEventMetricDataList();
         // at least 1 disconnect and 1 connect
-        assertTrue(data.size() >= 2);
+        assertThat(data.size()).isAtLeast(2);
         boolean foundDisconnectEvent = false;
         boolean foundConnectEvent = false;
         for (EventMetricData d : data) {
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index d873948..8f9f08d 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -86,7 +86,7 @@
     }
 
     public void testLmkKillOccurred() throws Exception {
-        if (statsdDisabled()) {
+        if (statsdDisabled() || !"true".equals(getProperty("ro.lmk.log_stats"))) {
             return;
         }
 
@@ -98,7 +98,7 @@
 
         Thread.sleep(WAIT_TIME_SHORT);
 
-        runActivity("LmkActivity", null, null, 12_000);
+        runActivity("LmkActivity", null, null, 5_000);
 
         // Sorted list of events in order in which they occurred.
         List<EventMetricData> data = getEventMetricDataList();
@@ -1320,7 +1320,7 @@
             Thread.sleep(WAIT_TIME_SHORT);
             getDevice().executeShellCommand(
                     "am broadcast -a action_anr -p " + DEVICE_SIDE_TEST_PACKAGE);
-            Thread.sleep(30_000);
+            Thread.sleep(11_000);
         }
 
         // Sorted list of events in order in which they occurred.
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
index 15b7ba3..bd94615 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
@@ -46,29 +46,29 @@
     private final int metric3MatcherId = 3;
 
     private final int act1MatcherId = 10;
-    private final int act1TtlSecs = 20;
+    private final int act1TtlSecs = 40;
     private final int act1CancelMatcherId = -10;
 
     private final int act2MatcherId = 20;
-    private final int act2TtlSecs = 40;
+    private final int act2TtlSecs = 60;
     private final int act2CancelMatcherId = -20;
 
 
     /**
      * Metric 1:
      *     Activation 1:
-     *         - Ttl: 20 seconds
+     *         - Ttl: 40 seconds
      *         - Type: IMMEDIATE
      *     Activation 2:
-     *         - Ttl: 40 seconds
+     *         - Ttl: 60 seconds
      *         - Type: ON_BOOT
      *
      * Metric 2:
      *     Activation 1:
-     *         - Ttl: 20 seconds
+     *         - Ttl: 40 seconds
      *         - Type: ON_BOOT
      *     Activation 2:
-     *         - Ttl: 40 seconds
+     *         - Ttl: 60 seconds
      *         - Type: IMMEDIATE
      *
      * Metric 3: No activations; always active
@@ -242,7 +242,7 @@
 
         // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 30 seconds
         // Metric 1 Activation 2: 0 seconds
         // Metric 2 Activation 1: 0 seconds (will activate after boot)
         // Metric 2 Activation 2: 0 seconds
@@ -255,9 +255,9 @@
         logAllMetrics();
 
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 30 seconds
         // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 20 seconds
+        // Metric 2 Activation 1: 30 seconds
         // Metric 2 Activation 2: 0 seconds
         rebootDeviceAndWaitUntilReady();
 
@@ -271,7 +271,7 @@
         // Metric 1 Activation 2: 0 seconds
         // Metric 2 Activation 1: 0 seconds
         // Metric 2 Activation 2: 0 seconds
-        Thread.sleep(20_000L);
+        Thread.sleep(30_000L);
 
         // Metric 1 event ignored, Activation 1 expired.
         // Metric 2 event ignored, Activation 1 expired.
@@ -283,7 +283,7 @@
         // Metric 1 Activation 1: 0 seconds
         // Metric 1 Activation 2: 0 seconds (will activate after boot)
         // Metric 2 Activation 1: 0 seconds
-        // Metric 2 Activation 2: 40 seconds
+        // Metric 2 Activation 2: 50 seconds
         doAppBreadcrumbReported(act2MatcherId);
         Thread.sleep(10L);
 
@@ -294,10 +294,10 @@
 
         // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 30 seconds
         // Metric 1 Activation 2: 0 seconds (will activate after boot)
         // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 40 seconds
+        // Metric 2 Activation 2: 50 seconds
         doAppBreadcrumbReported(act1MatcherId);
         Thread.sleep(10L);
 
@@ -307,17 +307,17 @@
         logAllMetrics();
 
         // Time remaining:
-        // Metric 1 Activation 1: 10 seconds
+        // Metric 1 Activation 1: 20 seconds
         // Metric 1 Activation 2: 0 seconds (will activate after boot)
         // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 30 seconds
+        // Metric 2 Activation 2: 40 seconds
         Thread.sleep(10_000L);
 
         // Time remaining:
-        // Metric 1 Activation 1: 10 seconds
-        // Metric 1 Activation 2: 40 seconds
-        // Metric 2 Activation 1: 20 seconds
-        // Metric 2 Activation 2: 30 seconds
+        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 2: 50 seconds
+        // Metric 2 Activation 1: 30 seconds
+        // Metric 2 Activation 2: 40 seconds
         rebootDeviceAndWaitUntilReady();
 
         // Fourth logged event for Metric 1.
@@ -331,7 +331,7 @@
         // Metric 1 Activation 2: 30 seconds
         // Metric 2 Activation 1: 10 seconds
         // Metric 2 Activation 2: 20 seconds
-        Thread.sleep(10_000L);
+        Thread.sleep(20_000L);
 
         // Fifth logged event for Metric 1.
         // Fifth logged event for Metric 2.
@@ -374,7 +374,7 @@
 
         // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 40 seconds
         // Metric 1 Activation 2: 0 seconds
         // Metric 2 Activation 1: 0 seconds (will activate after boot)
         // Metric 2 Activation 2: 0 seconds
@@ -387,7 +387,7 @@
         logAllMetrics();
 
         // Time remaining:
-        // Metric 1 Activation 1: 10 seconds
+        // Metric 1 Activation 1: 30 seconds
         // Metric 1 Activation 2: 0 seconds
         // Metric 2 Activation 1: 0 seconds (will activate after boot)
         // Metric 2 Activation 2: 0 seconds
@@ -400,7 +400,7 @@
 
         // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 30 seconds
         // Metric 1 Activation 2: 0 seconds
         // Metric 2 Activation 1: 0 seconds (will activate after boot)
         // Metric 2 Activation 2: 0 seconds
@@ -413,9 +413,9 @@
         logAllMetrics();
 
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 40 seconds
         // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 20 seconds
+        // Metric 2 Activation 1: 40 seconds
         // Metric 2 Activation 2: 0 seconds
         rebootDeviceAndWaitUntilReady();
 
@@ -426,9 +426,9 @@
 
         // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
         // Time remaining:
-        // Metric 1 Activation 1: 20 seconds
+        // Metric 1 Activation 1: 40 seconds
         // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 20 seconds
+        // Metric 2 Activation 1: 40 seconds
         // Metric 2 Activation 2: 0 seconds
         doAppBreadcrumbReported(act1MatcherId);
         Thread.sleep(10L);
@@ -444,7 +444,7 @@
         // Metric 1 Activation 2: 0 seconds
         // Metric 2 Activation 1: 0 seconds
         // Metric 2 Activation 2: 0 seconds
-        Thread.sleep(20_000);
+        Thread.sleep(40_000);
 
         // Metric 1 event ignored.
         // Metric 2 event ignored.
@@ -518,7 +518,11 @@
             int dataCount) {
         LogUtil.CLog.d("Got the following event metric data: " + metricReport.toString());
         assertEquals(metricId, metricReport.getMetricId());
-        assertEquals("Metric id = " + metricId, dataCount > 0, metricReport.hasEventMetrics());
+        if (dataCount > 0) {
+            assertTrue(metricReport.hasEventMetrics());
+        } else {
+            assertFalse(metricReport.hasEventMetrics());
+        }
         StatsLogReport.EventMetricDataWrapper eventData = metricReport.getEventMetrics();
         assertEquals(dataCount, eventData.getDataCount());
         for (int i = 0; i < eventData.getDataCount(); i++) {
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
index 830e079..7b95933 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
@@ -66,7 +66,7 @@
         turnOnAirplaneMode();
         turnOffAirplaneMode();
         // wait for long enough for device to restore connection
-        Thread.sleep(10_000);
+        Thread.sleep(13_000);
 
         BatteryStatsProto batterystatsProto = getBatteryStatsProto();
         List<CountMetricData> countMetricData = getCountMetricDataList();
diff --git a/tests/AlarmManager/src/android/alarmmanager/cts/TimeChangeTests.java b/tests/AlarmManager/src/android/alarmmanager/cts/TimeChangeTests.java
new file mode 100644
index 0000000..ed35dbe
--- /dev/null
+++ b/tests/AlarmManager/src/android/alarmmanager/cts/TimeChangeTests.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.alarmmanager.cts;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.SystemClock;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.compatibility.common.util.BatteryUtils;
+import com.android.compatibility.common.util.SystemUtil;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Tests that system time changes are handled appropriately for alarms
+ */
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+public class TimeChangeTests {
+    private static final String TAG = TimeChangeTests.class.getSimpleName();
+    private static final String ACTION_ALARM = "android.alarmmanager.cts.ACTION_ALARM";
+    private static final long DEFAULT_WAIT_MILLIS = 1_000;
+    private static final long MILLIS_IN_MINUTE = 60_000;
+
+    private final Context mContext = InstrumentationRegistry.getTargetContext();
+    private final AlarmManager mAlarmManager = mContext.getSystemService(AlarmManager.class);
+    private PendingIntent mAlarmPi;
+    private long mTestStartRtc;
+    private long mTestStartElapsed;
+    private boolean mTimeChanged;
+
+    final CountDownLatch mAlarmLatch = new CountDownLatch(1);
+
+    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            switch (intent.getAction()) {
+                case ACTION_ALARM:
+                    if (mAlarmLatch != null) {
+                        mAlarmLatch.countDown();
+                    }
+                    break;
+                default:
+                    Log.e(TAG, "Received unexpected action " + intent.getAction());
+            }
+        }
+    };
+
+    private void setTime(long rtcToSet) {
+        Log.i(TAG, "Changing system time to " + rtcToSet);
+        SystemUtil.runWithShellPermissionIdentity(() -> mAlarmManager.setTime(rtcToSet));
+        mTimeChanged = true;
+    }
+
+    @Before
+    public void setUp() {
+        final Intent alarmIntent = new Intent(ACTION_ALARM)
+                .setPackage(mContext.getPackageName())
+                .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+        mAlarmPi = PendingIntent.getBroadcast(mContext, 0, alarmIntent, 0);
+        final IntentFilter alarmFilter = new IntentFilter(ACTION_ALARM);
+        mContext.registerReceiver(mAlarmReceiver, alarmFilter);
+        SystemUtil.runShellCommand("settings put global alarm_manager_constants min_futurity=500");
+        BatteryUtils.runDumpsysBatteryUnplug();
+        mTestStartRtc = System.currentTimeMillis();
+        mTestStartElapsed = SystemClock.elapsedRealtime();
+    }
+
+    @Test
+    public void elapsedAlarmsUnaffected() throws Exception {
+        final long delayElapsed = 5_000;
+        final long expectedTriggerElapsed = mTestStartElapsed + delayElapsed;
+        mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+                expectedTriggerElapsed, mAlarmPi);
+        final long newRtc = mTestStartRtc - 32 * MILLIS_IN_MINUTE; // arbitrary, shouldn't matter
+        setTime(newRtc);
+        Thread.sleep(delayElapsed);
+        assertTrue("Elapsed alarm did not fire as expected after time change",
+                mAlarmLatch.await(DEFAULT_WAIT_MILLIS, TimeUnit.MILLISECONDS));
+    }
+
+    @Test
+    public void rtcAlarmsRescheduled() throws Exception {
+        final long newRtc = mTestStartRtc + 14 * MILLIS_IN_MINUTE; // arbitrary, but in the future
+        final long delayRtc = 4_231;
+        final long expectedTriggerRtc = newRtc + delayRtc;
+        mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, expectedTriggerRtc,
+                mAlarmPi);
+        Thread.sleep(delayRtc);
+        assertFalse("Alarm fired before time was changed",
+                mAlarmLatch.await(DEFAULT_WAIT_MILLIS, TimeUnit.MILLISECONDS));
+        setTime(newRtc);
+        Thread.sleep(delayRtc);
+        assertTrue("Alarm did not fire as expected after time was changed",
+                mAlarmLatch.await(DEFAULT_WAIT_MILLIS, TimeUnit.MILLISECONDS));
+    }
+
+    @After
+    public void tearDown() {
+        SystemUtil.runShellCommand("settings delete global alarm_manager_constants");
+        BatteryUtils.runDumpsysBatteryReset();
+        if (mTimeChanged) {
+            // Make an attempt at resetting the clock to normal
+            final long testDuration = SystemClock.elapsedRealtime() - mTestStartElapsed;
+            final long expectedCorrectRtc = mTestStartRtc + testDuration;
+            setTime(expectedCorrectRtc);
+        }
+    }
+}
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java
index 8fc13be..67d147e 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/DeviceStatesTest.java
@@ -18,6 +18,7 @@
 
 import android.annotation.TargetApi;
 import android.app.job.JobInfo;
+import android.content.pm.PackageManager;
 import android.os.SystemClock;
 import android.support.test.uiautomator.UiDevice;
 
@@ -148,9 +149,21 @@
     }
 
     /**
+     * Check if dock state is supported.
+     */
+    private boolean isDockStateSupported() {
+        // Car does not support dock state.
+        return !getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_AUTOMOTIVE);
+    }
+
+    /**
      * Ensure that device can switch state on dock normally.
      */
     public void testScreenOnDeviceOnDockChangeState() throws Exception {
+        if (!isDockStateSupported()) {
+            return;
+        }
         toggleScreenOn(true /* screen on */);
         verifyActiveState();
 
@@ -168,6 +181,9 @@
      *  Ensure that ignores this dock intent during screen off.
      */
     public void testScreenOffDeviceOnDockNoChangeState() throws Exception {
+        if (!isDockStateSupported()) {
+            return;
+        }
         toggleScreenOn(false /* screen off */);
         triggerIdleMaintenance();
         verifyIdleState();
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 253d77f..559a7bf 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -1071,6 +1071,13 @@
             return;
         }
 
+        // turn on bubbles globally
+        SystemUtil.runWithShellPermissionIdentity(() ->
+                Settings.Secure.putInt(mContext.getContentResolver(),
+                        Settings.Secure.NOTIFICATION_BUBBLES, 1));
+
+        Thread.sleep(500); // wait for ranking update
+
         assertEquals(1, Settings.Secure.getInt(
                 mContext.getContentResolver(), Settings.Secure.NOTIFICATION_BUBBLES));
 
@@ -1113,7 +1120,7 @@
         } finally {
             SystemUtil.runWithShellPermissionIdentity(() ->
                     Settings.Secure.putInt(mContext.getContentResolver(),
-                            Settings.Secure.NOTIFICATION_BUBBLES, 1));
+                            Settings.Secure.NOTIFICATION_BUBBLES, 0));
         }
     }
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityCompatModeTest.java b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityCompatModeTest.java
index a851840..1ba98d4 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityCompatModeTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityCompatModeTest.java
@@ -279,7 +279,9 @@
 
         // Fill in some stuff
         mActivity.mUsername.setText("foo");
+        sReplier.addResponse(CannedFillResponse.NO_RESPONSE);
         focusToPasswordExpectNoWindowEvent();
+        sReplier.getNextFillRequest();
         mActivity.mPassword.setText("bar");
 
         // Change URL bar before views become invisible
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
index 2b3e8a2..4457f95 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
@@ -20,6 +20,10 @@
 import static org.mockito.AdditionalMatchers.not;
 import static org.mockito.AdditionalMatchers.and;
 
+import android.app.ActivityManager;
+import android.app.Instrumentation;
+import android.app.NotificationManager;
+import android.app.UiAutomation;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.hardware.camera2.CameraAccessException;
@@ -33,8 +37,10 @@
 import android.os.Build;
 import android.os.Handler;
 import android.os.HandlerThread;
+import android.os.ParcelFileDescriptor;
 import android.test.AndroidTestCase;
 import android.util.Log;
+import androidx.test.InstrumentationRegistry;
 
 import com.android.compatibility.common.util.PropertyUtil;
 import com.android.ex.camera2.blocking.BlockingStateCallback;
@@ -42,6 +48,9 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.InOrder;
 
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashSet;
@@ -693,4 +702,80 @@
                     hardwareLevel != CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY);
         }
     }
+
+    public void testCameraManagerWithDnD() throws Exception {
+        String[] cameras = mCameraManager.getCameraIdList();
+        if (cameras.length == 0) {
+            Log.i(TAG, "No cameras present, skipping test");
+            return;
+        }
+
+        ActivityManager am = getContext().getSystemService(ActivityManager.class);
+
+        // Go devices do not support all interrupt filtering functionality
+        if (am.isLowRamDevice()) {
+            return;
+        }
+
+        // Allow the test package to adjust notification policy
+        toggleNotificationPolicyAccess(getContext().getPackageName(),
+                InstrumentationRegistry.getInstrumentation(), true);
+
+        // Enable DnD filtering
+
+        NotificationManager nm = getContext().getSystemService(NotificationManager.class);
+        try {
+            nm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
+
+            // Try to use the camera API
+
+            for (String cameraId : cameras) {
+                try {
+                    CameraCharacteristics c = mCameraManager.getCameraCharacteristics(cameraId);
+                    assertTrue("Unable to get camera characteristics when DnD is enabled",
+                            c != null);
+                } catch (RuntimeException e) {
+                    fail("RuntimeException thrown when attempting to access camera " +
+                            "characteristics with DnD enabled. " +
+                            "https://android-review.googlesource.com/c/platform/frameworks/base/+" +
+                            "/747089/ may be missing.");
+                }
+            }
+        } finally {
+            // Restore notifications to normal
+
+            nm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
+        }
+    }
+
+    private void toggleNotificationPolicyAccess(String packageName,
+            Instrumentation instrumentation, boolean on) throws IOException {
+
+        String command = " cmd notification " + (on ? "allow_dnd " : "disallow_dnd ") + packageName;
+
+        runCommand(command, instrumentation);
+
+        NotificationManager nm = getContext().getSystemService(NotificationManager.class);
+        assertEquals("Notification Policy Access Grant is " +
+                nm.isNotificationPolicyAccessGranted() + " not " + on, on,
+                nm.isNotificationPolicyAccessGranted());
+    }
+
+    private void runCommand(String command, Instrumentation instrumentation) throws IOException {
+        UiAutomation uiAutomation = instrumentation.getUiAutomation();
+        // Execute command
+        try (ParcelFileDescriptor fd = uiAutomation.executeShellCommand(command)) {
+            assertNotNull("Failed to execute shell command: " + command, fd);
+            // Wait for the command to finish by reading until EOF
+            try (InputStream in = new FileInputStream(fd.getFileDescriptor())) {
+                byte[] buffer = new byte[4096];
+                while (in.read(buffer) > 0) {}
+            } catch (IOException e) {
+                throw new IOException("Could not read stdout of command: " + command, e);
+            }
+        } finally {
+            uiAutomation.destroy();
+        }
+    }
+
 }
diff --git a/tests/framework/base/windowmanager/AndroidManifest.xml b/tests/framework/base/windowmanager/AndroidManifest.xml
index fd4cf03..4f8fe3d 100644
--- a/tests/framework/base/windowmanager/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/AndroidManifest.xml
@@ -279,6 +279,8 @@
         <activity android:name="android.server.wm.WindowInsetsPolicyTest$TestActivity"
                   android:turnScreenOn="true"
                   android:showWhenLocked="true"/>
+        <activity android:name="android.server.wm.WindowInsetsPolicyTest$FullscreenTestActivity"/>
+        <activity android:name="android.server.wm.WindowInsetsPolicyTest$FullscreenWmFlagsTestActivity"/>
         <activity android:name="android.server.wm.LayoutTests$TestActivity"
                   android:theme="@style/no_animation" />
         <activity android:name="android.server.wm.LocationOnScreenTests$TestActivity"
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DisplaySizeTest.java b/tests/framework/base/windowmanager/src/android/server/wm/DisplaySizeTest.java
index ac0f1b6..61b498d 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DisplaySizeTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DisplaySizeTest.java
@@ -23,10 +23,17 @@
 import static android.server.wm.displaysize.Components.SMALLEST_WIDTH_ACTIVITY;
 import static android.server.wm.displaysize.Components.SmallestWidthActivity.EXTRA_LAUNCH_ANOTHER_ACTIVITY;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import android.graphics.Point;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.VirtualDisplay;
 import android.os.Build;
+import android.os.Handler;
+import android.os.Looper;
 import android.platform.test.annotations.Presubmit;
+import android.view.Display;
 
 import org.junit.After;
 import org.junit.Test;
@@ -107,6 +114,58 @@
         }
     }
 
+    @Test
+    public void testSizeRangesAfterSettingDisplaySize() throws InterruptedException {
+        VirtualDisplay virtualDisplay = null;
+        try {
+            final int initialLength = 500;
+            final int newLength = 1000;
+            final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
+            virtualDisplay = displayManager.createVirtualDisplay("CtsDisplay", initialLength,
+                    initialLength, 160 /* densityDpi */, null /* surface */, 0 /* flags */);
+            final Display targetDisplay = virtualDisplay.getDisplay();
+            final int targetDisplayId = targetDisplay.getDisplayId();
+            final boolean[] displayChanged = { false };
+            displayManager.registerDisplayListener(new DisplayManager.DisplayListener() {
+                @Override
+                public void onDisplayAdded(int displayId) {}
+
+                @Override
+                public void onDisplayRemoved(int displayId) {}
+
+                @Override
+                public void onDisplayChanged(int displayId) {
+                    if (displayId == targetDisplayId) {
+                        synchronized (displayManager) {
+                            displayChanged[0] = true;
+                            displayManager.notify();
+                        }
+                        displayManager.unregisterDisplayListener(this);
+                    }
+                }
+            }, new Handler(Looper.getMainLooper()));
+
+            executeShellCommand(String.format("wm size %sx%s -d %s",
+                    newLength, newLength, targetDisplayId));
+            synchronized (displayManager) {
+                if (!displayChanged[0]) {
+                    displayManager.wait(1000 /* milliseconds */);
+                }
+            }
+
+            final Point expectedSize = new Point(newLength, newLength);
+            final Point smallestSize = new Point();
+            final Point largestSize = new Point();
+            targetDisplay.getCurrentSizeRange(smallestSize, largestSize);
+            assertEquals("Smallest size must be changed.", expectedSize, smallestSize);
+            assertEquals("Largest size must be changed.", expectedSize, largestSize);
+        } finally {
+            if (virtualDisplay != null) {
+                virtualDisplay.release();
+            }
+        }
+    }
+
     private static class ScreenDensitySession implements AutoCloseable {
         private static final String DENSITY_PROP_DEVICE = "ro.sf.lcd_density";
         private static final String DENSITY_PROP_EMULATOR = "qemu.sf.lcd_density";
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java
index 50c2633..f73d5a6 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsPolicyTest.java
@@ -16,20 +16,35 @@
 
 package android.server.wm;
 
+import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
+import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
+import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
+import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static android.server.wm.app.Components.LAUNCHING_ACTIVITY;
+import static android.server.wm.app.Components.TEST_ACTIVITY;
+import static android.view.Display.DEFAULT_DISPLAY;
+import static android.view.Surface.ROTATION_0;
+import static android.view.Surface.ROTATION_90;
 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
 
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assume.assumeTrue;
 
 import android.app.Activity;
+import android.content.ComponentName;
 import android.graphics.Insets;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
+import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.Window;
 import android.view.WindowInsets;
+import android.view.WindowManager;
+import android.view.WindowManager.LayoutParams;
 
 import androidx.test.rule.ActivityTestRule;
 
@@ -38,6 +53,8 @@
 import org.hamcrest.CustomTypeSafeMatcher;
 import org.hamcrest.Matcher;
 import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ErrorCollector;
@@ -45,7 +62,9 @@
 import java.util.function.Supplier;
 
 @Presubmit
-public class WindowInsetsPolicyTest {
+public class WindowInsetsPolicyTest extends ActivityManagerTestBase {
+
+    private ComponentName mTestActivityComponentName;
 
     @Rule
     public final ErrorCollector mErrorCollector = new ErrorCollector();
@@ -55,6 +74,23 @@
             new ActivityTestRule<>(TestActivity.class, false /* initialTouchMode */,
                     false /* launchActivity */);
 
+    @Rule
+    public final ActivityTestRule<FullscreenTestActivity> mFullscreenTestActivity =
+            new ActivityTestRule<>(FullscreenTestActivity.class, false /* initialTouchMode */,
+                    false /* launchActivity */);
+
+    @Rule
+    public final ActivityTestRule<FullscreenWmFlagsTestActivity> mFullscreenWmFlagsTestActivity =
+            new ActivityTestRule<>(FullscreenWmFlagsTestActivity.class,
+                    false /* initialTouchMode */, false /* launchActivity */);
+
+    @Before
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mTestActivityComponentName = new ComponentName(mContext, TestActivity.class);
+    }
+
     @Test
     public void testWindowInsets_dispatched() {
         final TestActivity activity = launchAndWait(mTestActivity);
@@ -75,6 +111,56 @@
         commonAsserts(insets);
     }
 
+    /**
+     * Tests whether an activity in split screen gets the top insets force consumed if
+     * {@link View#SYSTEM_UI_FLAG_FULLSCREEN} is set, and doesn't otherwise.
+     */
+    @Test
+    public void testForcedConsumedTopInsets() throws Exception {
+        assumeTrue("Skipping test: no split multi-window support",
+                supportsSplitScreenMultiWindow());
+
+        mAmWmState.computeState(new ComponentName[] {});
+        boolean naturalOrientationPortrait =
+                mAmWmState.getWmState().getDisplay(DEFAULT_DISPLAY)
+                        .mFullConfiguration.orientation == ORIENTATION_PORTRAIT;
+
+        try (final RotationSession rotationSession = new RotationSession()) {
+            rotationSession.set(naturalOrientationPortrait ? ROTATION_90 : ROTATION_0);
+
+            launchActivityInSplitScreenWithRecents(LAUNCHING_ACTIVITY);
+            final TestActivity activity = launchAndWait(mTestActivity);
+            mAmWmState.computeState(mTestActivityComponentName);
+
+            mAmWmState.assertContainsStack("Must contain fullscreen stack.",
+                    WINDOWING_MODE_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD);
+            mAmWmState.assertContainsStack("Must contain docked stack.",
+                    WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD);
+
+            mAmWmState.computeState(LAUNCHING_ACTIVITY, mTestActivityComponentName);
+
+            // Ensure that top insets are not consumed for LAYOUT_FULLSCREEN
+            WindowInsets insets = getOnMainSync(activity::getDispatchedInsets);
+            WindowInsets rootInsets = getOnMainSync(activity::getRootInsets);
+            assertEquals("top inset must be dispatched in split screen",
+                    rootInsets.getSystemWindowInsetTop(), insets.getSystemWindowInsetTop());
+
+            // Ensure that top insets are fully consumed for FULLSCREEN
+            final TestActivity fullscreenActivity = launchAndWait(mFullscreenTestActivity);
+            insets = getOnMainSync(fullscreenActivity::getDispatchedInsets);
+            assertEquals("top insets must be consumed if FULLSCREEN is set",
+                    0, insets.getSystemWindowInsetTop());
+
+            // Ensure that top insets are fully consumed for FULLSCREEN when setting it over wm
+            // layout params
+            final TestActivity fullscreenWmFlagsActivity =
+                    launchAndWait(mFullscreenWmFlagsTestActivity);
+            insets = getOnMainSync(fullscreenWmFlagsActivity::getDispatchedInsets);
+            assertEquals("top insets must be consumed if FULLSCREEN is set",
+                    0, insets.getSystemWindowInsetTop());
+        }
+    }
+
     private void commonAsserts(WindowInsets insets) {
         assertForAllInsets("must be non-negative", insets, insetsGreaterThanOrEqualTo(Insets.NONE));
 
@@ -178,4 +264,23 @@
         }
     }
 
+    public static class FullscreenTestActivity extends TestActivity {
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            getDecorView().setSystemUiVisibility(
+                    getDecorView().getSystemUiVisibility() | View.SYSTEM_UI_FLAG_FULLSCREEN);
+        }
+    }
+
+    public static class FullscreenWmFlagsTestActivity extends TestActivity {
+
+        @Override
+        protected void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
+        }
+    }
+
 }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsTest.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsTest.java
index 08d8b81..d0c8ebf 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsTest.java
@@ -417,6 +417,18 @@
         assertNull(insetInsets.getDisplayCutout());
     }
 
+    @Test
+    public void testConsumed_copy() {
+        final WindowInsets insets = new WindowInsets.Builder()
+                .setSystemWindowInsets(Insets.of(10, 20, 30, 40))
+                .setStableInsets(Insets.of(50, 60, 70, 80))
+                .build();
+
+        final WindowInsets consumed = insets.consumeSystemWindowInsets().consumeStableInsets();
+        final WindowInsets copy = new WindowInsets(consumed);
+        assertTrue(copy.isConsumed());
+    }
+
     private static Insets applyInset(Insets res) {
         return Insets.of(Math.max(0, res.left - INSET_LEFT),
                 Math.max(0, res.top - INSET_TOP),
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java b/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
index e0642be..6d21843 100644
--- a/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
+++ b/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
@@ -29,6 +29,8 @@
 
 import androidx.test.InstrumentationRegistry;
 
+import com.android.compatibility.common.util.TestUtils;
+
 import org.junit.Before;
 import org.junit.Test;
 
@@ -49,6 +51,8 @@
     private static final String TOKEN_0 = "SuperSecretToken";
     private static final String TOKEN_1 = "AnotherSecretToken";
 
+    private static final int ASSERT_TIMEOUT_SECONDS = 5; // 5 seconds
+
     @Before
     @Override
     public void setUp() throws Exception {
@@ -347,23 +351,26 @@
     }
 
     private void assertAppOrTokenUsed(String entity, boolean expected) throws Exception {
-        final String activeUsages =
-                mUiDevice.executeShellCommand("dumpsys usagestats apptimelimit actives");
-        final String[] actives = activeUsages.split("\n");
-        boolean found = false;
-
-        for (String active: actives) {
-            if (active.equals(entity)) {
-                found = true;
-                break;
-            }
-        }
+        final String failMessage;
         if (expected) {
-            assertTrue(entity +" not found in list of active activities and tokens\n"
-                    + activeUsages, found);
+            failMessage = entity + " not found in list of active activities and tokens";
         } else {
-            assertFalse(entity + " found in list of active activities and tokens\n"
-                    + activeUsages, found);
+            failMessage = entity + " found in list of active activities and tokens";
         }
+
+        TestUtils.waitUntil(failMessage, ASSERT_TIMEOUT_SECONDS, () -> {
+            final String activeUsages =
+                    mUiDevice.executeShellCommand("dumpsys usagestats apptimelimit actives");
+            final String[] actives = activeUsages.split("\n");
+            boolean found = false;
+
+            for (String active: actives) {
+                if (active.equals(entity)) {
+                    found = true;
+                    break;
+                }
+            }
+            return found == expected;
+        });
     }
 }
diff --git a/tests/tests/bluetooth/AndroidManifest.xml b/tests/tests/bluetooth/AndroidManifest.xml
index efdcb92..24cd01b 100644
--- a/tests/tests/bluetooth/AndroidManifest.xml
+++ b/tests/tests/bluetooth/AndroidManifest.xml
@@ -21,6 +21,7 @@
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 
diff --git a/tests/tests/location/src/android/location/cts/SettingInjectorServiceTest.java b/tests/tests/location/src/android/location/cts/SettingInjectorServiceTest.java
new file mode 100644
index 0000000..75bc142
--- /dev/null
+++ b/tests/tests/location/src/android/location/cts/SettingInjectorServiceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.location.cts;
+
+import android.content.Context;
+import android.location.SettingInjectorService;
+import android.test.InstrumentationTestCase;
+
+/**
+ * Test case for {@link SettingInjectorService}.
+ */
+public class SettingInjectorServiceTest extends InstrumentationTestCase {
+    private Context mContext;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mContext = getInstrumentation().getTargetContext();
+    }
+
+    public void testRefreshSettings() {
+        // Simply calls the method to make sure it exists.
+        SettingInjectorService.refreshSettings(mContext);
+    }
+}
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
index 25829c5..727b547 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
@@ -35,6 +35,7 @@
 import android.os.Build;
 import android.platform.test.annotations.AppModeFull;
 import android.util.Log;
+import android.util.Range;
 
 import com.android.compatibility.common.util.ApiLevelUtil;
 import com.android.compatibility.common.util.DynamicConfigDeviceSide;
@@ -788,4 +789,75 @@
            fail(failMessage + xmlOverrides.toString());
         }
     }
+
+    public void testGetSupportedFrameRates() throws IOException {
+        // Chose MediaFormat.MIMETYPE_VIDEO_H263 randomly
+        CodecCapabilities codecCap = CodecCapabilities.createFromProfileLevel(
+                MediaFormat.MIMETYPE_VIDEO_H263, H263ProfileBaseline, H263Level45);
+        Range<Integer> supportedFrameRates =
+                codecCap.getVideoCapabilities().getSupportedFrameRates();
+        Log.d(TAG, "Supported Frame Rates : " + supportedFrameRates.toString());
+        /*
+            ITU-T Rec. H.263/Annex X (03/2004) says that for H263ProfileBaseline and H263Level45,
+            the device has to support 15 fps.
+        */
+        assertTrue("Invalid framerate range", Range.create(1, 15).equals(supportedFrameRates));
+    }
+
+    public void testIsSampleRateSupported() throws IOException {
+        if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_AUDIO_AAC)) {
+            return; // skip
+        }
+        // Chose AAC Decoder/MediaFormat.MIMETYPE_AUDIO_AAC randomly
+        MediaCodec codec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_AUDIO_AAC);
+        MediaCodecInfo.AudioCapabilities audioCap = codec.getCodecInfo()
+                    .getCapabilitiesForType(MediaFormat.MIMETYPE_AUDIO_AAC).getAudioCapabilities();
+        final int[] validSampleRates = {8000, 16000, 22050, 44100};
+        for(int sampleRate : validSampleRates) {
+            Log.d(TAG, "SampleRate = " + sampleRate);
+            assertTrue("Expected True for isSampleRateSupported",
+                audioCap.isSampleRateSupported(sampleRate));
+        }
+        final int[] invalidSampleRates = {-1, 0, 1, Integer.MAX_VALUE};
+        for(int sampleRate : invalidSampleRates) {
+            Log.d(TAG, "SampleRate = " + sampleRate);
+            assertFalse("Expected False for isSampleRateSupported",
+                audioCap.isSampleRateSupported(sampleRate));
+        }
+        codec.release();
+    }
+
+    // API test coverage for MediaCodecInfo.EncoderCapabilities.getComplexityRange()
+    public void testGetComplexityRange() throws IOException {
+        boolean skipTest = true;
+        if (MediaUtils.hasEncoder(MediaFormat.MIMETYPE_AUDIO_AAC)) {
+            // Chose AAC Encoder/MediaFormat.MIMETYPE_AUDIO_AAC randomly
+            MediaCodec codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC);
+            Range<Integer> complexityRange =
+                    codec.getCodecInfo()
+                            .getCapabilitiesForType(MediaFormat.MIMETYPE_AUDIO_AAC)
+                            .getEncoderCapabilities()
+                            .getComplexityRange();
+            Log.d(TAG, "AAC ComplexityRange : " + complexityRange.toString());
+            assertTrue("AAC ComplexityRange invalid low value", complexityRange.getLower() >= 0);
+            codec.release();
+            skipTest = false;
+        }
+        if (MediaUtils.hasEncoder(MediaFormat.MIMETYPE_AUDIO_FLAC)) {
+            // Repeat test with FLAC Encoder
+            MediaCodec codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_FLAC);
+            Range<Integer> complexityRange =
+                    codec.getCodecInfo()
+                            .getCapabilitiesForType(MediaFormat.MIMETYPE_AUDIO_FLAC)
+                            .getEncoderCapabilities()
+                            .getComplexityRange();
+            Log.d(TAG, "FLAC ComplexityRange : " + complexityRange.toString());
+            assertTrue("FLAC ComplexityRange invalid low value", complexityRange.getLower() >= 0);
+            codec.release();
+            skipTest = false;
+        }
+        if (skipTest) {
+            MediaUtils.skipTest(TAG, "AAC and FLAC encoders not present");
+        }
+    }
 }
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java
index 7ac2924..1a47042 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowLandscapeTest.java
@@ -18,8 +18,8 @@
 
 import android.content.Intent;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
+import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.rule.ActivityTestRule;
 import androidx.test.runner.AndroidJUnit4;
 
@@ -144,7 +144,7 @@
     @Override
     protected PreferenceWithHeaders launchActivity(Intent intent) {
         if (intent != null) {
-            intent.setClass(InstrumentationRegistry.getTargetContext(),
+            intent.setClass(InstrumentationRegistry.getInstrumentation().getTargetContext(),
                     PreferenceWithHeadersLandscape.class);
         }
         return mActivityRule.launchActivity(intent);
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java
index bf19d7e..df0f253 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowPortraitTest.java
@@ -20,11 +20,12 @@
 
 import static org.junit.Assume.assumeFalse;
 
+import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
+import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.rule.ActivityTestRule;
 import androidx.test.runner.AndroidJUnit4;
 
@@ -40,13 +41,16 @@
 @RunWith(AndroidJUnit4.class)
 public class PreferenceActivityFlowPortraitTest extends PreferenceActivityFlowTest {
 
+    private Context mContext;
+
     @Rule
     public ActivityTestRule<PreferenceWithHeadersPortrait> mActivityRule =
             new ActivityTestRule<>(PreferenceWithHeadersPortrait.class, true, false);
 
     @Before
     public void setup() {
-        PackageManager pm = InstrumentationRegistry.getTargetContext().getPackageManager();
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        PackageManager pm = mContext.getPackageManager();
         // Ignore this test on Leanback since Leanback doesn't support portrait orientation
         assumeFalse(pm.hasSystemFeature(FEATURE_LEANBACK));
         mTestUtils = new TestUtils();
@@ -152,8 +156,7 @@
     @Override
     protected PreferenceWithHeaders launchActivity(Intent intent) {
         if (intent != null) {
-            intent.setClass(InstrumentationRegistry.getTargetContext(),
-                    PreferenceWithHeadersPortrait.class);
+            intent.setClass(mContext, PreferenceWithHeadersPortrait.class);
         }
         return mActivityRule.launchActivity(intent);
     }
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowTest.java
index 86c6c87..ef42eff 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityFlowTest.java
@@ -26,7 +26,6 @@
 
 import android.content.Intent;
 import android.graphics.Bitmap;
-import android.os.SystemClock;
 import android.util.Log;
 
 import com.android.compatibility.common.util.BitmapUtils;
@@ -52,7 +51,7 @@
     private static final String INNER_FRAGMENT_PREF_BUTTON = "Fragment preference";
     private static final String INNER_FRAGMENT_PREF_TITLE = "Inner fragment";
     private static final String LIST_PREF_TITLE = "List preference";
-    private static final String LIST_PREF_OPTION = "alpha";
+    private static final String LIST_PREF_OPTION = "Alpha Option 01";
 
     private static final int INITIAL_TITLE_RES_ID = R.string.test_title;
     private static final int EXPECTED_HEADERS_COUNT = 3;
@@ -147,7 +146,7 @@
         // Verify that the title was properly restored.
         assertEquals(title, mActivity.getTitle());
 
-        // Verify that everthing restores back to initial state again.
+        // Verify that everything restores back to initial state again.
         assertInitialState();
     }
 
@@ -371,7 +370,7 @@
 
         mTestUtils.tapOnViewWithText(LIST_PREF_TITLE);
 
-        mTestUtils.isTextShown(LIST_PREF_OPTION);
+        assertTextShown(LIST_PREF_OPTION);
 
         pressBack();
 
@@ -493,7 +492,7 @@
         }
     }
 
-    public boolean shouldRunLargeDeviceTest() {
+    private boolean shouldRunLargeDeviceTest() {
         if (mActivity.onIsMultiPane()) {
             return true;
         }
@@ -502,7 +501,7 @@
         return false;
     }
 
-    public boolean shouldRunSmallDeviceTest() {
+    private boolean shouldRunSmallDeviceTest() {
         if (!mActivity.onIsMultiPane()) {
             return true;
         }
@@ -537,10 +536,11 @@
     }
 
     private void assertHeadersHidden() {
-        // We check '&' instead of each individual separately because these headers are also part
-        // of individual preference panels breadcrumbs so it would fail for one.
-        assertFalse(mTestUtils.isTextShown(PREFS1_HEADER_TITLE)
-                && mTestUtils.isTextShown(PREFS2_HEADER_TITLE));
+        // We check that at least one is hidden instead of each individual one separately because
+        // these headers are also part of individual preference panels breadcrumbs so it would fail
+        // if we only checked for one.
+        assertTrue(mTestUtils.isTextHidden(PREFS1_HEADER_TITLE)
+                || mTestUtils.isTextHidden(PREFS2_HEADER_TITLE));
     }
 
     private void assertPanelPrefs1Shown() {
@@ -585,22 +585,17 @@
 
     private void recreate() {
         runOnUiThread(() -> mActivity.recreate());
-        SystemClock.sleep(1000);
-        waitForIdle();
-    }
-
-    private void waitForIdle() {
-        mTestUtils.device.waitForIdle();
+        mTestUtils.waitForIdle();
     }
 
     private void pressBack() {
-        mTestUtils.device.pressBack();
-        waitForIdle();
+        mTestUtils.mDevice.pressBack();
+        mTestUtils.waitForIdle();
     }
 
     private void launchActivity() {
         mActivity = launchActivity(null);
-        mTestUtils.device.waitForIdle();
+        mTestUtils.waitForIdle();
         runOnUiThread(() -> mIsMultiPane = mActivity.isMultiPane());
     }
 
@@ -619,7 +614,7 @@
         }
 
         mActivity = launchActivity(intent);
-        mTestUtils.device.waitForIdle();
+        mTestUtils.waitForIdle();
         runOnUiThread(() -> mIsMultiPane = mActivity.isMultiPane());
     }
 
diff --git a/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java b/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java
index 18ecfff..e70a34b 100644
--- a/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java
+++ b/tests/tests/preference/src/android/preference/cts/PreferenceActivityLegacyFlowTest.java
@@ -19,7 +19,6 @@
 import static org.junit.Assert.assertTrue;
 
 import android.graphics.Bitmap;
-import android.os.SystemClock;
 
 import androidx.test.filters.LargeTest;
 import androidx.test.rule.ActivityTestRule;
@@ -62,8 +61,6 @@
      */
     @Test
     public void legacyActivityTest() {
-        waitForIdle();
-
         // Prefs list should be shown.
         assertTextShown(LEGACY_SCREEN_TEXT);
     }
@@ -74,8 +71,6 @@
      */
     @Test
     public void legacyActivityRecreateTest() {
-        waitForIdle();
-
         Bitmap before = mTestUtils.takeScreenshot();
 
         recreate();
@@ -87,13 +82,12 @@
 
     private void recreate() {
         runOnUiThread(() -> mActivity.recreate());
-        SystemClock.sleep(1000);
-        waitForIdle();
+        mTestUtils.waitForIdle();
     }
 
     private void runOnUiThread(final Runnable runnable) {
         try {
-            mActivityRule.runOnUiThread(() -> runnable.run());
+            mActivityRule.runOnUiThread(runnable);
         } catch (Throwable ex) {
             throw new RuntimeException("Failure on the UI thread", ex);
         }
@@ -107,8 +101,4 @@
         assertTrue(mTestUtils.isTextShown(text));
     }
 
-    private void waitForIdle() {
-        mTestUtils.device.waitForIdle();
-    }
-
 }
diff --git a/tests/tests/preference/src/android/preference/cts/TestUtils.java b/tests/tests/preference/src/android/preference/cts/TestUtils.java
index 666f893..d15d99f 100644
--- a/tests/tests/preference/src/android/preference/cts/TestUtils.java
+++ b/tests/tests/preference/src/android/preference/cts/TestUtils.java
@@ -24,21 +24,20 @@
 import android.graphics.Bitmap;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.UiDevice;
-import android.support.test.uiautomator.UiObject;
 import android.support.test.uiautomator.UiObject2;
 import android.support.test.uiautomator.UiObjectNotFoundException;
 import android.support.test.uiautomator.UiScrollable;
 import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
 
-import androidx.test.InstrumentationRegistry;
+import androidx.test.platform.app.InstrumentationRegistry;
 
 /**
  * Collection of helper utils for testing preferences.
  */
 public class TestUtils {
 
-    public final UiDevice device;
+    public final UiDevice mDevice;
 
     private final Context mContext;
     private final Instrumentation mInstrumentation;
@@ -51,13 +50,17 @@
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mContext = mInstrumentation.getTargetContext();
         mPackageName = mContext.getPackageName();
-        device = UiDevice.getInstance(mInstrumentation);
+        mDevice = UiDevice.getInstance(mInstrumentation);
         mAutomation = mInstrumentation.getUiAutomation();
     }
 
+    void waitForIdle() {
+        mDevice.waitForIdle(1000);
+    }
+
     Bitmap takeScreenshot() {
         // Only take a screenshot once the screen is stable enough.
-        device.waitForIdle();
+        waitForIdle();
 
         Bitmap bt = mAutomation.takeScreenshot();
 
@@ -88,19 +91,11 @@
         UiObject2 object2 = getTextObject(text);
         if (object2 != null) {
             object2.click();
-            return;
+        } else {
+            scrollToAndGetTextObject(text);
+            getTextObject(text).click();
         }
-
-        // If the view is a part of a scrollable, it might be offscreen
-        try {
-            UiScrollable textScroll = new UiScrollable(new UiSelector().scrollable(true));
-
-            textScroll.scrollIntoView(new UiSelector().text(text));
-            UiObject object = new UiObject(new UiSelector().text(text));
-            object.click();
-        } catch (UiObjectNotFoundException e) {
-            throw new AssertionError("View with text '" + text + "' was not found!", e);
-        }
+        waitForIdle();
     }
 
     boolean isTextShown(String text) {
@@ -108,12 +103,7 @@
             return true;
         }
 
-        UiScrollable textScroll = new UiScrollable(new UiSelector().scrollable(true));
-        try {
-            return textScroll.scrollIntoView(new UiSelector().text(text));
-        } catch (UiObjectNotFoundException e) {
-            return false;
-        }
+        return scrollToAndGetTextObject(text);
     }
 
     boolean isTextHidden(String text) {
@@ -171,6 +161,17 @@
 
     private UiObject2 getTextObject(String text) {
         // Wait for up to 1 second to find the object. Returns null if the object cannot be found.
-        return device.wait(Until.findObject(By.text(text).pkg(mPackageName)), 1000);
+        return mDevice.wait(Until.findObject(By.text(text).pkg(mPackageName)), 1000);
+    }
+
+    private boolean scrollToAndGetTextObject(String text) {
+        UiScrollable scroller = new UiScrollable(new UiSelector().scrollable(true));
+        try {
+            // Swipe far away from the edges to avoid triggering navigation gestures
+            scroller.setSwipeDeadZonePercentage(0.25);
+            return scroller.scrollTextIntoView(text);
+        } catch (UiObjectNotFoundException e) {
+            throw new AssertionError("View with text '" + text + "' was not found!", e);
+        }
     }
 }
diff --git a/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java b/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java
index 730c6c7..11d40a0 100644
--- a/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java
@@ -73,6 +73,7 @@
     private String mEdgeToEdgeNavigationTitle;
     private String mSystemNavigationTitle;
     private String mGesturePreferenceTitle;
+    private boolean mConfiguredInSettings;
 
     private static String getSettingsString(Resources res, String strResName) {
         int resIdString = res.getIdentifier(strResName, "string", SETTINGS_PACKAGE_NAME);
@@ -117,6 +118,8 @@
         if (text != null) {
             mSystemGestureOptionsMap.put(text, false);
         }
+
+        mConfiguredInSettings = false;
     }
 
     @Rule
@@ -171,7 +174,7 @@
     }
 
 
-    private void launchToSettingsSystemGesture() {
+    private boolean launchToSettingsSystemGesture() {
         /* launch to the close to the system gesture fragment */
         Intent intent = new Intent();
         intent.setClassName("com.android.settings",
@@ -185,10 +188,18 @@
         mDevice.wait(Until.hasObject(By.pkg("com.android.settings").depth(0)),
                 5000);
         mDevice.wait(Until.hasObject(By.text(mGesturePreferenceTitle)), 5000);
+        if (mDevice.findObject(By.text(mGesturePreferenceTitle)) == null) {
+            return false;
+        }
         mDevice.findObject(By.text(mGesturePreferenceTitle)).click();
         mDevice.wait(Until.hasObject(By.text(mSystemNavigationTitle)), 5000);
+        if (mDevice.findObject(By.text(mSystemNavigationTitle)) == null) {
+            return false;
+        }
         mDevice.findObject(By.text(mSystemNavigationTitle)).click();
         mDevice.wait(Until.hasObject(By.text(mEdgeToEdgeNavigationTitle)), 5000);
+
+        return mDevice.hasObject(By.text(mEdgeToEdgeNavigationTitle));
     }
 
     private void leaveSettings() {
@@ -231,12 +242,18 @@
         mPixelsPerDp = metrics.density;
 
         // To setup the Edge to Edge environment by do the operation on Settings
-        launchToSettingsSystemGesture();
-        for (Map.Entry<String, Boolean> entry : mSystemGestureOptionsMap.entrySet()) {
-            UiObject2 uiObject2 = findSystemNavigationObject(entry.getKey(), true);
-            entry.setValue(uiObject2 != null);
+        boolean isOperatedSettingsToExpectedOption = launchToSettingsSystemGesture();
+        if (isOperatedSettingsToExpectedOption) {
+            for (Map.Entry<String, Boolean> entry : mSystemGestureOptionsMap.entrySet()) {
+                UiObject2 uiObject2 = findSystemNavigationObject(entry.getKey(), true);
+                entry.setValue(uiObject2 != null);
+            }
+            UiObject2 edgeToEdgeObj = mDevice.findObject(By.text(mEdgeToEdgeNavigationTitle));
+            if (edgeToEdgeObj != null) {
+                edgeToEdgeObj.click();
+                mConfiguredInSettings = true;
+            }
         }
-        mDevice.findObject(By.text(mEdgeToEdgeNavigationTitle)).click();
         mDevice.waitForIdle();
         leaveSettings();
 
@@ -262,16 +279,18 @@
             return;
         }
 
-        launchToSettingsSystemGesture();
-        for (Map.Entry<String, Boolean> entry : mSystemGestureOptionsMap.entrySet()) {
-            if (entry.getValue()) {
-                UiObject2 uiObject2 = findSystemNavigationObject(entry.getKey(), false);
-                if (uiObject2 != null) {
-                    uiObject2.click();
+        if (mConfiguredInSettings) {
+            launchToSettingsSystemGesture();
+            for (Map.Entry<String, Boolean> entry : mSystemGestureOptionsMap.entrySet()) {
+                if (entry.getValue()) {
+                    UiObject2 uiObject2 = findSystemNavigationObject(entry.getKey(), false);
+                    if (uiObject2 != null) {
+                        uiObject2.click();
+                    }
                 }
             }
+            leaveSettings();
         }
-        leaveSettings();
     }
 
 
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
index 7bb487e..24c39b7 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -128,25 +128,21 @@
     }
 
     /**
-     * Sanity check that both {@link PackageManager#FEATURE_TELEPHONY} and
-     * {@link NetworkCapabilities#TRANSPORT_CELLULAR} network must both be
-     * either defined or undefined; you can't cross the streams.
+     * Sanity check that the device has a cellular network and a valid default data subId
+     * when {@link PackageManager#FEATURE_TELEPHONY} support.
      */
     @Test
     public void testSanity() throws Exception {
+        if (!isSupported()) return;
+
         final boolean hasCellular = findCellularNetwork() != null;
-        if (isSupported() && !hasCellular) {
+        if (!hasCellular) {
             fail("Device claims to support " + PackageManager.FEATURE_TELEPHONY
                     + " but has no active cellular network, which is required for validation");
-        } else if (!isSupported() && hasCellular) {
-            fail("Device has active cellular network, but claims to not support "
-                    + PackageManager.FEATURE_TELEPHONY);
         }
 
-        if (isSupported()) {
-            if (mSubId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
-                fail("Device must have a valid default data subId for validation");
-            }
+        if (mSubId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+            fail("Device must have a valid default data subId for validation");
         }
     }
 
diff --git a/tests/tests/widget/AndroidManifest.xml b/tests/tests/widget/AndroidManifest.xml
index b4ca06c..321afb4 100644
--- a/tests/tests/widget/AndroidManifest.xml
+++ b/tests/tests/widget/AndroidManifest.xml
@@ -27,7 +27,8 @@
             android:maxRecents="1"
             android:multiArch="true"
             android:name="android.widget.cts.MockApplication"
-            android:supportsRtl="true">
+            android:supportsRtl="true"
+            android:theme="@android:style/Theme.Material.Light.DarkActionBar">
 
         <uses-library android:name="android.test.runner" />