Merge "CameraITS: switch to measure RGB channel noise" into lollipop-mr1-cts-dev
diff --git a/apps/CameraITS/pymodules/its/device.py b/apps/CameraITS/pymodules/its/device.py
index 035e70b..ad9786e 100644
--- a/apps/CameraITS/pymodules/its/device.py
+++ b/apps/CameraITS/pymodules/its/device.py
@@ -49,6 +49,7 @@
 
     # Seconds timeout on each socket operation.
     SOCK_TIMEOUT = 10.0
+    SEC_TO_NSEC = 1000*1000*1000.0
 
     PACKAGE = 'com.android.cts.verifier.camera.its'
     INTENT_START = 'com.android.cts.verifier.camera.its.START'
@@ -483,6 +484,18 @@
                 "dng" in formats and "raw10" in formats or \
                 "raw" in formats and "raw10" in formats:
             raise its.error.Error('Different raw formats not supported')
+
+        # Detect long exposure time and set timeout accordingly
+        longest_exp_time = 0
+        for req in cmd["captureRequests"]:
+            if "android.sensor.exposureTime" in req and \
+                    req["android.sensor.exposureTime"] > longest_exp_time:
+                longest_exp_time = req["android.sensor.exposureTime"]
+
+        extended_timeout = longest_exp_time / self.SEC_TO_NSEC + \
+                self.SOCK_TIMEOUT
+        self.sock.settimeout(extended_timeout)
+
         print "Capturing %d frame%s with %d format%s [%s]" % (
                   ncap, "s" if ncap>1 else "", nsurf, "s" if nsurf>1 else "",
                   ",".join(formats))
@@ -524,6 +537,7 @@
                 obj["metadata"] = mds[i]
                 objs.append(obj)
             rets.append(objs if ncap>1 else objs[0])
+        self.sock.settimeout(self.SOCK_TIMEOUT)
         return rets if len(rets)>1 else rets[0]
 
 def report_result(camera_id, success, summary_path=None):
diff --git a/apps/CameraITS/pymodules/its/objects.py b/apps/CameraITS/pymodules/its/objects.py
index 22540b8..e1541a1 100644
--- a/apps/CameraITS/pymodules/its/objects.py
+++ b/apps/CameraITS/pymodules/its/objects.py
@@ -195,12 +195,20 @@
     set_filter_off_or_fast_if_possible(props, req,
         "android.colorCorrection.availableAberrationModes",
         "android.colorCorrection.aberrationMode")
-    set_filter_off_or_fast_if_possible(props, req,
-        "android.hotPixel.availableHotPixelModes",
-        "android.hotPixel.mode")
-    set_filter_off_or_fast_if_possible(props, req,
-        "android.edge.availableEdgeModes",
-        "android.edge.mode")
+    if props.has_key("android.request.availableCharacteristicsKeys"):
+        hot_pixel_modes = 393217 in props["android.request.availableCharacteristicsKeys"]
+        edge_modes = 196610 in props["android.request.availableCharacteristicsKeys"]
+    if props.has_key("android.request.availableRequestKeys"):
+        hot_pixel_mode = 393216 in props["android.request.availableRequestKeys"]
+        edge_mode = 196608 in props["android.request.availableRequestKeys"]
+    if hot_pixel_modes and hot_pixel_mode:
+        set_filter_off_or_fast_if_possible(props, req,
+            "android.hotPixel.availableHotPixelModes",
+            "android.hotPixel.mode")
+    if edge_modes and edge_mode:
+        set_filter_off_or_fast_if_possible(props, req,
+            "android.edge.availableEdgeModes",
+            "android.edge.mode")
 
 def get_fastest_manual_capture_settings(props):
     """Return a capture request and format spec for the fastest capture.
diff --git a/apps/CameraITS/tests/scene0/test_metadata.py b/apps/CameraITS/tests/scene0/test_metadata.py
index b4ca4cb..375a6af 100644
--- a/apps/CameraITS/tests/scene0/test_metadata.py
+++ b/apps/CameraITS/tests/scene0/test_metadata.py
@@ -48,16 +48,19 @@
     check('props["android.info.supportedHardwareLevel"] is not None')
     check('props["android.info.supportedHardwareLevel"] in [0,1,2]')
     full = getval('props["android.info.supportedHardwareLevel"]') == 1
+    manual_sensor = its.caps.manual_sensor(props)
 
     # Test: rollingShutterSkew, and frameDuration tags must all be present,
     # and rollingShutterSkew must be greater than zero and smaller than all
     # of the possible frame durations.
-    check('md.has_key("android.sensor.frameDuration")')
-    check('md["android.sensor.frameDuration"] is not None')
+    if manual_sensor:
+        check('md.has_key("android.sensor.frameDuration")')
+        check('md["android.sensor.frameDuration"] is not None')
     check('md.has_key("android.sensor.rollingShutterSkew")')
     check('md["android.sensor.rollingShutterSkew"] is not None')
-    check('md["android.sensor.frameDuration"] > '
-          'md["android.sensor.rollingShutterSkew"] > 0')
+    if manual_sensor:
+        check('md["android.sensor.frameDuration"] > '
+              'md["android.sensor.rollingShutterSkew"] > 0')
 
     # Test: timestampSource must be a valid value.
     check('props.has_key("android.sensor.info.timestampSource")')
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index c5903d1..39a474e 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -951,17 +951,6 @@
                     android:value="android.hardware.camera.any"/>
         </activity>
 
-        <activity android:name=".camera.its.ItsTestActivity"
-                  android:label="@string/camera_its_test"
-                  android:configChanges="keyboardHidden|orientation|screenSize">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.cts.intent.category.MANUAL_TEST" />
-            </intent-filter>
-            <meta-data android:name="test_category" android:value="@string/test_category_camera" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.camera.any" />
-        </activity>
-
         <activity android:name=".usb.UsbAccessoryTestActivity"
                 android:label="@string/usb_accessory_test"
                 android:configChanges="keyboardHidden|orientation|screenSize">
@@ -1300,10 +1289,15 @@
                 <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_IMAGE" />
                 <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_VIDEO" />
                 <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_AUDIO" />
+                <action android:name="com.android.cts.verifier.managedprovisioning.TEST_NFC_BEAM" />
                 <category android:name="android.intent.category.DEFAULT"></category>
             </intent-filter>
         </activity>
 
+        <activity android:name=".managedprovisioning.NfcTestActivity">
+            <meta-data android:name="test_required_features" android:value="android.hardware.nfc" />
+        </activity>
+
         <provider
             android:name="android.support.v4.content.FileProvider"
             android:authorities="com.android.cts.verifier.managedprovisioning.fileprovider"
diff --git a/apps/CtsVerifier/res/layout/byod_nfc_test_activity.xml b/apps/CtsVerifier/res/layout/byod_nfc_test_activity.xml
new file mode 100644
index 0000000..52251b4
--- /dev/null
+++ b/apps/CtsVerifier/res/layout/byod_nfc_test_activity.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
+    android:layout_height="match_parent" >
+
+    <Button android:text="@string/provisioning_byod_send_manual_beam"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:id="@+id/manual_beam_button" />
+
+    <Button android:text="@string/provisioning_byod_send_share_intent"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:id="@+id/intent_share_button"
+        android:layout_below="@+id/manual_beam_button" />
+
+</RelativeLayout>
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 8982665..07f7654 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -89,11 +89,13 @@
     </string>
     <string name="car_dock_test">Car Dock Test</string>
     <string name="car_dock_test_desc">This test ensures that car mode opens the app associated with
-        car dock when going into car mode. Click on "Enable Car Mode" to start the test. Clicking on
-        the button will either bring up a disambiguation dialog asking which app to open or
-        immediately open the CAR_DOCK application. Select the "CTS Verifier" app if the dialog pops up,
-        which open the CAR_DOCK application. In the CAR_DOCK application, press the home button, which
-        will enable the pass button if the framework correctly tries to open the CAR_DOCk app again.</string>
+        car dock when going into car mode.\n\n
+        Click on "Enable Car Mode" to start the test. Clicking on the button will either bring up a
+        disambiguation dialog asking which app to open or immediately open the CAR_DOCK application.
+        Select the "CTS Verifier" app and then "Always" if the dialog pops up.
+        This will open the CAR_DOCK application.\n\n
+        In the CAR_DOCK application, press the home button, which will enable the pass button if the
+        framework correctly tries to open the CAR_DOCK app again.</string>
     <string name="car_mode_enable">Enable Car Mode</string>
     <string name="car_dock_activity_text">Press the Home button</string>
     <string name="da_no_policy">1. Press the \"Generate Policy\" to create a random device
@@ -1407,6 +1409,27 @@
         Then use the Back button to return to this test and mark accordingly.
     </string>
 
+    <string name="provisioning_byod_nfc_beam">Disable Nfc beam</string>
+    <string name="provisioning_byod_nfc_beam_allowed_instruction">
+        Please press the Go button to test if Nfc beam can be triggered in the work profile.\n
+        \n
+        For the first test, press \"Send manual beam\" to trigger a beam, then bump into another device to send the file. Verify that the file is successfully received.\n
+        \n
+        For the second test, press \"Send share intent\" to trigger a beam, then bump into another device to send the file. Verify that the file is successfully received.\n
+        \n
+        Then use the Back button to return to this test and mark accordingly.
+    </string>
+    <string name="provisioning_byod_nfc_beam_disallowed_instruction">
+        Please press the Go button to test if Nfc beam is disallowed by policy
+        \n
+        Verify that Nfc beam is not triggered when pressing the button.\n
+        \n
+        Then use the Back button to return to this test and mark accordingly.
+    </string>
+    <string name="provisioning_byod_send_manual_beam">Send manual beam</string>
+    <string name="provisioning_byod_send_share_intent">Send share intent</string>
+    <string name="provisioning_byod_cannot_resolve_beam_activity">Cannot find beam activity</string>
+
     <string name="provisioning_byod_no_activity">Cannot communicate with activity in the work profile.</string>
     <string name="provisioning_byod_delete_profile">Initiate deletion of work profile.</string>
     <string name="provisioning_byod_profile_deleted">Work profile deleted.</string>
@@ -1450,10 +1473,10 @@
 
     <!-- String for the bundled TV app Tests -->
 
-    <string name="tv_input_discover_test">Third-party TV input test</string>
+    <string name="tv_input_discover_test">3rd-party TV input test</string>
     <string name="tv_input_discover_test_info">
     Verify that the bundled TV app launches via Intent and calls the proper API to discover
-    third-party TV inputs.
+    3rd-party TV inputs.
     </string>
     <string name="tv_input_discover_test_go_to_setup">
     Select the \"Launch TV app\" button and set up the newly installed TV input:
@@ -1474,7 +1497,7 @@
     to the \"Dummy\" channel.
     </string>
     <string name="tv_input_discover_test_verify_global_search">
-    Verify the TV app provides query results for third-party input\'s channels and programs in
+    Verify the TV app provides query results for 3rd-party input\'s channels and programs in
     global search results.
     </string>
     <string name="tv_input_discover_test_go_to_epg">
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
index e3d0b6d..ce10535 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
@@ -1094,25 +1094,34 @@
             }
 
             // Initiate the captures.
+            long maxExpTimeNs = -1;
             for (int i = 0; i < requests.size(); i++) {
+                CaptureRequest.Builder req = requests.get(i);
                 // For DNG captures, need the LSC map to be available.
                 if (mCaptureRawIsDng) {
-                    requests.get(i).set(CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE, 1);
+                    req.set(CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE, 1);
+                }
+                Long expTimeNs = req.get(CaptureRequest.SENSOR_EXPOSURE_TIME);
+                if (expTimeNs != null && expTimeNs > maxExpTimeNs) {
+                    maxExpTimeNs = expTimeNs;
                 }
 
-                CaptureRequest.Builder req = requests.get(i);
                 for (int j = 0; j < numSurfaces; j++) {
                     req.addTarget(mCaptureReaders[j].getSurface());
                 }
                 mSession.capture(req.build(), mCaptureResultListener, mResultHandler);
             }
 
+            long timeout = TIMEOUT_CALLBACK * 1000;
+            if (maxExpTimeNs > 0) {
+                timeout += maxExpTimeNs / 1000000; // ns to ms
+            }
             // Make sure all callbacks have been hit (wait until captures are done).
             // If no timeouts are received after a timeout, then fail.
             int currentCount = mCountCallbacksRemaining.get();
             while (currentCount > 0) {
                 try {
-                    Thread.sleep(TIMEOUT_CALLBACK*1000);
+                    Thread.sleep(timeout);
                 } catch (InterruptedException e) {
                     throw new ItsException("Timeout failure", e);
                 }
@@ -1232,13 +1241,32 @@
 
                 StringBuilder logMsg = new StringBuilder();
                 logMsg.append(String.format(
-                        "Capt result: AE=%d, AF=%d, AWB=%d, sens=%d, exp=%.1fms, dur=%.1fms, ",
+                        "Capt result: AE=%d, AF=%d, AWB=%d, ",
                         result.get(CaptureResult.CONTROL_AE_STATE),
                         result.get(CaptureResult.CONTROL_AF_STATE),
-                        result.get(CaptureResult.CONTROL_AWB_STATE),
-                        result.get(CaptureResult.SENSOR_SENSITIVITY),
-                        result.get(CaptureResult.SENSOR_EXPOSURE_TIME).intValue() / 1000000.0f,
-                        result.get(CaptureResult.SENSOR_FRAME_DURATION).intValue() / 1000000.0f));
+                        result.get(CaptureResult.CONTROL_AWB_STATE)));
+                int[] capabilities = mCameraCharacteristics.get(
+                        CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
+                if (capabilities == null) {
+                    throw new ItsException("Failed to get capabilities");
+                }
+                boolean readSensorSettings = false;
+                for (int capability : capabilities) {
+                    if (capability ==
+                            CameraCharacteristics.
+                                    REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS) {
+                        readSensorSettings = true;
+                        break;
+                    }
+                }
+                if (readSensorSettings) {
+                    logMsg.append(String.format(
+                            "sens=%d, exp=%.1fms, dur=%.1fms, ",
+                            result.get(CaptureResult.SENSOR_SENSITIVITY),
+                            result.get(CaptureResult.SENSOR_EXPOSURE_TIME).intValue() / 1000000.0f,
+                            result.get(CaptureResult.SENSOR_FRAME_DURATION).intValue() /
+                                        1000000.0f));
+                }
                 if (result.get(CaptureResult.COLOR_CORRECTION_GAINS) != null) {
                     logMsg.append(String.format(
                             "gains=[%.1f, %.1f, %.1f, %.1f], ",
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
index fdf0089..af3a7d5 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -83,6 +83,7 @@
     private TestItem mCrossProfileImageCaptureSupportTest;
     private TestItem mCrossProfileVideoCaptureSupportTest;
     private TestItem mCrossProfileAudioCaptureSupportTest;
+    private TestItem mDisableNfcBeamTest;
 
     private int mCurrentTestPosition;
 
@@ -273,6 +274,35 @@
                     .show();
         }
 
+        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) {
+            mDisableNfcBeamTest = new TestItem(this, R.string.provisioning_byod_nfc_beam,
+                    R.string.provisioning_byod_nfc_beam_allowed_instruction,
+                    new Intent(ByodHelperActivity.ACTION_TEST_NFC_BEAM)) {
+                @Override
+                public void performTest(final ByodFlowTestActivity activity) {
+                    activity.showManualTestDialog(mDisableNfcBeamTest,
+                            new DefaultTestCallback(mDisableNfcBeamTest) {
+                        @Override
+                        public void onPass() {
+                            // Start a second test with beam disallowed by policy.
+                            Intent testNfcBeamIntent = new Intent(
+                                    ByodHelperActivity.ACTION_TEST_NFC_BEAM);
+                            testNfcBeamIntent.putExtra(NfcTestActivity.EXTRA_DISALLOW_BY_POLICY,
+                                    true);
+                            TestItem disableNfcBeamTest2 = new TestItem(activity,
+                                    R.string.provisioning_byod_nfc_beam,
+                                    R.string.provisioning_byod_nfc_beam_disallowed_instruction,
+                                    testNfcBeamIntent);
+                            // The result should be reflected on the original test.
+                            activity.showManualTestDialog(disableNfcBeamTest2,
+                                    new DefaultTestCallback(mDisableNfcBeamTest));
+                        }
+                    });
+                }
+            };
+            mTests.add(mDisableNfcBeamTest);
+        }
+
         /* TODO: reinstate when bug b/20131958 is fixed
         if (canResolveIntent(ByodHelperActivity.getCaptureAudioIntent())) {
             // Capture audio intent can be resolved in primary profile, so test.
@@ -303,7 +333,31 @@
         return intent.resolveActivity(getPackageManager()) != null;
     }
 
+    private class DefaultTestCallback implements TestItem.TestCallback {
+        final private TestItem mTest;
+
+        public DefaultTestCallback(TestItem test) {
+            mTest = test;
+        }
+
+        @Override
+        public void onPass() {
+            clearRemainingState(mTest);
+            setTestResult(mTest, TestResult.Passed);
+        }
+
+        @Override
+        public void onFail() {
+            clearRemainingState(mTest);
+            setTestResult(mTest, TestResult.Failed);
+        }
+    }
+
     private void showManualTestDialog(final TestItem test) {
+        showManualTestDialog(test, new DefaultTestCallback(test));
+    }
+
+    private void showManualTestDialog(final TestItem test, final TestItem.TestCallback callback) {
         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
                 .setIcon(android.R.drawable.ic_dialog_info)
                 .setTitle(R.string.provisioning_byod)
@@ -311,15 +365,13 @@
                 .setPositiveButton(R.string.pass_button_text, new AlertDialog.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
-                        clearRemainingState(test);
-                        setTestResult(test, TestResult.Passed);
+                        callback.onPass();
                     }
                 })
                 .setNegativeButton(R.string.fail_button_text, new AlertDialog.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
-                        clearRemainingState(test);
-                        setTestResult(test, TestResult.Failed);
+                        callback.onFail();
                     }
                 });
         View customView = test.getCustomView();
@@ -435,6 +487,11 @@
 
     static class TestItem {
 
+        public interface TestCallback {
+            void onPass();
+            void onFail();
+        }
+
         private String mDisplayName;
         private TestResult mPassed;
         private boolean mManualTest;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
index 52225c1..800137a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
@@ -68,6 +68,7 @@
     public static final String ACTION_CAPTURE_AND_CHECK_VIDEO = "com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_VIDEO";
     // Primage -> managed intent: request to capture and check an audio recording
     public static final String ACTION_CAPTURE_AND_CHECK_AUDIO = "com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_AUDIO";
+    public static final String ACTION_TEST_NFC_BEAM = "com.android.cts.verifier.managedprovisioning.TEST_NFC_BEAM";
 
     public static final String EXTRA_PROVISIONED = "extra_provisioned";
 
@@ -176,6 +177,12 @@
                 finish();
             }
             return;
+        } else if (action.equals(ACTION_TEST_NFC_BEAM)) {
+            Intent testNfcBeamIntent = new Intent(this, NfcTestActivity.class);
+            testNfcBeamIntent.putExtras(intent);
+            startActivity(testNfcBeamIntent);
+            finish();
+            return;
         }
         // This activity has no UI and is only used to respond to CtsVerifier in the primary side.
         finish();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
index dd3e16d..15349ab 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
@@ -52,6 +52,7 @@
             filter.addAction(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_IMAGE);
             filter.addAction(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_VIDEO);
             filter.addAction(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_AUDIO);
+            filter.addAction(ByodHelperActivity.ACTION_TEST_NFC_BEAM);
             filter.addAction(CrossProfileTestActivity.ACTION_CROSS_PROFILE);
             filter.addAction(WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION);
             filter.addAction(WorkNotificationTestActivity.ACTION_CLEAR_WORK_NOTIFICATION);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/NfcTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/NfcTestActivity.java
new file mode 100644
index 0000000..2f7619c
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/NfcTestActivity.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.managedprovisioning;
+
+import android.app.Activity;
+import android.app.admin.DevicePolicyManager;
+import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.net.Uri;
+import android.nfc.NfcAdapter;
+import android.os.Bundle;
+import android.os.UserManager;
+import android.support.v4.content.FileProvider;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Toast;
+
+import com.android.cts.verifier.R;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+
+public class NfcTestActivity extends Activity {
+    private static final String TAG = "NfcTestActivity";
+
+    /* package */ static final String EXTRA_DISALLOW_BY_POLICY = "disallowByPolicy";
+
+    private static final String NFC_BEAM_PACKAGE = "com.android.nfc";
+    private static final String NFC_BEAM_ACTIVITY = "com.android.nfc.BeamShareActivity";
+    private static final String SAMPLE_IMAGE_FILENAME = "image_to_share.jpg";
+    private static final String SAMPLE_IMAGE_CONTENT = "sample image";
+    private static final int MARGIN = 80;
+    private static final int TEXT_SIZE = 200;
+
+    private ComponentName mAdminReceiverComponent;
+    private DevicePolicyManager mDevicePolicyManager;
+    private UserManager mUserMangaer;
+    private NfcAdapter mNfcAdapter;
+    private boolean mDisallowByPolicy;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.byod_nfc_test_activity);
+
+        mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName());
+        mDevicePolicyManager = (DevicePolicyManager) getSystemService(
+                Context.DEVICE_POLICY_SERVICE);
+        mUserMangaer = (UserManager) getSystemService(Context.USER_SERVICE);
+        mDisallowByPolicy = getIntent().getBooleanExtra(EXTRA_DISALLOW_BY_POLICY, false);
+        if (mDisallowByPolicy) {
+            mDevicePolicyManager.addUserRestriction(mAdminReceiverComponent,
+                    UserManager.DISALLOW_OUTGOING_BEAM);
+        }
+
+        final Uri uri = createUriForImage(SAMPLE_IMAGE_FILENAME, SAMPLE_IMAGE_CONTENT);
+        Uri[] uris = new Uri[] { uri };
+
+        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+        mNfcAdapter.setBeamPushUris(uris, this);
+
+        findViewById(R.id.manual_beam_button).setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View view) {
+                mNfcAdapter.invokeBeam(NfcTestActivity.this);
+            }
+        });
+        findViewById(R.id.intent_share_button).setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View view) {
+                Intent shareIntent = new Intent(Intent.ACTION_SEND);
+                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
+                shareIntent.setType("image/jpg");
+                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+                // Specify the package name of NfcBeamActivity so that the tester don't need to
+                // select the activity manually.
+                shareIntent.setClassName(NFC_BEAM_PACKAGE, NFC_BEAM_ACTIVITY);
+                try {
+                    startActivity(shareIntent);
+                } catch (ActivityNotFoundException e) {
+                    Toast.makeText(NfcTestActivity.this,
+                            R.string.provisioning_byod_cannot_resolve_beam_activity,
+                            Toast.LENGTH_SHORT).show();
+                    Log.e(TAG, "Nfc beam activity not found", e);
+                }
+            }
+        });
+    }
+
+    @Override
+    public void finish() {
+        if (mUserMangaer.hasUserRestriction(UserManager.DISALLOW_OUTGOING_BEAM)) {
+            mDevicePolicyManager.clearUserRestriction(mAdminReceiverComponent,
+                    UserManager.DISALLOW_OUTGOING_BEAM);
+        }
+        super.finish();
+    }
+
+    /**
+     * Creates a Bitmap image that contains red on white text with a specified margin.
+     * @param text Text to be displayed in the image.
+     * @return A Bitmap image with the above specification.
+     */
+    private Bitmap createSampleImage(String text) {
+        Paint paint = new Paint();
+        paint.setStyle(Paint.Style.FILL);
+        paint.setTextSize(TEXT_SIZE);
+        Rect rect = new Rect();
+        paint.getTextBounds(text, 0, text.length(), rect);
+        int w = 2 * MARGIN + rect.right - rect.left;
+        int h = 2 * MARGIN + rect.bottom - rect.top;
+        Bitmap dest = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
+        Canvas canvas = new Canvas();
+        canvas.setBitmap(dest);
+        paint.setColor(Color.WHITE);
+        canvas.drawPaint(paint);
+        paint.setColor(Color.RED);
+        canvas.drawText(text, MARGIN - rect.left, MARGIN - rect.top, paint);
+        return dest;
+    }
+
+    private Uri createUriForImage(String name, String text) {
+        final File file = new File(getFilesDir() + File.separator + "images"
+                + File.separator + name);
+        file.getParentFile().mkdirs(); //if the folder doesn't exists it is created
+        try {
+            createSampleImage(text).compress(Bitmap.CompressFormat.JPEG, 100,
+                    new FileOutputStream(file));
+        } catch (FileNotFoundException e) {
+            return null;
+        }
+        return FileProvider.getUriForFile(this,
+                "com.android.cts.verifier.managedprovisioning.fileprovider", file);
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
index 3d44ecd..e076fc3 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
+++ b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
@@ -61,7 +61,7 @@
     public static final int MSG_CHECK_PACKAGE_ADDED = 1;
     public static final int MSG_CHECK_PACKAGE_REMOVED = 2;
     public static final int MSG_CHECK_PACKAGE_CHANGED = 3;
-    public static final int MSG_CHECK_NO_CALLBACK = 4;
+    public static final int MSG_CHECK_NO_PACKAGE_ADDED = 4;
 
     public static final int RESULT_PASS = 1;
     public static final int RESULT_FAIL = 2;
@@ -139,8 +139,8 @@
         assertEquals(RESULT_PASS, result);
     }
 
-    public void testNoCallbackForUser() throws Throwable {
-        int result = sendMessageToCallbacksService(MSG_CHECK_NO_CALLBACK,
+    public void testNoPackageAddedCallbackForUser() throws Throwable {
+        int result = sendMessageToCallbacksService(MSG_CHECK_NO_PACKAGE_ADDED,
                 mUser, SIMPLE_APP_PACKAGE);
         assertEquals(RESULT_PASS, result);
     }
@@ -238,8 +238,8 @@
 
         public int waitForResult() {
             try {
-                if (mSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
-                    return result;
+                if (mSemaphore.tryAcquire(120, TimeUnit.SECONDS)) {
+                     return result;
                 }
             } catch (InterruptedException e) {
             }
diff --git a/hostsidetests/devicepolicy/app/LauncherTestsSupport/src/com/android/cts/launchertests/support/LauncherCallbackTestsService.java b/hostsidetests/devicepolicy/app/LauncherTestsSupport/src/com/android/cts/launchertests/support/LauncherCallbackTestsService.java
index 8d61496..195a18b 100644
--- a/hostsidetests/devicepolicy/app/LauncherTestsSupport/src/com/android/cts/launchertests/support/LauncherCallbackTestsService.java
+++ b/hostsidetests/devicepolicy/app/LauncherTestsSupport/src/com/android/cts/launchertests/support/LauncherCallbackTestsService.java
@@ -22,6 +22,7 @@
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.HandlerThread;
 import android.os.IBinder;
 import android.os.Message;
 import android.os.Messenger;
@@ -31,6 +32,9 @@
 import android.util.Pair;
 
 import java.util.ArrayList;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
 import java.util.List;
 
 /**
@@ -49,23 +53,28 @@
     public static final int MSG_CHECK_PACKAGE_ADDED = 1;
     public static final int MSG_CHECK_PACKAGE_REMOVED = 2;
     public static final int MSG_CHECK_PACKAGE_CHANGED = 3;
-    public static final int MSG_CHECK_NO_CALLBACK = 4;
+    public static final int MSG_CHECK_NO_PACKAGE_ADDED = 4;
 
     public static final int RESULT_PASS = 1;
     public static final int RESULT_FAIL = 2;
 
     private static final String TAG = "LauncherCallbackTests";
 
-    private static List<Pair<String, UserHandle>> mPackagesAdded
-            = new ArrayList<Pair<String, UserHandle>>();
-    private static List<Pair<String, UserHandle>> mPackagesRemoved
-            = new ArrayList<Pair<String, UserHandle>>();
-    private static List<Pair<String, UserHandle>> mPackagesChanged
-            = new ArrayList<Pair<String, UserHandle>>();
-    private static Object mPackagesLock = new Object();
+    private static BlockingQueue<Pair<String, UserHandle>> mPackagesAdded
+            = new LinkedBlockingQueue();
+    private static BlockingQueue<Pair<String, UserHandle>> mPackagesRemoved
+            = new LinkedBlockingQueue();
+    private static BlockingQueue<Pair<String, UserHandle>> mPackagesChanged
+            = new LinkedBlockingQueue();
 
     private TestCallback mCallback;
+    private Object mCallbackLock = new Object();
     private final Messenger mMessenger = new Messenger(new CheckHandler());
+    private final HandlerThread mCallbackThread = new HandlerThread("callback");
+
+    public LauncherCallbackTestsService() {
+        mCallbackThread.start();
+    }
 
     class CheckHandler extends Handler {
         @Override
@@ -77,6 +86,7 @@
             try {
                 switch (msg.what) {
                     case MSG_CHECK_PACKAGE_ADDED: {
+                        Log.i(TAG, "MSG_CHECK_PACKAGE_ADDED");
                         boolean exists = eventExists(params, mPackagesAdded);
                         teardown();
                         msg.replyTo.send(Message.obtain(null, MSG_RESULT,
@@ -84,6 +94,7 @@
                         break;
                     }
                     case MSG_CHECK_PACKAGE_REMOVED: {
+                        Log.i(TAG, "MSG_CHECK_PACKAGE_REMOVED");
                         boolean exists = eventExists(params, mPackagesRemoved);
                         teardown();
                         msg.replyTo.send(Message.obtain(null, MSG_RESULT,
@@ -91,16 +102,16 @@
                         break;
                     }
                     case MSG_CHECK_PACKAGE_CHANGED: {
+                        Log.i(TAG, "MSG_CHECK_PACKAGE_CHANGED");
                         boolean exists = eventExists(params, mPackagesChanged);
                         teardown();
                         msg.replyTo.send(Message.obtain(null, MSG_RESULT,
                                         exists ? RESULT_PASS : RESULT_FAIL, 0));
                         break;
                     }
-                    case MSG_CHECK_NO_CALLBACK: {
-                        boolean exists = eventExists(params, mPackagesAdded)
-                                || eventExists(params, mPackagesRemoved)
-                                || eventExists(params, mPackagesChanged);
+                    case MSG_CHECK_NO_PACKAGE_ADDED: {
+                        Log.i(TAG, "MSG_CHECK_NO_PACKAGE_ADDED");
+                        boolean exists = eventExists(params, mPackagesAdded);
                         teardown();
                         msg.replyTo.send(Message.obtain(null, MSG_RESULT,
                                         exists ? RESULT_FAIL : RESULT_PASS, 0));
@@ -129,24 +140,26 @@
     private void setup() {
         LauncherApps launcherApps = (LauncherApps) getSystemService(
                 Context.LAUNCHER_APPS_SERVICE);
-        synchronized (mPackagesLock) {
-            mPackagesAdded.clear();
-            mPackagesRemoved.clear();
-            mPackagesChanged.clear();
+        synchronized (mCallbackLock) {
             if (mCallback != null) {
                 launcherApps.unregisterCallback(mCallback);
             }
+            mPackagesAdded.clear();
+            mPackagesRemoved.clear();
+            mPackagesChanged.clear();
             mCallback = new TestCallback();
-            launcherApps.registerCallback(mCallback);
+            launcherApps.registerCallback(mCallback, new Handler(mCallbackThread.getLooper()));
+            Log.i(TAG, "started listening for events");
         }
     }
 
     private void teardown() {
         LauncherApps launcherApps = (LauncherApps) getSystemService(
                 Context.LAUNCHER_APPS_SERVICE);
-        synchronized (mPackagesLock) {
+        synchronized (mCallbackLock) {
             if (mCallback != null) {
                 launcherApps.unregisterCallback(mCallback);
+                Log.i(TAG, "stopped listening for events");
                 mCallback = null;
             }
             mPackagesAdded.clear();
@@ -155,20 +168,23 @@
         }
     }
 
-    private boolean eventExists(Bundle params, List<Pair<String, UserHandle>> events) {
+    private boolean eventExists(Bundle params, BlockingQueue<Pair<String, UserHandle>> events) {
         UserHandle user = params.getParcelable(USER_EXTRA);
         String packageName = params.getString(PACKAGE_EXTRA);
-        synchronized (mPackagesLock) {
-            if (events != null) {
-                for (Pair<String, UserHandle> added : events) {
-                    if (added.first.equals(packageName) && added.second.equals(user)) {
-                        Log.i(TAG, "Event exists " + packageName + " for user " + user);
-                        return true;
-                    }
+        Log.i(TAG, "checking for " + packageName + " " + user);
+        try {
+            Pair<String, UserHandle> event = events.poll(60, TimeUnit.SECONDS);
+            while (event != null) {
+                if (event.first.equals(packageName) && event.second.equals(user)) {
+                    Log.i(TAG, "Event exists " + packageName + " for user " + user);
+                    return true;
                 }
+                event = events.poll(20, TimeUnit.SECONDS);
             }
-            return false;
+        } catch (InterruptedException e) {
+            Log.e(TAG, "Failed checking for event", e);
         }
+        return false;
     }
 
     @Override
@@ -178,20 +194,29 @@
 
     private class TestCallback extends LauncherApps.Callback {
         public void onPackageRemoved(String packageName, UserHandle user) {
-            synchronized (mPackagesLock) {
-                mPackagesRemoved.add(new Pair<String, UserHandle>(packageName, user));
+            Log.i(TAG, "package removed event " + packageName + " " + user);
+            try {
+                mPackagesRemoved.put(new Pair(packageName, user));
+            } catch (InterruptedException e) {
+                Log.e(TAG, "Failed saving event", e);
             }
         }
 
         public void onPackageAdded(String packageName, UserHandle user) {
-            synchronized (mPackagesLock) {
-                mPackagesAdded.add(new Pair<String, UserHandle>(packageName, user));
+            Log.i(TAG, "package added event " + packageName + " " + user);
+            try {
+                mPackagesAdded.put(new Pair(packageName, user));
+            } catch (InterruptedException e) {
+                Log.e(TAG, "Failed saving event", e);
             }
         }
 
         public void onPackageChanged(String packageName, UserHandle user) {
-            synchronized (mPackagesLock) {
-                mPackagesChanged.add(new Pair<String, UserHandle>(packageName, user));
+            Log.i(TAG, "package changed event " + packageName + " " + user);
+            try {
+                mPackagesChanged.put(new Pair(packageName, user));
+            } catch (InterruptedException e) {
+                Log.e(TAG, "Failed saving event", e);
             }
         }
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NfcTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NfcTest.java
new file mode 100644
index 0000000..c74211d
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NfcTest.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.managedprofile;
+
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+public class NfcTest extends AndroidTestCase {
+    private static final String SAMPLE_TEXT = "This is my text to send.";
+    private static final String TEXT_MIME_TYPE = "text/plain";
+    private static final String NFC_BEAM_ACTIVITY = "com.android.nfc.BeamShareActivity";
+
+    public void testNfcShareDisabled() throws Exception {
+        Intent intent = getTextShareIntent();
+        assertFalse("Nfc beam activity should not be resolved", isNfcBeamActivityResolved(intent));
+    }
+
+    public void testNfcShareEnabled() throws Exception {
+        Intent intent = getTextShareIntent();
+        assertTrue("Nfc beam activity should be resolved", isNfcBeamActivityResolved(intent));
+    }
+
+    private Intent getTextShareIntent() {
+        Intent intent = new Intent();
+        intent.setAction(Intent.ACTION_SEND);
+        intent.putExtra(Intent.EXTRA_TEXT, SAMPLE_TEXT);
+        intent.setType(TEXT_MIME_TYPE);
+        return intent;
+    }
+
+    private boolean isNfcBeamActivityResolved(Intent intent) {
+        PackageManager pm = mContext.getPackageManager();
+        for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) {
+            if (NFC_BEAM_ACTIVITY.equals(resolveInfo.activityInfo.name)) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+}
+
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java
index 0af38a4..8da189f 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java
@@ -81,7 +81,7 @@
         try {
             assertTrue(runDeviceTests(LAUNCHER_TESTS_PKG,
                     LAUNCHER_TESTS_CLASS,
-                            "testNoCallbackForUser",
+                            "testNoPackageAddedCallbackForUser",
                             0, "-e testUser " + mSecondaryUserSerialNumber));
         } finally {
             getDevice().uninstallPackage(SIMPLE_APP_PKG);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java
index 32be962..7e49f80 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsSingleUserTest.java
@@ -24,8 +24,10 @@
  * Set of tests for LauncherApps with managed profiles.
  */
 public class LauncherAppsSingleUserTest extends BaseLauncherAppsTest {
+    private static final String FEATURE_LIVE_TV = "android.software.live_tv";
 
     private boolean mHasLauncherApps;
+    private boolean mHasLiveTvFeature;
 
     @Override
     protected void setUp() throws Exception {
@@ -35,6 +37,8 @@
         if (mHasLauncherApps) {
             installTestApps();
         }
+
+        mHasLiveTvFeature = hasDeviceFeature(FEATURE_LIVE_TV);
     }
 
     @Override
@@ -96,7 +100,7 @@
     }
 
     public void testLauncherCallbackPackageChangedMainUser() throws Exception {
-        if (!mHasLauncherApps) {
+        if (!mHasLauncherApps || mHasLiveTvFeature) {
             return;
         }
         installApp(SIMPLE_APP_APK);
@@ -114,7 +118,7 @@
     }
 
     public void testLauncherNonExportedAppFails() throws Exception {
-        if (!mHasLauncherApps) {
+        if (!mHasLauncherApps || mHasLiveTvFeature) {
             return;
         }
         installApp(SIMPLE_APP_APK);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 70cd9be..f8fa222 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -39,7 +39,8 @@
 
     private static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
     private int mUserId;
-
+    private boolean mHasNfcFeature;
+    
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -47,6 +48,7 @@
         // We need multi user to be supported in order to create a profile of the user owner.
         mHasFeature = mHasFeature && hasDeviceFeature(
                 "android.software.managed_users");
+        mHasNfcFeature = hasDeviceFeature("android.hardware.nfc");
 
         if (mHasFeature) {
             mUserId = createManagedProfile();
@@ -274,6 +276,30 @@
         }
     }
 
+    public void testNfcRestriction() throws Exception {
+        if (!mHasFeature || !mHasNfcFeature) {
+            return;
+        }
+
+        assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
+                "testNfcShareEnabled", mUserId));
+        assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
+                "testNfcShareEnabled", 0));
+
+        String restriction = "no_outgoing_beam";  // UserManager.DISALLOW_OUTGOING_BEAM
+        String command = "add-restriction";
+
+        String addRestrictionCommandOutput =
+                changeUserRestrictionForUser(restriction, command, mUserId);
+        assertTrue("Command was expected to succeed " + addRestrictionCommandOutput,
+                addRestrictionCommandOutput.contains("Status: ok"));
+
+        assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
+                "testNfcShareDisabled", mUserId));
+        assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
+                "testNfcShareEnabled", 0));
+    }
+
     private void disableActivityForUser(String activityName, int userId)
             throws DeviceNotAvailableException {
         String command = "am start -W --user " + userId
diff --git a/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java b/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
index 9b4fbc1..e12135a 100644
--- a/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
+++ b/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
@@ -586,10 +586,10 @@
     }
 
     private void checkKernelWakelock(String[] parts) {
-        assertEquals(7, parts.length);
-        assertNotNull(parts[4]); // kernel wakelock
-        assertInteger(parts[5]); // totalTime
-        assertInteger(parts[6]); // count
+        assertTrue(parts.length >= 7);
+	assertNotNull(parts[4]); // Kernel wakelock
+	assertInteger(parts[parts.length-2]); // totalTime
+        assertInteger(parts[parts.length-1]); // count
     }
 
     private void checkWakeupReason(String[] parts) {
diff --git a/libs/deviceutil/src/android/cts/util/MediaUtils.java b/libs/deviceutil/src/android/cts/util/MediaUtils.java
old mode 100644
new mode 100755
index 20153c5..5908923
--- a/libs/deviceutil/src/android/cts/util/MediaUtils.java
+++ b/libs/deviceutil/src/android/cts/util/MediaUtils.java
@@ -17,6 +17,7 @@
 
 import android.content.Context;
 import android.content.res.AssetFileDescriptor;
+import android.media.MediaCodec;
 import android.media.MediaCodecInfo;
 import android.media.MediaCodecList;
 import android.media.MediaExtractor;
@@ -139,6 +140,17 @@
         return result;
     }
 
+    public static MediaCodec getDecoder(MediaFormat format) {
+        String decoder = sMCL.findDecoderForFormat(format);
+        if (decoder != null) {
+            try {
+                return MediaCodec.createByCodecName(decoder);
+            } catch (IOException e) {
+            }
+        }
+        return null;
+    }
+
     public static boolean canDecode(MediaFormat format) {
         if (sMCL.findDecoderForFormat(format) == null) {
             Log.i(TAG, "no decoder for " + format);
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
index a83f7a9..547b205 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
@@ -51,6 +51,8 @@
     private boolean mHasWifi;
     /** Whether the device running these tests supports telephony. */
     private boolean mHasTelephony;
+    /** Track whether WiFi was enabled in case we turn it off. */
+    private boolean mInitialWiFiState;
 
     private JobInfo.Builder mBuilder;
 
@@ -67,6 +69,14 @@
         mHasTelephony = packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
         mBuilder =
                 new JobInfo.Builder(CONNECTIVITY_JOB_ID, kJobServiceComponent);
+
+        mInitialWiFiState = mWifiManager.isWifiEnabled();
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        // Ensure that we leave WiFi in its previous state.
+        mWifiManager.setWifiEnabled(mInitialWiFiState);
     }
 
     // --------------------------------------------------------------------------------------------
@@ -202,6 +212,14 @@
         }
     }
 
+    /**
+     * Disconnect from WiFi in an attempt to connect to cellular data. Worth noting that this is
+     * best effort - there are no public APIs to force connecting to cell data. We disable WiFi
+     * and wait for a broadcast that we're connected to cell.
+     * We will not call into this function if the device doesn't support telephony.
+     * @see #mHasTelephony
+     * @see #checkDeviceSupportsMobileData()
+     */
     private void disconnectWifiToConnectToMobile() throws InterruptedException {
         if (mHasWifi && mWifiManager.isWifiEnabled()) {
             ConnectivityActionReceiver connectMobileReceiver =
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index d4b1a35..76b528b 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -313,13 +313,6 @@
   bug: 17675466
 },
 {
-  description: "tests will soon become mandatory",
-  names: [
-    "android.hardware.cts.SensorTest#testBatchAndFlush"
-  ],
-  bug: 18958411
-},
-{
   description: "This test failed on hw decoder that doesn't output frame with the configured format.",
   names: [
     "android.media.cts.ImageReaderDecoderTest#testHwAVCDecode360pForFlexibleYuv"
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/Camera2SurfaceViewCtsActivity.java b/tests/tests/hardware/src/android/hardware/camera2/cts/Camera2SurfaceViewCtsActivity.java
index 1881774..8a217fd 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/Camera2SurfaceViewCtsActivity.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/Camera2SurfaceViewCtsActivity.java
@@ -32,6 +32,7 @@
     private SurfaceView mSurfaceView;
     private int currentWidth = 0;
     private int currentHeight = 0;
+    private final Object sizeLock = new Object();
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -55,6 +56,12 @@
                             timeOutMs, expectWidth, expectHeight));
         }
 
+        synchronized(sizeLock) {
+            if (expectWidth == currentWidth && expectHeight == currentHeight) {
+                return true;
+            }
+        }
+
         int waitTimeMs = timeOutMs;
         boolean changeSucceeded = false;
         while (!changeSucceeded && waitTimeMs > 0) {
@@ -87,8 +94,10 @@
     @Override
     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
         Log.i(TAG, "Surface Changed to: " + width + "x" + height);
-        currentWidth = width;
-        currentHeight = height;
+        synchronized (sizeLock) {
+            currentWidth = width;
+            currentHeight = height;
+        }
         surfaceChangedDone.open();
     }
 
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 29c7362..43ac33b 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -1325,6 +1325,10 @@
                         !mStaticInfo.isCapabilitySupported(CameraCharacteristics.
                                 REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
                     // OK
+                } else if (template == CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG &&
+                        !mStaticInfo.isCapabilitySupported(CameraCharacteristics.
+                                REQUEST_AVAILABLE_CAPABILITIES_ZSL)) {
+                    // OK.
                 } else if (sLegacySkipTemplates.contains(template) &&
                         mStaticInfo.isHardwareLevelLegacy()) {
                     // OK
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraTestUtils.java
index be43d2f..a17041d 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -41,7 +41,9 @@
 import android.media.Image.Plane;
 import android.os.Handler;
 import android.util.Log;
+import android.view.Display;
 import android.view.Surface;
+import android.view.WindowManager;
 
 import com.android.ex.camera2.blocking.BlockingCameraManager;
 import com.android.ex.camera2.blocking.BlockingCameraManager.BlockingOpenException;
@@ -1058,4 +1060,22 @@
         }
         return resultRegions;
     }
+
+    public static Size getPreviewSizeBound(WindowManager windowManager, Size bound) {
+        Display display = windowManager.getDefaultDisplay();
+
+        int width = display.getWidth();
+        int height = display.getHeight();
+
+        if (height > width) {
+            height = width;
+            width = display.getHeight();
+        }
+
+        if (bound.getWidth() <= width &&
+            bound.getHeight() <= height)
+            return bound;
+        else
+            return new Size(width, height);
+    }
 }
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java
index d5bd4b5..92eef80 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java
@@ -147,7 +147,8 @@
                 changeExposure(requestBuilder, DEFAULT_EXP_TIME_NS, DEFAULT_SENSITIVITY);
 
                 Size previewSz =
-                        getMaxPreviewSize(mCamera.getId(), mCameraManager, PREVIEW_SIZE_BOUND);
+                        getMaxPreviewSize(mCamera.getId(), mCameraManager,
+                        getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
 
                 startPreview(requestBuilder, previewSz, listener);
                 waitForSettingsApplied(listener, NUM_FRAMES_WAITED_FOR_UNKNOWN_LATENCY);
@@ -202,7 +203,8 @@
                         STATISTICS_LENS_SHADING_MAP_MODE_ON);
 
                 Size previewSz =
-                        getMaxPreviewSize(mCamera.getId(), mCameraManager, PREVIEW_SIZE_BOUND);
+                        getMaxPreviewSize(mCamera.getId(), mCameraManager,
+                        getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
 
                 listener = new SimpleCaptureCallback();
                 startPreview(requestBuilder, previewSz, listener);
@@ -256,7 +258,8 @@
                 int[] modes = mStaticInfo.getAeAvailableAntiBandingModesChecked();
 
                 Size previewSz =
-                        getMaxPreviewSize(mCamera.getId(), mCameraManager, PREVIEW_SIZE_BOUND);
+                        getMaxPreviewSize(mCamera.getId(), mCameraManager,
+                        getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
 
                 for (int mode : modes) {
                     antiBandingTestByMode(previewSz, mode);
@@ -1165,7 +1168,9 @@
                 changeExposure(requestBuilder, expTimes[i], sensitivities[j]);
                 mSession.capture(requestBuilder.build(), listener, mHandler);
 
-                CaptureResult result = listener.getCaptureResult(WAIT_FOR_RESULT_TIMEOUT_MS);
+                // make sure timeout is long enough for long exposure time
+                long timeout = WAIT_FOR_RESULT_TIMEOUT_MS + expTimes[i];
+                CaptureResult result = listener.getCaptureResult(timeout);
                 long resultExpTime = getValueNotNull(result, CaptureResult.SENSOR_EXPOSURE_TIME);
                 int resultSensitivity = getValueNotNull(result, CaptureResult.SENSOR_SENSITIVITY);
                 validateExposureTime(expTimes[i], resultExpTime);
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java
index bb73629..e669007 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java
@@ -330,7 +330,9 @@
      */
     private void initializeImageReader(String cameraId, int format) throws Exception {
         mOrderedPreviewSizes = CameraTestUtils.getSupportedPreviewSizes(
-                cameraId, mCameraManager, CameraTestUtils.PREVIEW_SIZE_BOUND);
+                cameraId, mCameraManager,
+                CameraTestUtils.getPreviewSizeBound(mWindowManager,
+                    CameraTestUtils.PREVIEW_SIZE_BOUND));
         Size maxPreviewSize = mOrderedPreviewSizes.get(0);
         createImageReader(maxPreviewSize, format, NUM_MAX_IMAGES, /*listener*/null);
         updatePreviewSurface(maxPreviewSize);
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java
index 5fc6321..ff69581 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2AndroidTestCase.java
@@ -38,6 +38,7 @@
 import android.test.AndroidTestCase;
 import android.util.Log;
 import android.view.Surface;
+import android.view.WindowManager;
 
 import com.android.ex.camera2.blocking.BlockingSessionCallback;
 import com.android.ex.camera2.blocking.BlockingStateCallback;
@@ -70,11 +71,14 @@
     protected List<Size> mOrderedVideoSizes; // In descending order.
     protected List<Size> mOrderedStillSizes; // In descending order.
 
+    protected WindowManager mWindowManager;
+
     @Override
     public void setContext(Context context) {
         super.setContext(context);
         mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
         assertNotNull("Can't connect to camera manager!", mCameraManager);
+        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
     }
 
     /**
@@ -184,7 +188,8 @@
         mStaticInfo = new StaticMetadata(mCameraManager.getCameraCharacteristics(cameraId),
                 CheckLevel.ASSERT, /*collector*/null);
         mOrderedPreviewSizes = getSupportedPreviewSizes(
-                cameraId, mCameraManager, PREVIEW_SIZE_BOUND);
+                cameraId, mCameraManager,
+                getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
         mOrderedVideoSizes = getSupportedVideoSizes(cameraId, mCameraManager, PREVIEW_SIZE_BOUND);
         mOrderedStillSizes = getSupportedStillSizes(cameraId, mCameraManager, null);
 
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java
index 03e9647..5d832d6 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2MultiViewTestCase.java
@@ -43,6 +43,7 @@
 import android.util.Size;
 import android.view.Surface;
 import android.view.TextureView;
+import android.view.WindowManager;
 
 import com.android.ex.camera2.blocking.BlockingCameraManager;
 import com.android.ex.camera2.blocking.BlockingSessionCallback;
@@ -76,6 +77,8 @@
     private CameraHolder[] mCameraHolders;
     private HashMap<String, Integer> mCameraIdMap;
 
+    protected WindowManager mWindowManager;
+
     public Camera2MultiViewTestCase() {
         super(Camera2MultiViewCtsActivity.class);
     }
@@ -104,6 +107,7 @@
             mCameraHolders[i] = new CameraHolder(mCameraIds[i]);
             mCameraIdMap.put(mCameraIds[i], i);
         }
+        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
     }
 
     @Override
@@ -359,7 +363,8 @@
             mStaticInfo = new StaticMetadata(mCameraManager.getCameraCharacteristics(mCameraId),
                     CheckLevel.ASSERT, /*collector*/null);
             mOrderedPreviewSizes = getSupportedPreviewSizes(
-                    mCameraId, mCameraManager, PREVIEW_SIZE_BOUND);
+                    mCameraId, mCameraManager,
+                    getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
             assertNotNull(String.format("Failed to open camera device ID: %s", mCameraId), mCamera);
         }
 
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
index 6c8557d..f2a9aee 100755
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
@@ -29,6 +29,7 @@
 import android.util.Log;
 import android.view.Surface;
 import android.view.SurfaceHolder;
+import android.view.WindowManager;
 import android.content.Context;
 import android.graphics.ImageFormat;
 import android.hardware.camera2.CameraAccessException;
@@ -103,6 +104,7 @@
     protected List<Size> mOrderedStillSizes; // In descending order.
     protected HashMap<Size, Long> mMinPreviewFrameDurationMap;
 
+    protected WindowManager mWindowManager;
 
     public Camera2SurfaceViewTestCase() {
         super(Camera2SurfaceViewCtsActivity.class);
@@ -132,6 +134,8 @@
         mHandler = new Handler(mHandlerThread.getLooper());
         mCameraListener = new BlockingStateCallback();
         mCollector = new CameraErrorCollector();
+
+        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
     }
 
     @Override
@@ -562,7 +566,8 @@
         mCollector.setCameraId(cameraId);
         mStaticInfo = new StaticMetadata(mCameraManager.getCameraCharacteristics(cameraId),
                 CheckLevel.ASSERT, /*collector*/null);
-        mOrderedPreviewSizes = getSupportedPreviewSizes(cameraId, mCameraManager, PREVIEW_SIZE_BOUND);
+        mOrderedPreviewSizes = getSupportedPreviewSizes(cameraId, mCameraManager,
+                getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
         mOrderedVideoSizes = getSupportedVideoSizes(cameraId, mCameraManager, PREVIEW_SIZE_BOUND);
         mOrderedStillSizes = getSupportedStillSizes(cameraId, mCameraManager, null);
         // Use ImageFormat.YUV_420_888 for now. TODO: need figure out what's format for preview
@@ -615,8 +620,8 @@
                 mPreviewSize.getHeight());
         assertTrue("wait for surface change to " + mPreviewSize.toString() + " timed out", res);
         mPreviewSurface = holder.getSurface();
-        assertTrue("Preview surface is invalid", mPreviewSurface.isValid());
         assertNotNull("Preview surface is null", mPreviewSurface);
+        assertTrue("Preview surface is invalid", mPreviewSurface.isValid());
     }
 
     /**
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java
index d8f8a1d..380e47d 100755
--- a/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/CameraGLTest.java
@@ -497,7 +497,7 @@
      * TODO: This should be made stricter once SurfaceTexture timestamps are generated by the drivers.
      */
     @UiThreadTest
-    @TimeoutReq(minutes = 20)
+    @TimeoutReq(minutes = 30)
     public void testCameraToSurfaceTextureMetadata() throws Exception {
         runForAllCameras(testCameraToSurfaceTextureMetadataByCamera);
     }
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
index 58e3903..cf616b6 100644
--- a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
@@ -45,6 +45,7 @@
 import android.util.Log;
 import android.view.SurfaceHolder;
 
+import com.android.cts.util.TimeoutReq;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -1770,6 +1771,7 @@
     }
 
     @UiThreadTest
+    @TimeoutReq(minutes = 30)
     public void testPreviewPictureSizesCombination() throws Exception {
         int nCameras = Camera.getNumberOfCameras();
         for (int id = 0; id < nCameras; id++) {
diff --git a/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java b/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java
index 18796d4..68efef0 100755
--- a/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java
@@ -97,15 +97,15 @@
             } else {
                 assertMinMemoryMb(424);
             }
-        } else if (greaterThanDpi(density, DENSITY_XHIGH, screenSize,
+        } else if (greaterThanDpi(density, DENSITY_560, screenSize,
                 SCREENLAYOUT_SIZE_NORMAL, SCREENLAYOUT_SIZE_SMALL) ||
-                greaterThanDpi(density, DENSITY_TV, screenSize, SCREENLAYOUT_SIZE_LARGE) ||
-                greaterThanDpi(density, DENSITY_MEDIUM, screenSize, SCREENLAYOUT_SIZE_XLARGE)) {
+                greaterThanDpi(density, DENSITY_400, screenSize, SCREENLAYOUT_SIZE_LARGE) ||
+                greaterThanDpi(density, DENSITY_XHIGH, screenSize, SCREENLAYOUT_SIZE_XLARGE)) {
 
             if (supports64Bit) {
-                assertMinMemoryMb(832);
+                assertMinMemoryMb(1824);
             } else {
-                assertMinMemoryMb(512);
+                assertMinMemoryMb(1344);
             }
         } else if (greaterThanDpi(density, DENSITY_400, screenSize,
                 SCREENLAYOUT_SIZE_NORMAL, SCREENLAYOUT_SIZE_SMALL) ||
@@ -117,15 +117,15 @@
             } else {
                 assertMinMemoryMb(896);
             }
-        } else if (greaterThanDpi(density, DENSITY_560, screenSize,
+        } else if (greaterThanDpi(density, DENSITY_XHIGH, screenSize,
                 SCREENLAYOUT_SIZE_NORMAL, SCREENLAYOUT_SIZE_SMALL) ||
-                greaterThanDpi(density, DENSITY_400, screenSize, SCREENLAYOUT_SIZE_LARGE) ||
-                greaterThanDpi(density, DENSITY_XHIGH, screenSize, SCREENLAYOUT_SIZE_XLARGE)) {
+                greaterThanDpi(density, DENSITY_TV, screenSize, SCREENLAYOUT_SIZE_LARGE) ||
+                greaterThanDpi(density, DENSITY_MEDIUM, screenSize, SCREENLAYOUT_SIZE_XLARGE)) {
 
             if (supports64Bit) {
-                assertMinMemoryMb(1824);
+                assertMinMemoryMb(832);
             } else {
-                assertMinMemoryMb(1344);
+                assertMinMemoryMb(512);
             }
         }
     }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java
index d69bf31..d3b317b 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java
@@ -49,10 +49,8 @@
     @SuppressWarnings("deprecation")
     public static EventOrderingVerification getDefault(TestSensorEnvironment environment) {
         int reportingMode = environment.getSensor().getReportingMode();
-        if (reportingMode != Sensor.REPORTING_MODE_CONTINUOUS
-                && reportingMode != Sensor.REPORTING_MODE_ON_CHANGE) {
+        if (reportingMode == Sensor.REPORTING_MODE_ONE_SHOT)
             return null;
-        }
         return new EventOrderingVerification();
     }
 
diff --git a/tests/tests/media/src/android/media/cts/DecoderTest.java b/tests/tests/media/src/android/media/cts/DecoderTest.java
old mode 100644
new mode 100755
index 33ca414..40e619b
--- a/tests/tests/media/src/android/media/cts/DecoderTest.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTest.java
@@ -1284,6 +1284,10 @@
         }
     }
 
+    private static MediaCodec createDecoder(MediaFormat format) {
+        return MediaUtils.getDecoder(format);
+    }
+
     // for video
     private int countFrames(int video, int resetMode, int eosframe, Surface s)
             throws Exception {
@@ -1396,7 +1400,7 @@
         ByteBuffer[] codecInputBuffers;
         ByteBuffer[] codecOutputBuffers;
 
-        MediaCodec codec = createDecoder(mime);
+        MediaCodec codec = createDecoder(format);
         Log.i("@@@@", "using codec: " + codec.getName());
         codec.configure(format, surface, null /* crypto */, 0 /* flags */);
         codec.start();
diff --git a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
index 014c1a5..89d6efa 100644
--- a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
+++ b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
@@ -657,7 +657,6 @@
             } catch (InterruptedException e) {
                 // don't care
             }
-            cleanupGl();
             mCompositionThread = null;
             mSurface = null;
             mStartCompletionSemaphore = null;
@@ -967,7 +966,6 @@
 
             public void cleanup() {
                 mNumTextureUpdated.set(0);
-                mVerticesData.clear();
                 if (mTextureId != 0) {
                     int[] textures = new int[] {
                             mTextureId
diff --git a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
index 78b5cfd..216e21b 100644
--- a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
@@ -159,13 +159,29 @@
     }
 
     public void testRecorderCamera() throws Exception {
+        int width;
+        int height;
+        Camera camera = null;
         if (!hasCamera()) {
             return;
         }
+        // Try to get camera first supported resolution.
+        // If we fail for any reason, set the video size to default value.
+        try {
+            camera = Camera.open();
+            width = camera.getParameters().getSupportedPreviewSizes().get(0).width;
+            height = camera.getParameters().getSupportedPreviewSizes().get(0).height;
+        } catch (Exception e) {
+            width = VIDEO_WIDTH;
+            height = VIDEO_HEIGHT;
+        }
+        if (camera != null) {
+            camera.release();
+        }
         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
         mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
         mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
-        mMediaRecorder.setVideoSize(VIDEO_WIDTH, VIDEO_HEIGHT);
+        mMediaRecorder.setVideoSize(width, height);
         mMediaRecorder.setVideoEncodingBitRate(VIDEO_BIT_RATE_IN_BPS);
         mMediaRecorder.setPreviewDisplay(mActivity.getSurfaceHolder().getSurface());
         mMediaRecorder.prepare();
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index 15d368f..9daf3c4 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -29,6 +29,7 @@
 import android.net.wifi.WifiManager;
 import android.test.AndroidTestCase;
 import android.util.Log;
+import android.os.SystemProperties;
 
 import com.android.internal.telephony.PhoneConstants;
 
@@ -70,10 +71,14 @@
         // Get com.android.internal.R.array.networkAttributes
         int resId = getContext().getResources().getIdentifier("networkAttributes", "array", "android");
         String[] naStrings = getContext().getResources().getStringArray(resId);
-
+        //TODO: What is the "correct" way to determine if this is a wifi only device?
+        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
         for (String naString : naStrings) {
             try {
                 NetworkConfig n = new NetworkConfig(naString);
+                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
+                    continue;
+                }
                 mNetworks.put(n.type, n);
             } catch (Exception e) {}
         }
diff --git a/tests/tests/os/src/android/os/cts/StatFsTest.java b/tests/tests/os/src/android/os/cts/StatFsTest.java
index 67afde9..a0653fd 100644
--- a/tests/tests/os/src/android/os/cts/StatFsTest.java
+++ b/tests/tests/os/src/android/os/cts/StatFsTest.java
@@ -46,15 +46,15 @@
         assertTrue(stat.getBlockSize() > 0);
         assertTrue(stat.getBlockCount() > 0);
         assertTrue(stat.getFreeBlocks() >= stat.getAvailableBlocks());
-        assertTrue(stat.getAvailableBlocks() > 0);
+        assertTrue(stat.getAvailableBlocks() >= 0);
 
         assertTrue(stat.getBlockSizeLong() > 0);
         assertTrue(stat.getBlockCountLong() > 0);
         assertTrue(stat.getFreeBlocksLong() >= stat.getAvailableBlocksLong());
-        assertTrue(stat.getAvailableBlocksLong() > 0);
+        assertTrue(stat.getAvailableBlocksLong() >= 0);
 
-        assertTrue(stat.getFreeBytes() > 0);
-        assertTrue(stat.getAvailableBytes() > 0);
+        assertTrue(stat.getFreeBytes() >= 0);
+        assertTrue(stat.getAvailableBytes() >= 0);
         assertTrue(stat.getTotalBytes() > 0);
     }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java
index 0eae82b..c1b2229 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java
@@ -373,7 +373,7 @@
         values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
         Uri fileUri = mResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
         // give media provider some time to realize there's no album art
-        //SystemClock.sleep(1000);
+        SystemClock.sleep(1000);
         // get its album id
         Cursor c = mResolver.query(fileUri, new String[] { MediaStore.Audio.Media.ALBUM_ID},
                 null, null, null);
diff --git a/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp b/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp
index d9c7ce7..6807523 100644
--- a/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp
@@ -151,11 +151,12 @@
         return false;
     }
 
-    if (aps->isStreamActive((audio_stream_type_t)(AUDIO_STREAM_MIN -1), 0)) {
+    status_t status = aps->isStreamActive((audio_stream_type_t)(-1), 0);
+    if (status == NO_ERROR) {
         return false;
     }
-
-    if (aps->isStreamActive((audio_stream_type_t)AUDIO_STREAM_CNT, 0)) {
+    status = aps->isStreamActive((audio_stream_type_t)AUDIO_STREAM_CNT, 0);
+    if (status == NO_ERROR) {
         return false;
     }
     return true;
diff --git a/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp b/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp
index 5029f6a..1c45e91 100644
--- a/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp
@@ -37,6 +37,7 @@
 #include <errno.h>
 #include <inttypes.h>
 #include <linux/sysctl.h>
+#include <arpa/inet.h>
 
 #define PASSED 0
 #define UNKNOWN_ERROR -1
@@ -311,6 +312,28 @@
     return !vulnerable;
 }
 
+static jboolean android_security_cts_NativeCodeTest_doPingPongRootTest(JNIEnv*, jobject)
+{
+    int icmp_sock;
+    struct sockaddr sock_addr;
+
+    memset(&sock_addr, 0, sizeof(sock_addr));
+    icmp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
+    sock_addr.sa_family = AF_INET;
+
+    /* first connect */
+    connect(icmp_sock, &sock_addr, sizeof(sock_addr));
+
+    /* disconnect */
+    sock_addr.sa_family = AF_UNSPEC;
+    connect(icmp_sock, &sock_addr, sizeof(sock_addr));
+
+    /* second disconnect -> crash */
+    sock_addr.sa_family = AF_UNSPEC;
+    connect(icmp_sock, &sock_addr, sizeof(sock_addr));
+
+    return true;
+}
 
 static JNINativeMethod gMethods[] = {
     {  "doPerfEventTest", "()Z",
@@ -327,6 +350,8 @@
             (void *) android_security_cts_NativeCodeTest_doFutexTest },
     {  "doNvmapIocFromIdTest", "()Z",
             (void *) android_security_cts_NativeCodeTest_doNvmapIocFromIdTest },
+    {  "doPingPongRootTest", "()Z",
+            (void *) android_security_cts_NativeCodeTest_doPingPongRootTest },
 };
 
 int register_android_security_cts_NativeCodeTest(JNIEnv* env)
diff --git a/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java b/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java
index 8ebe6ac..dfefad7 100644
--- a/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java
+++ b/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java
@@ -120,6 +120,7 @@
          */
         int firstPid = -1;
         int previousPid = -1;
+        int lastPid = -1;
         for (int i = 0; i < MAX_PID; i++) {
             byte[] output = new byte[RANDOM_BYTES_PER_PID];
             int pid;
@@ -202,7 +203,9 @@
                 firstPid = pid;
             }
 
-            if (i > PRIMING_ITERATIONS) {
+            if (i <= PRIMING_ITERATIONS) {
+                lastPid = pid;
+            } else if (pid > lastPid && (lastPid > firstPid || pid < firstPid)) {
                 wastePids(firstPid, previousPid);
             }
         }
diff --git a/tests/tests/security/src/android/security/cts/NativeCodeTest.java b/tests/tests/security/src/android/security/cts/NativeCodeTest.java
index 0bb8d12..5ee8f69 100644
--- a/tests/tests/security/src/android/security/cts/NativeCodeTest.java
+++ b/tests/tests/security/src/android/security/cts/NativeCodeTest.java
@@ -64,6 +64,13 @@
                    doNvmapIocFromIdTest());
     }
 
+    public void testPingPongRoot() throws Exception {
+        assertTrue("Device is vulnerable to CVE-2015-3636, a vulnerability in the ping "
+                   + "socket implementation. Please apply the security patch at "
+                   + "https://github.com/torvalds/linux/commit/a134f083e79f",
+                   doPingPongRootTest());
+    }
+
     /**
      * Returns true iff this device is vulnerable to CVE-2013-2094.
      * A patch for CVE-2013-2094 can be found at
@@ -132,4 +139,17 @@
      * false if the device is vulnerable.
      */
     private static native boolean doCVE20141710Test();
+
+    /**
+     * CVE-2015-3636
+     *
+     * Returns true if the patch is applied, crashes the system otherwise.
+     *
+     * Detects if the following patch is present.
+     * https://github.com/torvalds/linux/commit/a134f083e79f
+     *
+     * Credit: Wen Xu and wushi of KeenTeam.
+     * http://seclists.org/oss-sec/2015/q2/333
+     */
+    private static native boolean doPingPongRootTest();
 }
diff --git a/tests/tests/security/src/android/security/cts/SELinuxDomainTest.java b/tests/tests/security/src/android/security/cts/SELinuxDomainTest.java
index 7533666..c97c8c2 100644
--- a/tests/tests/security/src/android/security/cts/SELinuxDomainTest.java
+++ b/tests/tests/security/src/android/security/cts/SELinuxDomainTest.java
@@ -265,15 +265,15 @@
     }
 
     /*
-     * Their will at least be some kernel thread running and all kthreads should
-     * be in kernel context.
+     * All kthreads should be in kernel context.
      */
     public void testKernelDomain() throws FileNotFoundException {
         String domain = "u:r:kernel:s0";
         List<ProcessDetails> procs = ProcessDetails.getProcessMap().get(domain);
-        assertNotNull(procs);
-        for (ProcessDetails p : procs) {
-            assertTrue("Non Kernel thread \"" + p + "\" found!", p.isKernel());
+        if (procs != null) {
+            for (ProcessDetails p : procs) {
+                assertTrue("Non Kernel thread \"" + p + "\" found!", p.isKernel());
+            }
         }
     }
 
diff --git a/tests/tests/security/src/android/security/cts/ServicePermissionsTest.java b/tests/tests/security/src/android/security/cts/ServicePermissionsTest.java
index 00cbfd8..bda0d6d 100644
--- a/tests/tests/security/src/android/security/cts/ServicePermissionsTest.java
+++ b/tests/tests/security/src/android/security/cts/ServicePermissionsTest.java
@@ -137,7 +137,9 @@
 
             if (lines.size() == 1) {
                 String message = lines.get(0);
-                if (!message.contains("Permission Denial") &&
+                if ("backup".equals(service) && "Inactive".equals(message)) {
+                    Log.i(TAG, "Exempt inactive backup service.");
+                } else if (!message.contains("Permission Denial") &&
                         !message.contains("android.permission.DUMP")) {
                     fail("dump() for " + service + " produced a single line which didn't "
                             + "reference a permission; it may be leaking sensitive data.");
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java
index 041fcdd..ce4a3be 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java
@@ -47,7 +47,7 @@
                 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
         mHandler = new RenderSpecHandler();
         int uiMode = getResources().getConfiguration().uiMode;
-        mOnTv = (uiMode & Configuration.UI_MODE_TYPE_TELEVISION) == Configuration.UI_MODE_TYPE_TELEVISION;
+        mOnTv = (uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION;
     }
 
     public boolean getOnTv() {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index 33a9cee..e9ff48f 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
@@ -95,7 +95,7 @@
      * brackets are optional):
      * <p/>
      * Mozilla/5.0 (Linux;[ U;] Android <version>;[ <language>-<country>;]
-     * [<devicemodel>;] Build/<buildID>) AppleWebKit/<major>.<minor> (KHTML, like Gecko)
+     * [<devicemodel>;] Build/<buildID>[; wv]) AppleWebKit/<major>.<minor> (KHTML, like Gecko)
      * Version/<major>.<minor> Chrome/<major>.<minor>.<branch>.<build>[ Mobile]
      * Safari/<major>.<minor>
      */
@@ -107,7 +107,8 @@
         Log.i(LOG_TAG, String.format("Checking user agent string %s", actualUserAgentString));
         final String patternString =
                 "Mozilla/5\\.0 \\(Linux;( U;)? Android ([^;]+);( (\\w+)-(\\w+);)?" +
-                "\\s?(.*)\\sBuild/(.+)\\) AppleWebKit/(\\d+)\\.(\\d+) \\(KHTML, like Gecko\\) " +
+                "\\s?(.*)\\sBuild/(.+?)(; wv)?\\) AppleWebKit/(\\d+)\\.(\\d+) " +
+                "\\(KHTML, like Gecko\\) " +
                 "Version/\\d+\\.\\d+ Chrome/\\d+\\.\\d+\\.\\d+\\.\\d+( Mobile)? " +
                 "Safari/(\\d+)\\.(\\d+)";
         // Groups used:
@@ -118,11 +119,12 @@
         //  5   - language
         //  6 - device model (optional)
         //  7 - build ID
-        //  8 - AppleWebKit major version number
-        //  9 - AppleWebKit minor version number
-        // 10 - " Mobile" string (optional)
-        // 11 - Safari major version number
-        // 12 - Safari minor version number
+        //  8 - WebView identifier "; wv" (optional)
+        //  9 - AppleWebKit major version number
+        // 10 - AppleWebKit minor version number
+        // 11 - " Mobile" string (optional)
+        // 12 - Safari major version number
+        // 13 - Safari minor version number
         Log.i(LOG_TAG, String.format("Trying to match pattern %s", patternString));
         final Pattern userAgentExpr = Pattern.compile(patternString);
         Matcher patternMatcher = userAgentExpr.matcher(actualUserAgentString);
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
index 62c268d..8fb61bf 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
@@ -46,6 +46,7 @@
     public static final String SCREEN_SIZE = "screen_size";
     public static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
     public static final String SCREEN_DENSITY = "screen_density";
+    public static final String SMALLEST_SCREEN_WIDTH_DP = "smallest_screen_width_dp";
     public static final String RESOLUTION = "resolution";
     public static final String VERSION_SDK = "androidPlatformVersion";
     public static final String VERSION_RELEASE = "buildVersion";
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
index 52ddfe9..5828259 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
@@ -97,6 +97,9 @@
         String screenSize = getScreenSize();
         addResult(SCREEN_SIZE, screenSize);
 
+        Configuration configuration = getContext().getResources().getConfiguration();
+        addResult(SMALLEST_SCREEN_WIDTH_DP, configuration.smallestScreenWidthDp);
+
         Intent intent = new Intent();
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.setClass(this.getContext(), DeviceInfoActivity.class);
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java
index 0c947c3..96145e9 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java
@@ -95,6 +95,8 @@
                 getMetric(metricsCopy, DeviceInfoConstants.SCREEN_DENSITY_BUCKET));
         serializer.attribute(ns, DeviceInfoConstants.SCREEN_SIZE,
                 getMetric(metricsCopy, DeviceInfoConstants.SCREEN_SIZE));
+        serializer.attribute(ns, DeviceInfoConstants.SMALLEST_SCREEN_WIDTH_DP,
+                getMetric(metricsCopy, DeviceInfoConstants.SMALLEST_SCREEN_WIDTH_DP));
         serializer.endTag(ns, SCREEN_TAG);
 
         serializer.startTag(ns, PHONE_TAG);