Merge "Add okhttp tests as a CTS package"
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index 9b089df..cd7f2d1 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -8,6 +8,10 @@
   bug: 8148617
 },
 {
+  name: "android.holo.cts.HoloHostTest",
+  bug: 15343612
+},
+{
   name: "android.nativeopengl.EGLCleanupTest#TestCorrect",
   name: "android.nativeopengl.EGLCreateContextTest#BadAttributeFails",
   bug: 11652564
diff --git a/tests/print/src/android/print/cts/PrintInstrument.java b/tests/print/src/android/print/cts/PrintInstrument.java
index b154901..1c568a1 100644
--- a/tests/print/src/android/print/cts/PrintInstrument.java
+++ b/tests/print/src/android/print/cts/PrintInstrument.java
@@ -131,7 +131,7 @@
 
         args.putIBinder(ARG_PRIVILEGED_OPS, new PrivilegedOperations(mAm));
 
-        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId)) {
+        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, null)) {
             throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
         }
 
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java
new file mode 100644
index 0000000..5a9baeb
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java
@@ -0,0 +1,203 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.camera2.cts;
+
+import android.graphics.ImageFormat;
+import android.hardware.camera2.CameraCharacteristics;
+import android.hardware.camera2.CameraDevice;
+import android.hardware.camera2.CaptureRequest;
+import android.hardware.camera2.CaptureResult;
+import android.hardware.camera2.DngCreator;
+import android.hardware.camera2.cts.helpers.StaticMetadata;
+import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
+import android.media.Image;
+import android.media.ImageReader;
+import android.util.Log;
+import android.util.Pair;
+import android.util.Size;
+import android.view.Surface;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FileOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import static android.hardware.camera2.cts.CameraTestUtils.configureCameraOutputs;
+
+/**
+ * Tests for the DngCreator API.
+ */
+public class DngCreatorTest extends Camera2AndroidTestCase {
+    private static final String TAG = "DngCreatorTest";
+    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
+    private static final String DEBUG_DNG_FILE = "/raw16.dng";
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    /**
+     * Test basic raw capture and DNG saving functionality for each of the available cameras.
+     *
+     * <p>
+     * For each camera, capture a single RAW16 image at the first capture size reported for
+     * the raw format on that device, and save that image as a DNG file.  No further validation
+     * is done.
+     * </p>
+     *
+     * <p>
+     * Note: Enabling adb shell setprop log.tag.DngCreatorTest VERBOSE will also cause the
+     * raw image captured for the first reported camera device to be saved to an output file.
+     * </p>
+     */
+    public void testSingleImageBasic() throws Exception {
+        for (int i = 0; i < mCameraIds.length; i++) {
+            String deviceId = mCameraIds[i];
+            ImageReader captureReader = null;
+            FileOutputStream fileStream = null;
+            ByteArrayOutputStream outputStream = null;
+            try {
+                openDevice(deviceId);
+
+                Size[] targetCaptureSizes =
+                        mStaticInfo.getAvailableSizesForFormatChecked(ImageFormat.RAW_SENSOR,
+                                StaticMetadata.StreamDirection.Output);
+                if (targetCaptureSizes.length == 0) {
+                    if (VERBOSE) {
+                        Log.v(TAG, "Skipping testSingleImageBasic - " +
+                                "no raw output streams for camera " + deviceId);
+                    }
+                    continue;
+                }
+
+                Size s = targetCaptureSizes[0];
+
+                // Create capture image reader
+                CameraTestUtils.SimpleImageReaderListener captureListener
+                        = new CameraTestUtils.SimpleImageReaderListener();
+                captureReader = createImageReader(s, ImageFormat.RAW_SENSOR, 2,
+                        captureListener);
+                Pair<Image, CaptureResult> resultPair = captureSingleRawShot(s, captureReader, captureListener);
+                CameraCharacteristics characteristics = mStaticInfo.getCharacteristics();
+
+                // Test simple writeImage, no header checks
+                DngCreator dngCreator = new DngCreator(characteristics, resultPair.second);
+                outputStream = new ByteArrayOutputStream();
+                dngCreator.writeImage(outputStream, resultPair.first);
+
+                if (VERBOSE && i == 0) {
+                    // Write out captured DNG file for the first camera device if setprop is enabled
+                    fileStream = new FileOutputStream(DEBUG_FILE_NAME_BASE +
+                            DEBUG_DNG_FILE);
+                    fileStream.write(outputStream.toByteArray());
+                    fileStream.flush();
+                    fileStream.close();
+                    Log.v(TAG, "Test DNG file for camera " + deviceId + " saved to " +
+                            DEBUG_FILE_NAME_BASE + DEBUG_DNG_FILE);
+                }
+            } finally {
+                closeDevice(deviceId);
+                closeImageReader(captureReader);
+
+                if (outputStream != null) {
+                    outputStream.close();
+                }
+
+                if (fileStream != null) {
+                    fileStream.close();
+                }
+            }
+        }
+    }
+
+    // TODO: Further tests for DNG header validation.
+
+    /**
+     * Capture a single raw image.
+     *
+     * <p>Capture an raw image for a given size.</p>
+     *
+     * @param s The size of the raw image to capture.  Must be one of the available sizes for this
+     *          device.
+     * @return a pair containing the {@link Image} and {@link CaptureResult} used for this capture.
+     */
+    private Pair<Image, CaptureResult> captureSingleRawShot(Size s, ImageReader captureReader,
+            CameraTestUtils.SimpleImageReaderListener captureListener) throws Exception {
+        if (VERBOSE) {
+            Log.v(TAG, "captureSingleRawShot - Capturing raw image.");
+        }
+
+        Size maxYuvSz = mOrderedPreviewSizes.get(0);
+        Size[] targetCaptureSizes =
+                mStaticInfo.getAvailableSizesForFormatChecked(ImageFormat.RAW_SENSOR,
+                        StaticMetadata.StreamDirection.Output);
+
+        // Validate size
+        boolean validSize = false;
+        for (int i = 0; i < targetCaptureSizes.length; ++i) {
+            if (targetCaptureSizes[i].equals(s)) {
+                validSize = true;
+                break;
+            }
+        }
+        assertTrue("Capture size is supported.", validSize);
+        Surface captureSurface = captureReader.getSurface();
+
+        // Capture images.
+        List<Surface> outputSurfaces = new ArrayList<Surface>();
+        outputSurfaces.add(captureSurface);
+        CaptureRequest.Builder request = prepareCaptureRequestForSurfaces(outputSurfaces);
+        request.set(CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE,
+                CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE_ON);
+        CameraTestUtils.SimpleCaptureListener resultListener =
+                new CameraTestUtils.SimpleCaptureListener();
+
+        startCapture(request.build(), /*repeating*/false, resultListener, mHandler);
+
+        // Verify capture result and images
+        CaptureResult result = resultListener.getCaptureResult(CAPTURE_WAIT_TIMEOUT_MS);
+
+        Image captureImage = captureListener.getImage(CAPTURE_WAIT_TIMEOUT_MS);
+
+        CameraTestUtils.validateImage(captureImage, s.getWidth(), s.getHeight(),
+                ImageFormat.RAW_SENSOR, null);
+        // Stop capture, delete the streams.
+        stopCapture(/*fast*/false);
+
+        return new Pair<Image, CaptureResult>(captureImage, result);
+    }
+
+    private CaptureRequest.Builder prepareCaptureRequestForSurfaces(List<Surface> surfaces)
+            throws Exception {
+        configureCameraOutputs(mCamera, surfaces, mCameraListener);
+
+        CaptureRequest.Builder captureBuilder =
+                mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
+        assertNotNull("Fail to get captureRequest", captureBuilder);
+        for (Surface surface : surfaces) {
+            captureBuilder.addTarget(surface);
+        }
+
+        return captureBuilder;
+    }
+}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java
new file mode 100644
index 0000000..3a0ae09
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.camera2.cts;
+
+import static android.hardware.camera2.CameraCharacteristics.*;
+
+import android.graphics.ImageFormat;
+import android.hardware.camera2.CameraCharacteristics;
+import android.hardware.camera2.cts.helpers.StaticMetadata;
+import android.hardware.camera2.cts.helpers.StaticMetadata.CheckLevel;
+import android.hardware.camera2.cts.testcases.Camera2AndroidTestCase;
+import android.util.Log;
+import android.util.Size;
+
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * <p>
+ * This class covers the {@link CameraCharacteristics} tests that are not
+ * covered by {@link CaptureRequestTest} and {@link CameraCharacteristicsTest}
+ * (auto-generated tests that only do the non-null checks).
+ * </p>
+ * <p>
+ * Note that most of the tests in this class don't require camera open.
+ * </p>
+ */
+public class StaticMetadataTest extends Camera2AndroidTestCase {
+    private static final String TAG = "StaticMetadataTest";
+    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
+    private static final float MIN_FPS_FOR_FULL_DEVICE = 20.0f;
+    private static final int RAW_STREAM_IDX = 0;
+    private static final int PROCESSED_NON_STALLING_STREAM_IDX = 1;
+    private static final int PROCESSED_STALLING_STREAM_IDX = 2;
+
+
+    /**
+     * Test the available capability for different hardware support level devices.
+     */
+    public void testHwSupportedLevel() throws Exception {
+        for (String id : mCameraIds) {
+            initStaticMetadata(id);
+            List<Integer> availabeCaps = mStaticInfo.getAvailableCapabilitiesChecked();
+
+            mCollector.expectTrue("All device must contains BACKWARD_COMPATIBLE capability",
+                    availabeCaps.contains(REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE));
+
+            if (mStaticInfo.isHardwareLevelFull()) {
+                // Capability advertisement must be right.
+                mCollector.expectTrue("Full device must contains MANUAL_SENSOR capability",
+                        availabeCaps.contains(REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR));
+                mCollector.expectTrue("Full device must contains MANUAL_POST_PROCESSING capability",
+                        availabeCaps.contains(
+                                REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING));
+
+                // Max resolution fps must be >= 20.
+                mCollector.expectTrue("Full device must support at least 20fps for max resolution",
+                        getFpsForMaxSize(id) >= MIN_FPS_FOR_FULL_DEVICE);
+
+                // Need support per frame control
+                mCollector.expectTrue("Full device must support per frame control",
+                        mStaticInfo.isPerFrameControlSupported());
+            }
+
+            // TODO: test all the keys mandatory for all capability devices.
+        }
+    }
+
+    /**
+     * Test max number of output stream reported by device
+     */
+    public void testMaxNumOutputStreams() throws Exception {
+        for (String id : mCameraIds) {
+            initStaticMetadata(id);
+            int[] maxNumStreams = mStaticInfo.getMaxNumOutputStreamsChecked();
+            assertTrue("max number of streams must be a 3 element array",
+                    maxNumStreams.length == 3);
+
+            mCollector.expectTrue("max number of raw output streams must be a non negative number",
+                    maxNumStreams[RAW_STREAM_IDX] >= 0);
+            mCollector.expectTrue("max number of processed (stalling) output streams must be >= 1",
+                    maxNumStreams[PROCESSED_STALLING_STREAM_IDX] >= 1);
+
+            if (mStaticInfo.isHardwareLevelFull()) {
+                mCollector.expectTrue("max number of processed (non-stalling) output streams" +
+                        "must be >= 3 for FULL device",
+                        maxNumStreams[PROCESSED_NON_STALLING_STREAM_IDX] >= 3);
+            } else {
+                mCollector.expectTrue("max number of processed (non-stalling) output streams" +
+                        "must be >= 2 for LIMITED device",
+                        maxNumStreams[PROCESSED_NON_STALLING_STREAM_IDX] >= 2);
+            }
+        }
+
+    }
+
+    /**
+     * Test lens facing.
+     */
+    public void testLensFacing() throws Exception {
+        for (String id : mCameraIds) {
+            initStaticMetadata(id);
+            mStaticInfo.getLensFacingChecked();
+        }
+    }
+
+    private float getFpsForMaxSize(String cameraId) throws Exception {
+        HashMap<Size, Long> minFrameDurationMap =
+                mStaticInfo.getAvailableMinFrameDurationsForFormatChecked(ImageFormat.YUV_420_888);
+
+        Size[] sizes = CameraTestUtils.getSupportedSizeForFormat(ImageFormat.YUV_420_888,
+                cameraId, mCameraManager);
+        Size maxSize = CameraTestUtils.getMaxSize(sizes);
+        Long minDuration = minFrameDurationMap.get(maxSize);
+        if (VERBOSE) {
+            Log.v(TAG, "min frame duration for size " + maxSize + " is " + minDuration);
+        }
+        assertTrue("min duration for max size must be postive number",
+                minDuration != null && minDuration > 0);
+
+        return 1e9f / minDuration;
+    }
+
+    /**
+     * Initialize static metadata for a given camera id.
+     */
+    private void initStaticMetadata(String cameraId) throws Exception {
+        mCollector.setCameraId(cameraId);
+        mStaticInfo = new StaticMetadata(mCameraManager.getCameraCharacteristics(cameraId),
+                CheckLevel.COLLECT, /* collector */mCollector);
+    }
+}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 76f79f7..bca554e 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -26,7 +26,6 @@
 import android.hardware.camera2.cts.CameraTestUtils;
 import android.hardware.camera2.params.StreamConfigurationMap;
 import android.util.Log;
-import android.util.Range;
 import android.util.Rational;
 
 import junit.framework.Assert;
@@ -161,11 +160,9 @@
      * @return true if the device is FULL, false otherwise.
      */
     public boolean isHardwareLevelFull() {
-        // TODO: Make this key non-optional for all HAL3.2+ devices
         Integer hwLevel = getValueFromKeyNonNull(
                 CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
 
-        // Bad. Missing metadata. Warning is logged.
         if (hwLevel == null) {
             return false;
         }
@@ -1273,6 +1270,64 @@
     }
 
     /**
+     * Get available capabilities and do the sanity check.
+     *
+     * @return reported available capabilities list, empty list if the value is unavailable.
+     */
+    public List<Integer> getAvailableCapabilitiesChecked() {
+        Key<int[]> key =
+                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES;
+        int[] availableCaps = getValueFromKeyNonNull(key);
+        List<Integer> capList;
+
+        if (availableCaps == null) {
+            return new ArrayList<Integer>();
+        }
+
+        checkArrayValuesInRange(key, availableCaps,
+                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE,
+                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_DNG);
+        capList = Arrays.asList(CameraTestUtils.toObject(availableCaps));
+        return capList;
+    }
+
+    /**
+     * Get max number of output streams and do the basic sanity check.
+     *
+     * @return reported max number of output stream array, empty array if the value is unavailable.
+     */
+    public int[] getMaxNumOutputStreamsChecked() {
+        Key<int[]> key =
+                CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_STREAMS;
+        int[] maxNumStreams = getValueFromKeyNonNull(key);
+
+        if (maxNumStreams == null) {
+            return new int[0];
+        }
+
+        return maxNumStreams;
+    }
+
+    /**
+     * Get lens facing and do the sanity check
+     * @return lens facing, return default value (BACK) if value is unavailable.
+     */
+    public int getLensFacingChecked() {
+        Key<Integer> key =
+                CameraCharacteristics.LENS_FACING;
+        Integer facing = getValueFromKeyNonNull(key);
+
+        if (facing == null) {
+            return CameraCharacteristics.LENS_FACING_BACK;
+        }
+
+        checkTrueForKey(key, " value is out of range ",
+                facing >= CameraCharacteristics.LENS_FACING_FRONT &&
+                facing <= CameraCharacteristics.LENS_FACING_BACK);
+        return facing;
+    }
+
+    /**
      * Get the value in index for a fixed-size array from a given key.
      *
      * <p>If the camera device is incorrectly reporting values, log a warning and return
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorTest.java b/tests/tests/hardware/src/android/hardware/cts/SensorTest.java
index 907759f..d5f1434 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorTest.java
@@ -21,6 +21,7 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 import android.content.Context;
 import android.content.pm.PackageManager;
@@ -34,12 +35,16 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.test.AndroidTestCase;
+import android.util.Log;
 
 public class SensorTest extends AndroidTestCase {
     private SensorManager mSensorManager;
     private TriggerListener mTriggerListener;
     private SensorListener mSensorListener;
-    private ArrayList<Sensor> mContinuousSensorList;
+    private List<Sensor> mSensorList;
+    private static final String TAG = "SensorTest";
+    // Test only SDK defined sensors. Any sensors with type > 100 are ignored.
+    private static final int MAX_SENSOR_TYPE = 100;
 
     @Override
     protected void setUp() throws Exception {
@@ -47,18 +52,7 @@
         mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
         mTriggerListener = new TriggerListener();
         mSensorListener = new SensorListener();
-        mContinuousSensorList = new ArrayList<Sensor>();
-        for (int i = Sensor.TYPE_ACCELEROMETER; i <= Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR; ++i) {
-            Sensor sensor = mSensorManager.getDefaultSensor(i);
-            // Skip all non-continuous mode sensors.
-            if (sensor == null || Sensor.TYPE_SIGNIFICANT_MOTION == i ||
-                Sensor.TYPE_STEP_COUNTER == i || Sensor.TYPE_STEP_DETECTOR == i ||
-                Sensor.TYPE_LIGHT == i || Sensor.TYPE_PROXIMITY == i ||
-                Sensor.TYPE_AMBIENT_TEMPERATURE == i) {
-                continue;
-            }
-            mContinuousSensorList.add(sensor);
-        }
+        mSensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
     }
 
     public void testSensorOperations() {
@@ -79,7 +73,7 @@
 
         sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
         boolean hasStepCounter = getContext().getPackageManager().hasSystemFeature(
-                                        PackageManager.FEATURE_SENSOR_STEP_COUNTER);
+                PackageManager.FEATURE_SENSOR_STEP_COUNTER);
         // stepcounter sensor is optional
         if (hasStepCounter) {
             assertEquals(Sensor.TYPE_STEP_COUNTER, sensor.getType());
@@ -90,7 +84,7 @@
 
         sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
         boolean hasStepDetector = getContext().getPackageManager().hasSystemFeature(
-                                        PackageManager.FEATURE_SENSOR_STEP_DETECTOR);
+                PackageManager.FEATURE_SENSOR_STEP_DETECTOR);
         // stepdetector sensor is optional
         if (hasStepDetector) {
             assertEquals(Sensor.TYPE_STEP_DETECTOR, sensor.getType());
@@ -189,76 +183,77 @@
     // Register for updates from each continuous mode sensor, wait for 25 events, call flush and
     // wait for flushCompleteEvent before unregistering for the sensor.
     public void testBatchAndFlush() throws Exception {
-        for (Sensor sensor : mContinuousSensorList) {
-            final CountDownLatch eventReceived = new CountDownLatch(25);
-            final CountDownLatch flushReceived = new CountDownLatch(1);
-            SensorEventListener2 listener = new SensorEventListener2() {
-                @Override
-                public void onSensorChanged(SensorEvent event) {
-                    eventReceived.countDown();
-                }
-
-                @Override
-                public void onAccuracyChanged(Sensor sensor, int accuracy) {
-                }
-
-                @Override
-                public void onFlushCompleted(Sensor sensor) {
-                    flushReceived.countDown();
-                }
-            };
-            boolean result = mSensorManager.registerListener(listener, sensor,
-                                            SensorManager.SENSOR_DELAY_NORMAL, 10000000);
-            assertTrue(result);
-            // Wait for 25 events and call flush.
-            eventReceived.await();
-            result = mSensorManager.flush(listener);
-            assertTrue(result);
-            flushReceived.await();
-            mSensorManager.unregisterListener(listener);
+        for (Sensor sensor : mSensorList) {
+            // Skip OEM defined sensors and trigger sensors.
+            if (sensor.getType() > MAX_SENSOR_TYPE || sensor.getMinDelay() < 0) {
+                continue;
+            }
+            registerListenerCallFlush(sensor, null);
         }
     }
 
     // Same as testBatchAndFlush but using Handler version of the API to register for sensors.
     // onSensorChanged is now called on a background thread.
     public void testBatchAndFlushWithHandler() throws Exception {
-        for (Sensor sensor : mContinuousSensorList) {
-            final CountDownLatch eventReceived = new CountDownLatch(25);
-            final CountDownLatch flushReceived = new CountDownLatch(1);
-            SensorEventListener2 listener = new SensorEventListener2() {
-                @Override
-                public void onSensorChanged(SensorEvent event) {
-                    eventReceived.countDown();
-                }
-
-                @Override
-                public void onAccuracyChanged(Sensor sensor, int accuracy) {
-                }
-
-                @Override
-                public void onFlushCompleted(Sensor sensor) {
-                    flushReceived.countDown();
-                }
-            };
-            HandlerThread handlerThread = new HandlerThread("sensorThread");
-            handlerThread.start();
-            Handler handler = new Handler(handlerThread.getLooper());
-            boolean result = mSensorManager.registerListener(listener, sensor,
-                                            SensorManager.SENSOR_DELAY_NORMAL, 15000000,
-                                            handler);
-            assertTrue(result);
-            // Wait for 25 events and call flush.
-            eventReceived.await();
-            result = mSensorManager.flush(listener);
-            assertTrue(result);
-            flushReceived.await();
-            mSensorManager.unregisterListener(listener);
+        HandlerThread handlerThread = new HandlerThread("sensorThread");
+        handlerThread.start();
+        Handler handler = new Handler(handlerThread.getLooper());
+        for (Sensor sensor : mSensorList) {
+            // Skip OEM defined sensors and trigger sensors.
+            if (sensor.getType() > MAX_SENSOR_TYPE || sensor.getMinDelay() < 0) {
+                continue;
+            }
+            registerListenerCallFlush(sensor, handler);
         }
     }
 
+    private void registerListenerCallFlush(Sensor sensor, Handler handler)
+            throws InterruptedException {
+        final CountDownLatch eventReceived = new CountDownLatch(25);
+        final CountDownLatch flushReceived = new CountDownLatch(1);
+        SensorEventListener2 listener = new SensorEventListener2() {
+            @Override
+            public void onSensorChanged(SensorEvent event) {
+                eventReceived.countDown();
+            }
+
+            @Override
+            public void onAccuracyChanged(Sensor sensor, int accuracy) {
+            }
+
+            @Override
+            public void onFlushCompleted(Sensor sensor) {
+                flushReceived.countDown();
+            }
+        };
+        // Consider only continuous mode sensors for testing registerListener.
+        if (sensor.getMinDelay() > 0) {
+            Log.i(TAG, "testBatch " + sensor.getName());
+            boolean result = mSensorManager.registerListener(listener, sensor,
+                    SensorManager.SENSOR_DELAY_NORMAL, 10000000, handler);
+            assertTrue("registerListener failed " + sensor.getName(), result);
+            // Wait for 25 events or 20 seconds.
+            boolean countZero = eventReceived.await(20, TimeUnit.SECONDS);
+            if (!countZero) {
+                fail("Timed out waiting for events from " + sensor.getName());
+            }
+        }
+
+        Log.i(TAG, "testFlush " + sensor.getName());
+        boolean result = mSensorManager.flush(listener);
+        assertTrue("flush failed " + sensor.getName(), result);
+        boolean countZero = flushReceived.await(20, TimeUnit.SECONDS);
+        if (!countZero) {
+            fail("Timed out waiting for flushCompleteEvent from " + sensor.getName());
+        }
+        mSensorManager.unregisterListener(listener);
+        Log.i(TAG, "testBatchAndFlush pass " + sensor.getName());
+    }
+
     // Call registerListener for multiple sensors at a time and call flush.
     public void testBatchAndFlushWithMutipleSensors() throws Exception {
-        int numSensors = mContinuousSensorList.size() < 3 ? mContinuousSensorList.size() : 3;
+        final int MAX_SENSORS = 3;
+        int numSensors = mSensorList.size() < MAX_SENSORS ? mSensorList.size() : MAX_SENSORS;
         if (numSensors == 0) {
             return;
         }
@@ -279,17 +274,37 @@
                 flushReceived.countDown();
             }
         };
-        for (int i = 0; i < numSensors; ++i) {
-            Sensor sensor = mContinuousSensorList.get(i);
+        StringBuilder registeredSensors = new StringBuilder(30);
+        for (Sensor sensor : mSensorList) {
+            // Skip all non-continuous sensors.
+            if (sensor.getMinDelay() <= 0 || sensor.getType() > MAX_SENSOR_TYPE) {
+                continue;
+            }
             boolean result = mSensorManager.registerListener(listener, sensor,
-                                            SensorManager.SENSOR_DELAY_FASTEST);
-            assertTrue(result);
+                    SensorManager.SENSOR_DELAY_FASTEST, 10000000);
+            assertTrue("registerListener failed for " + sensor.getName(), result);
+            registeredSensors.append(sensor.getName());
+            registeredSensors.append(" ");
+            if (--numSensors == 0) {
+                break;
+            }
         }
-        // Wait for N events and call flush.
-        eventReceived.await();
+        if (registeredSensors.toString().isEmpty()) {
+            return;
+        }
+
+        Log.i(TAG, "testBatchAndFlushWithMutipleSensors " + registeredSensors);
+        // Wait for numSensors * 50 events or 20 seconds.
+        boolean countZero = eventReceived.await(20, TimeUnit.SECONDS);
+        if (!countZero) {
+            fail("Timed out waiting for events from " + registeredSensors.toString());
+        }
         boolean result = mSensorManager.flush(listener);
-        assertTrue(result);
-        flushReceived.await();
+        assertTrue("flush failed " + registeredSensors.toString(), result);
+        countZero = flushReceived.await(20, TimeUnit.SECONDS);
+        if (!countZero) {
+            fail("Timed out waiting for flushCompleteEvent from " + registeredSensors.toString());
+        }
         mSensorManager.unregisterListener(listener);
     }
 
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
index e2112b7..95e3add 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
@@ -33,7 +33,7 @@
     }
 
     public void testCookieSyncManager() throws Exception {
-        if (!NullWebViewUtils.isWebViewAvailable()) {
+        if (getActivity().getWebView() == null) {
             return;
         }
         CookieSyncManager csm1 = CookieSyncManager.createInstance(getActivity());
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
index 704ae24..7f3b183 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
@@ -36,7 +36,7 @@
     protected void setUp() throws Exception {
         super.setUp();
 
-        if (!NullWebViewUtils.isWebViewAvailable()) {
+        if (getActivity().getWebView() == null) {
             return;
         }