Merge "resolve merge conflicts of 49daa6e6db to mnc-dev." into mnc-dev
diff --git a/build/test_package.mk b/build/test_package.mk
index c6b0865..13e582e 100644
--- a/build/test_package.mk
+++ b/build/test_package.mk
@@ -39,6 +39,11 @@
 else
 PRIVATE_CTS_TEST_PACKAGE_NAME_ := android.$(notdir $(LOCAL_PATH))
 endif
+ifeq ($(cts_runtime_hint),)
+$(cts_package_xml): PRIVATE_CTS_RUNTIME_HINT := "0"
+else
+$(cts_package_xml): PRIVATE_CTS_RUNTIME_HINT := $(cts_runtime_hint)
+endif
 $(cts_package_xml): PRIVATE_TEST_PACKAGE := $(PRIVATE_CTS_TEST_PACKAGE_NAME_)
 $(cts_package_xml): PRIVATE_MANIFEST := $(LOCAL_PATH)/AndroidManifest.xml
 $(cts_package_xml): PRIVATE_TEST_TYPE := $(if $(LOCAL_CTS_TEST_RUNNER),$(LOCAL_CTS_TEST_RUNNER),'')
@@ -56,9 +61,13 @@
 						-i "$(PRIVATE_INSTRUMENTATION)" \
 						-n $(PRIVATE_PACKAGE) \
 						-p $(PRIVATE_TEST_PACKAGE) \
+						-x "runtimeHint->$(PRIVATE_CTS_RUNTIME_HINT)" \
 						-e $(CTS_EXPECTATIONS) \
 						-b $(CTS_UNSUPPORTED_ABIS) \
 						-a $(CTS_TARGET_ARCH) \
 						-o $@
 # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma.
 $(my_register_name) : $(cts_package_xml) $(cts_module_test_config)
+
+# Make sure we clear cts_runtime_hint, so other parents will use the default if they do not set cts_runtime_hint.
+cts_runtime_hint :=
diff --git a/suite/cts/deviceTests/filesystemperf/Android.mk b/suite/cts/deviceTests/filesystemperf/Android.mk
index 843d21a..7ee93de 100644
--- a/suite/cts/deviceTests/filesystemperf/Android.mk
+++ b/suite/cts/deviceTests/filesystemperf/Android.mk
@@ -26,5 +26,7 @@
 
 LOCAL_SDK_VERSION := 16
 
+cts_runtime_hint := 28
+
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/suite/cts/deviceTests/videoperf/Android.mk b/suite/cts/deviceTests/videoperf/Android.mk
index a393683..b589475 100644
--- a/suite/cts/deviceTests/videoperf/Android.mk
+++ b/suite/cts/deviceTests/videoperf/Android.mk
@@ -33,5 +33,7 @@
 
 LOCAL_SDK_VERSION := current
 
+cts_runtime_hint := 50
+
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/hardware/Android.mk b/tests/tests/hardware/Android.mk
index 9c26d8a..07d5de9 100644
--- a/tests/tests/hardware/Android.mk
+++ b/tests/tests/hardware/Android.mk
@@ -57,4 +57,6 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
+cts_runtime_hint := 120
+
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/keystore/Android.mk b/tests/tests/keystore/Android.mk
index eaf5389..e51bc04 100644
--- a/tests/tests/keystore/Android.mk
+++ b/tests/tests/keystore/Android.mk
@@ -26,6 +26,8 @@
 
 LOCAL_SDK_VERSION := current
 
+cts_runtime_hint := 28
+
 include $(BUILD_CTS_PACKAGE)
 
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/media/Android.mk b/tests/tests/media/Android.mk
index 13daca6..ea7256d 100644
--- a/tests/tests/media/Android.mk
+++ b/tests/tests/media/Android.mk
@@ -51,6 +51,8 @@
 #LOCAL_SDK_VERSION := current
 LOCAL_JAVA_LIBRARIES += android.test.runner org.apache.http.legacy
 
+cts_runtime_hint := 265
+
 include $(BUILD_CTS_PACKAGE)
 
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/media/src/android/media/cts/AudioRecordTest.java b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
index b1ee3f5..1865bb2 100644
--- a/tests/tests/media/src/android/media/cts/AudioRecordTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
@@ -696,10 +696,12 @@
         long firstSampleTime = 0;
 
         // blank final variables: all successful paths will initialize the times.
+        // this must be declared here for visibility as they are set within the try block.
         final long endTime;
         final long startTime;
         final long stopRequestTime;
         final long stopTime;
+        final long coldInputStartTime;
 
         try {
             if (markerPeriodsPerSecond != 0) {
@@ -839,11 +841,21 @@
 
             // We've read all the frames, now check the record timing.
             endTime = System.currentTimeMillis();
-            //Log.d(TAG, "first sample time " + (firstSampleTime - startTime)
+
+            coldInputStartTime = firstSampleTime - startTime;
+            //Log.d(TAG, "first sample time " + coldInputStartTime
             //        + " test time " + (endTime - firstSampleTime));
-            // Verify recording starts within 200 ms of record.startRecording() (typical 100ms)
+
+            if (coldInputStartTime > 200) {
+                Log.w(TAG, "cold input start time way too long "
+                        + coldInputStartTime + " > 200ms");
+            } else if (coldInputStartTime > 100) {
+                Log.w(TAG, "cold input start time too long "
+                        + coldInputStartTime + " > 100ms");
+            }
+            assertTrue(coldInputStartTime < 5000); // must start within 5 seconds.
+
             // Verify recording completes within 50 ms of expected test time (typical 20ms)
-            assertEquals(0, firstSampleTime - startTime, 200);
             assertEquals(TEST_TIME_MS, endTime - firstSampleTime, auditRecording ? 1000 : 50);
 
             // Even though we've read all the frames we want, the events may not be sent to
@@ -945,7 +957,7 @@
 
         // report this
         ReportLog log = getReportLog();
-        log.printValue(reportName + ": startRecording lag", firstSampleTime - startTime,
+        log.printValue(reportName + ": startRecording lag", coldInputStartTime,
                 ResultType.LOWER_BETTER, ResultUnit.MS);
         log.printValue(reportName + ": stop execution time", stopTime - stopRequestTime,
                 ResultType.LOWER_BETTER, ResultUnit.MS);
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecTest.java b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
index bb05ea0..d3ab54f 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
@@ -467,22 +467,32 @@
     }
 
     public void testReleaseAfterFlush() throws IOException, InterruptedException {
+        String mimes[] = new String[] { MIME_TYPE, MIME_TYPE_AUDIO};
+        for (String mime : mimes) {
+            if (!MediaUtils.checkEncoder(mime)) {
+                continue;
+            }
+            testReleaseAfterFlush(mime);
+        }
+    }
+
+    private void testReleaseAfterFlush(String mime) throws IOException, InterruptedException {
         CountDownLatch buffersExhausted = null;
         CountDownLatch codecFlushed = null;
         AtomicInteger numBuffers = null;
 
         // sync flush from same thread
-        MediaCodec encoder = MediaCodec.createEncoderByType(MIME_TYPE);
-        runReleaseAfterFlush(encoder, buffersExhausted, codecFlushed, numBuffers);
+        MediaCodec encoder = MediaCodec.createEncoderByType(mime);
+        runReleaseAfterFlush(mime, encoder, buffersExhausted, codecFlushed, numBuffers);
 
         // sync flush from different thread
-        encoder = MediaCodec.createEncoderByType(MIME_TYPE);
+        encoder = MediaCodec.createEncoderByType(mime);
         buffersExhausted = new CountDownLatch(1);
         codecFlushed = new CountDownLatch(1);
         numBuffers = new AtomicInteger();
         Thread flushThread = new FlushThread(encoder, buffersExhausted, codecFlushed);
         flushThread.start();
-        runReleaseAfterFlush(encoder, buffersExhausted, codecFlushed, numBuffers);
+        runReleaseAfterFlush(mime, encoder, buffersExhausted, codecFlushed, numBuffers);
         flushThread.join();
 
         // async
@@ -495,19 +505,19 @@
         Handler handler = new Handler(callbackThread.getLooper());
 
         // async flush from same thread
-        encoder = MediaCodec.createEncoderByType(MIME_TYPE);
+        encoder = MediaCodec.createEncoderByType(mime);
         buffersExhausted = null;
         codecFlushed = null;
         ReleaseAfterFlushCallback callback =
-                new ReleaseAfterFlushCallback(encoder, buffersExhausted, codecFlushed, nBuffs);
+                new ReleaseAfterFlushCallback(mime, encoder, buffersExhausted, codecFlushed, nBuffs);
         encoder.setCallback(callback, handler); // setCallback before configure, which is called in run
         callback.run(); // drive input on main thread
 
         // async flush from different thread
-        encoder = MediaCodec.createEncoderByType(MIME_TYPE);
+        encoder = MediaCodec.createEncoderByType(mime);
         buffersExhausted = new CountDownLatch(1);
         codecFlushed = new CountDownLatch(1);
-        callback = new ReleaseAfterFlushCallback(encoder, buffersExhausted, codecFlushed, nBuffs);
+        callback = new ReleaseAfterFlushCallback(mime, encoder, buffersExhausted, codecFlushed, nBuffs);
         encoder.setCallback(callback, handler);
         flushThread = new FlushThread(encoder, buffersExhausted, codecFlushed);
         flushThread.start();
@@ -544,17 +554,21 @@
     }
 
     private static class ReleaseAfterFlushCallback extends MediaCodec.Callback implements Runnable {
+        final String mMime;
         final MediaCodec mEncoder;
         final CountDownLatch mBuffersExhausted, mCodecFlushed;
         final int mNumBuffersBeforeFlush;
 
         CountDownLatch mStopInput = new CountDownLatch(1);
+        List<Integer> mInputBufferIndices = new ArrayList<>();
         List<Integer> mOutputBufferIndices = new ArrayList<>();
 
-        ReleaseAfterFlushCallback(MediaCodec encoder,
+        ReleaseAfterFlushCallback(String mime,
+                MediaCodec encoder,
                 CountDownLatch buffersExhausted,
                 CountDownLatch codecFlushed,
                 int numBuffersBeforeFlush) {
+            mMime = mime;
             mEncoder = encoder;
             mBuffersExhausted = buffersExhausted;
             mCodecFlushed = codecFlushed;
@@ -563,7 +577,10 @@
 
         @Override
         public void onInputBufferAvailable(MediaCodec codec, int index) {
-            fail(codec + " onInputBufferAvailable " + index);
+            assertTrue("video onInputBufferAvailable " + index, mMime.startsWith("audio/"));
+            synchronized (mInputBufferIndices) {
+                mInputBufferIndices.add(index);
+            };
         }
 
         @Override
@@ -590,11 +607,20 @@
         public void run() {
             InputSurface inputSurface = null;
             try {
-                inputSurface = initCodecAndSurface(mEncoder);
+                inputSurface = initCodecAndSurface(mMime, mEncoder);
                 do {
-                    GLES20.glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
-                    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
-                    inputSurface.swapBuffers();
+                    int inputIndex = -1;
+                    if (inputSurface == null) {
+                        // asynchronous audio codec
+                        synchronized (mInputBufferIndices) {
+                            if (mInputBufferIndices.isEmpty()) {
+                                continue;
+                            } else {
+                                inputIndex = mInputBufferIndices.remove(0);
+                            }
+                        }
+                    }
+                    feedEncoder(mEncoder, inputSurface, inputIndex);
                 } while (!mStopInput.await(TIMEOUT_USEC, TimeUnit.MICROSECONDS));
             } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
@@ -606,13 +632,14 @@
     }
 
     private static void runReleaseAfterFlush(
+            String mime,
             MediaCodec encoder,
             CountDownLatch buffersExhausted,
             CountDownLatch codecFlushed,
             AtomicInteger numBuffers) {
         InputSurface inputSurface = null;
         try {
-            inputSurface = initCodecAndSurface(encoder);
+            inputSurface = initCodecAndSurface(mime, encoder);
             List<Integer> outputBufferIndices = getOutputBufferIndices(encoder, inputSurface);
             if (numBuffers != null) {
                 numBuffers.set(outputBufferIndices.size());
@@ -623,19 +650,29 @@
         }
     }
 
-    private static InputSurface initCodecAndSurface(MediaCodec encoder) {
-        InputSurface inputSurface;
-        CodecInfo info = getAvcSupportedFormatInfo();
-        MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, info.mMaxW, info.mMaxH);
-        format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
-                MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
-        format.setInteger(MediaFormat.KEY_BIT_RATE, info.mBitRate);
-        format.setInteger(MediaFormat.KEY_FRAME_RATE, info.mFps);
-        format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
-        OutputSurface outputSurface = new OutputSurface(1, 1);
-        encoder.configure(format, outputSurface.getSurface(), null, MediaCodec.CONFIGURE_FLAG_ENCODE);
-        inputSurface = new InputSurface(encoder.createInputSurface());
-        inputSurface.makeCurrent();
+    private static InputSurface initCodecAndSurface(String mime, MediaCodec encoder) {
+        MediaFormat format;
+        InputSurface inputSurface = null;
+        if (mime.startsWith("audio/")) {
+            format = MediaFormat.createAudioFormat(mime, AUDIO_SAMPLE_RATE, AUDIO_CHANNEL_COUNT);
+            format.setInteger(MediaFormat.KEY_AAC_PROFILE, AUDIO_AAC_PROFILE);
+            format.setInteger(MediaFormat.KEY_BIT_RATE, AUDIO_BIT_RATE);
+            encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
+        } else if (MIME_TYPE.equals(mime)) {
+            CodecInfo info = getAvcSupportedFormatInfo();
+            format = MediaFormat.createVideoFormat(mime, info.mMaxW, info.mMaxH);
+            format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+                    MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
+            format.setInteger(MediaFormat.KEY_BIT_RATE, info.mBitRate);
+            format.setInteger(MediaFormat.KEY_FRAME_RATE, info.mFps);
+            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
+            OutputSurface outputSurface = new OutputSurface(1, 1);
+            encoder.configure(format, outputSurface.getSurface(), null, MediaCodec.CONFIGURE_FLAG_ENCODE);
+            inputSurface = new InputSurface(encoder.createInputSurface());
+            inputSurface.makeCurrent();
+        } else {
+            throw new IllegalArgumentException("unsupported mime type: " + mime);
+        }
         encoder.start();
         return inputSurface;
     }
@@ -657,9 +694,7 @@
         List<Integer> indices = new ArrayList<>();
         do {
             feedMoreFrames = indices.isEmpty();
-            GLES20.glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
-            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
-            inputSurface.swapBuffers();
+            feedEncoder(encoder, inputSurface, -1);
             // dequeue buffers until not available
             int index = encoder.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);
             while (index >= 0) {
@@ -672,6 +707,31 @@
         return indices;
     }
 
+    /**
+     * @param encoder audio/video encoder
+     * @param inputSurface null for and only for audio encoders
+     * @param inputIndex only used for audio; if -1 the function would attempt to dequeue from encoder;
+     * do not use -1 for asynchronous encoders
+     */
+    private static void feedEncoder(MediaCodec encoder, InputSurface inputSurface, int inputIndex) {
+        if (inputSurface == null) {
+            // audio
+            while (inputIndex == -1) {
+                inputIndex = encoder.dequeueInputBuffer(TIMEOUT_USEC);
+            }
+            ByteBuffer inputBuffer = encoder.getInputBuffer(inputIndex);;
+            for (int i = 0; i < inputBuffer.capacity() / 2; i++) {
+                inputBuffer.putShort((short)i);
+            }
+            encoder.queueInputBuffer(inputIndex, 0, inputBuffer.limit(), 0, 0);
+        } else {
+            // video
+            GLES20.glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
+            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+            inputSurface.swapBuffers();
+        }
+    }
+
     private static void releaseAfterFlush(
             MediaCodec encoder,
             List<Integer> outputBufferIndices,
@@ -798,6 +858,11 @@
     }
 
     public void testDecodeAfterFlush() throws InterruptedException {
+        testDecodeAfterFlush(true /* audio */);
+        testDecodeAfterFlush(false /* audio */);
+    }
+
+    private void testDecodeAfterFlush(final boolean audio) throws InterruptedException {
         final int INPUT_RESOURCE_ID =
                 R.raw.video_480x360_mp4_h264_1350kbps_30fps_aac_stereo_192kbps_44100hz;
 
@@ -806,23 +871,27 @@
         final int DECODING_TIMEOUT_MS = 10000;
 
         final AtomicBoolean completed = new AtomicBoolean(false);
-        Thread videoDecodingThread = new Thread(new Runnable() {
+        Thread decodingThread = new Thread(new Runnable() {
             @Override
             public void run() {
                 OutputSurface outputSurface = null;
                 MediaExtractor mediaExtractor = null;
                 MediaCodec mediaCodec = null;
                 try {
-                    outputSurface = new OutputSurface(1, 1);
-                    mediaExtractor = getMediaExtractorForMimeType(INPUT_RESOURCE_ID, "video/");
+                    String mimeTypePrefix  = audio ? "audio/" : "video/";
+                    if (!audio) {
+                        outputSurface = new OutputSurface(1, 1);
+                    }
+                    mediaExtractor = getMediaExtractorForMimeType(INPUT_RESOURCE_ID, mimeTypePrefix);
                     MediaFormat mediaFormat =
                             mediaExtractor.getTrackFormat(mediaExtractor.getSampleTrackIndex());
                     if (!MediaUtils.checkDecoderForFormat(mediaFormat)) {
+                        completed.set(true);
                         return; // skip
                     }
                     String mimeType = mediaFormat.getString(MediaFormat.KEY_MIME);
                     mediaCodec = MediaCodec.createDecoderByType(mimeType);
-                    mediaCodec.configure(mediaFormat, outputSurface.getSurface(),
+                    mediaCodec.configure(mediaFormat, outputSurface == null ? null : outputSurface.getSurface(),
                             null /* crypto */, 0 /* flags */);
                     mediaCodec.start();
 
@@ -851,10 +920,10 @@
                 }
             }
         });
-        videoDecodingThread.start();
-        videoDecodingThread.join(DECODING_TIMEOUT_MS);
+        decodingThread.start();
+        decodingThread.join(DECODING_TIMEOUT_MS);
         // In case it's timed out, need to stop the thread and have all resources released.
-        videoDecodingThread.interrupt();
+        decodingThread.interrupt();
         if (!completed.get()) {
             throw new RuntimeException("timed out decoding to end-of-stream");
         }
diff --git a/tests/tests/mediastress/Android.mk b/tests/tests/mediastress/Android.mk
index 5bb23d0..d78ddac 100644
--- a/tests/tests/mediastress/Android.mk
+++ b/tests/tests/mediastress/Android.mk
@@ -33,6 +33,8 @@
 
 LOCAL_SDK_VERSION := current
 
+cts_runtime_hint := 170
+
 include $(BUILD_CTS_PACKAGE)
 
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/print/src/android/print/cts/BasePrintTest.java b/tests/tests/print/src/android/print/cts/BasePrintTest.java
index 1378bdb..321ae39 100644
--- a/tests/tests/print/src/android/print/cts/BasePrintTest.java
+++ b/tests/tests/print/src/android/print/cts/BasePrintTest.java
@@ -139,6 +139,14 @@
     }
 
     @Override
+    protected void runTest() throws Throwable {
+        // Do nothing if the device does not support printing.
+        if (supportsPrinting()) {
+            super.runTest();
+        }
+    }
+
+    @Override
     public void setUp() throws Exception {
         super.setUp();
         if (!supportsPrinting()) {
@@ -181,25 +189,28 @@
 
     @Override
     public void tearDown() throws Exception {
-        if (supportsPrinting()) {
-            // Done with the activity.
-            getActivity().finish();
-            enableImes();
-
-            // Restore the locale if needed.
-            if (mOldLocale != null) {
-                Resources resources = getInstrumentation().getTargetContext().getResources();
-                DisplayMetrics displayMetrics = resources.getDisplayMetrics();
-                Configuration newConfiguration = new Configuration(resources.getConfiguration());
-                newConfiguration.locale = mOldLocale;
-                mOldLocale = null;
-                resources.updateConfiguration(newConfiguration, displayMetrics);
-            }
-
-            disablePrintServices();
-            // Make sure the spooler is cleaned.
-            clearPrintSpoolerData();
+        if (!supportsPrinting()) {
+            return;
         }
+
+        // Done with the activity.
+        getActivity().finish();
+        enableImes();
+
+        // Restore the locale if needed.
+        if (mOldLocale != null) {
+            Resources resources = getInstrumentation().getTargetContext().getResources();
+            DisplayMetrics displayMetrics = resources.getDisplayMetrics();
+            Configuration newConfiguration = new Configuration(resources.getConfiguration());
+            newConfiguration.locale = mOldLocale;
+            mOldLocale = null;
+            resources.updateConfiguration(newConfiguration, displayMetrics);
+        }
+
+        disablePrintServices();
+        // Make sure the spooler is cleaned.
+        clearPrintSpoolerData();
+
         super.tearDown();
     }
 
@@ -549,6 +560,7 @@
     }
 
     protected boolean supportsPrinting() {
-        return getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PRINTING);
+        return getInstrumentation().getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_PRINTING);
     }
 }
diff --git a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
index 9a93a60..b7caabb 100644
--- a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
@@ -16,6 +16,7 @@
 package android.telephony.cts;
 
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.net.ConnectivityManager;
 import android.telephony.CellInfo;
 import android.telephony.CellInfoGsm;
@@ -41,6 +42,7 @@
     // Maximum and minimum possible RSSI values(in dbm).
     private static final int MAX_RRSI = -10;
     private static final int MIN_RSSI = -150;
+    private PackageManager mPm;
 
     @Override
     protected void setUp() throws Exception {
@@ -48,9 +50,16 @@
         mTelephonyManager =
                 (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
         mCm = (ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+        mPm = getContext().getPackageManager();
     }
 
     public void testCellInfo() throws Throwable {
+
+        if(! (mPm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY))) {
+            Log.d(TAG, "Skipping test that requires FEATURE_TELEPHONY");
+            return;
+        }
+
         if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
             Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
             return;
diff --git a/tools/tradefed-host/.classpath b/tools/tradefed-host/.classpath
index e716219..dbeeb01 100644
--- a/tools/tradefed-host/.classpath
+++ b/tools/tradefed-host/.classpath
@@ -7,5 +7,6 @@
 	<classpathentry exported="true" kind="var" path="CTS_SRC_ROOT/out/host/common/obj/JAVA_LIBRARIES/ctsdeviceinfolib_intermediates/javalib.jar"/>
 	<classpathentry kind="var" path="CTS_SRC_ROOT/out/host/common/obj/JAVA_LIBRARIES/hosttestlib_intermediates/javalib.jar"/>
 	<classpathentry kind="var" path="CTS_SRC_ROOT/prebuilts/misc/common/tradefed/tradefed-prebuilt.jar"/>
+	<classpathentry combineaccessrules="false" kind="src" path="/cts-commonutil"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
index d74cce5..244f348 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
@@ -64,6 +64,7 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
@@ -251,6 +252,20 @@
         }
     }
 
+
+    /**
+     * A {@link Comparator} for sorting {@link TestPackage}s by running time hint.
+     */
+    static class RuntimeHintComparator implements Comparator<TestPackage> {
+
+        @Override
+        public int compare(TestPackage left, TestPackage right) {
+            return Long.compare(left.getPackageDef().getRuntimeHint(),
+                    right.getPackageDef().getRuntimeHint());
+        }
+
+    }
+
     /**
      * A {@link ResultForwarder} that will forward a bugreport on each failed test.
      */
@@ -811,6 +826,10 @@
             int numTestPackages = testPackageList.size();
             int totalShards = Math.min(mTotalShards, numTestPackages);
 
+            // Sort test packages by running time hint, to force packages with large expected
+            // running times to different shards if possible.
+            Collections.sort(testPackageList, new RuntimeHintComparator());
+
             List<TestPackage> shardTestPackageList = new ArrayList<>();
             for (int i = mShardAssignment; i < numTestPackages; i += totalShards) {
                 shardTestPackageList.add(testPackageList.get(i));
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
index 13f3572..630dee3 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
@@ -72,6 +72,11 @@
     public IAbi getAbi();
 
     /**
+     * @return the estimated running time of this test package.
+     */
+    public long getRuntimeHint();
+
+    /**
      * Set the filter to use for tests
      *
      * @param testFilter
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
index 12c3ddd..d08c0bc 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
@@ -66,6 +66,7 @@
     private String mRunTimeArgs = null;
     private String mTestPackageName = null;
     private String mDigest = null;
+    private long mRuntimeHint = 0;
     private IAbi mAbi = null;
     private List<ITargetPreparer> mPreparers = null;
 
@@ -137,6 +138,18 @@
      * {@inheritDoc}
      */
     @Override
+    public long getRuntimeHint() {
+        return mRuntimeHint;
+    }
+
+    void setRuntimeHint(long runtimeHint) {
+        mRuntimeHint = runtimeHint;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
     public String getName() {
         return mName;
     }
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
index 649dd9e..951c461 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
@@ -86,6 +86,10 @@
                 final String targetNameSpace = attributes.getValue("targetNameSpace");
                 final String runTimeArgs = attributes.getValue("runtimeArgs");
                 final String testType = getTestType(attributes);
+                long runTimeHint = 0;
+                if (attributes.getValue("runtimeHint") != null) {
+                    runTimeHint = Long.parseLong(attributes.getValue("runtimeHint"));
+                }
 
                 for (String abiName : AbiUtils.getAbisSupportedByCts()) {
                     Abi abi = new Abi(abiName, AbiUtils.getBitness(abiName));
@@ -102,6 +106,7 @@
                     }
                     packageDef.setTargetBinaryName(targetBinaryName);
                     packageDef.setTargetNameSpace(targetNameSpace);
+                    packageDef.setRuntimeHint(runTimeHint);
                     packageDef.setAbi(abi);
                     mPackageDefs.put(abiName, packageDef);
                 }