Merge "Add tests for AIDL union"
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/FreeformWindowingModeTests.java b/tests/framework/base/windowmanager/src/android/server/wm/FreeformWindowingModeTests.java
index 342c5b9..1567288 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/FreeformWindowingModeTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/FreeformWindowingModeTests.java
@@ -24,6 +24,7 @@
 import static android.server.wm.app.Components.NO_RELAUNCH_ACTIVITY;
 import static android.server.wm.app.Components.TEST_ACTIVITY;
 
+import static android.server.wm.app.Components.TestActivity.TEST_ACTIVITY_ACTION_FINISH_SELF;
 import static org.junit.Assert.assertEquals;
 
 import android.graphics.Rect;
@@ -82,15 +83,26 @@
 
     @Test
     public void testNonResizeableActivityHasFullDisplayBounds() throws Exception {
+        launchActivity(TEST_ACTIVITY);
+
+        mWmState.computeState(TEST_ACTIVITY);
+
+        final ActivityTask testActivityTask =
+                mWmState.getTaskByActivity(TEST_ACTIVITY);
+        Rect expectedBounds = testActivityTask.getBounds();
+        mBroadcastActionTrigger.doAction(TEST_ACTIVITY_ACTION_FINISH_SELF);
+        mWmState.waitFor((wmState) ->
+                        !wmState.containsActivity(TEST_ACTIVITY),
+                "Waiting for test activity to finish...");
+
         launchActivity(NON_RESIZEABLE_ACTIVITY, WINDOWING_MODE_FREEFORM);
 
         mWmState.computeState(NON_RESIZEABLE_ACTIVITY);
 
-        final ActivityTask task =
+        final ActivityTask nonResizeableActivityTask =
                 mWmState.getTaskByActivity(NON_RESIZEABLE_ACTIVITY);
-        final ActivityTask stack = mWmState.getRootTask(task.mRootTaskId);
 
-        if (task.isFullscreen()) {
+        if (nonResizeableActivityTask.isFullscreen()) {
             // If the task is on the fullscreen stack, then we know that it will have bounds that
             // fill the entire display.
             return;
@@ -98,8 +110,7 @@
 
         // If the task is not on the fullscreen stack, then compare the task bounds to the display
         // bounds.
-        assertEquals(mWmState.getDisplay(stack.mDisplayId).getDisplayRect(),
-                task.getBounds());
+        assertEquals(expectedBounds, nonResizeableActivityTask.getBounds());
     }
 
     @Test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
index 0fc4bc8..69b472e 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
@@ -33,6 +33,8 @@
 import org.junit.Before;
 import org.junit.Test;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+
 /**
  * Build/Install/Run:
  *     atest CtsWindowManagerDeviceTestCases:SplashscreenTests
@@ -59,9 +61,15 @@
         mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY);
         mWmState.getStableBounds();
         final Bitmap image = takeScreenshot();
+        int windowingMode = mWmState.getFocusedStackWindowingMode();
+        Rect appBounds = new Rect();
+        appBounds.set(windowingMode == WINDOWING_MODE_FULLSCREEN ?
+                mWmState.getStableBounds() :
+                mWmState.findFirstWindowWithType(
+                        WindowManagerState.WindowState.WINDOW_TYPE_STARTING).getContentInsets());
         // Use ratios to flexibly accomodate circular or not quite rectangular displays
         // Note: Color.BLACK is the pixel color outside of the display region
-        assertColors(image, mWmState.getStableBounds(),
+        assertColors(image, appBounds,
             Color.RED, 0.50f, Color.BLACK, 0.02f);
     }
 
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
index 23c15b4..c49d1fb 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerState.java
@@ -1512,7 +1512,7 @@
     public static class WindowState extends WindowContainer {
 
         private static final int WINDOW_TYPE_NORMAL = 0;
-        private static final int WINDOW_TYPE_STARTING = 1;
+        public static final int WINDOW_TYPE_STARTING = 1;
         private static final int WINDOW_TYPE_EXITING = 2;
         private static final int WINDOW_TYPE_DEBUGGER = 3;
 
diff --git a/tests/inputmethod/AndroidTest.xml b/tests/inputmethod/AndroidTest.xml
index fd2ea5d..7419606 100644
--- a/tests/inputmethod/AndroidTest.xml
+++ b/tests/inputmethod/AndroidTest.xml
@@ -70,6 +70,11 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsInputMethodTestCases.apk" />
     </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+      <!-- Disable hidden API checking, see b/166236554 -->
+        <option name="run-command" value="settings put global hidden_api_policy 1" />
+        <option name="teardown-command" value="settings delete global hidden_api_policy" />
+    </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.view.inputmethod.cts" />
         <option name="runtime-hint" value="1m0s" />
diff --git a/tests/media/jni/NativeCodecDecoderTest.cpp b/tests/media/jni/NativeCodecDecoderTest.cpp
index 0c9638e..754ccb3 100644
--- a/tests/media/jni/NativeCodecDecoderTest.cpp
+++ b/tests/media/jni/NativeCodecDecoderTest.cpp
@@ -210,7 +210,8 @@
         }
         CHECK_STATUS(AMediaCodec_queueInputBuffer(mCodec, bufferIndex, 0, size, pts, flags),
                      "AMediaCodec_queueInputBuffer failed");
-        ALOGV("input: id: %zu  size: %zu  pts: %d  flags: %d", bufferIndex, size, (int)pts, flags);
+        ALOGV("input: id: %zu  size: %zu  pts: %" PRId64 "  flags: %d", bufferIndex, size, pts,
+              flags);
         if (size > 0) {
             mOutputBuff->saveInPTS(pts);
             mInputCount++;
@@ -233,8 +234,8 @@
         mOutputBuff->saveOutPTS(info->presentationTimeUs);
         mOutputCount++;
     }
-    ALOGV("output: id: %zu  size: %d  pts: %d  flags: %d", bufferIndex, info->size,
-          (int)info->presentationTimeUs, info->flags);
+    ALOGV("output: id: %zu  size: %d  pts: %" PRId64 "  flags: %d", bufferIndex, info->size,
+          info->presentationTimeUs, info->flags);
     CHECK_STATUS(AMediaCodec_releaseOutputBuffer(mCodec, bufferIndex, mWindow != nullptr),
                  "AMediaCodec_releaseOutputBuffer failed");
     return !hasSeenError();
@@ -257,7 +258,7 @@
             if (bufferIndex >= 0) {
                 isOk = enqueueCodecConfig(bufferIndex);
             } else {
-                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", (int)bufferIndex);
+                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", bufferIndex);
                 return false;
             }
         }
diff --git a/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp b/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp
index 2c76eb1..bcf6ef1 100644
--- a/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp
+++ b/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp
@@ -243,7 +243,8 @@
         }
         CHECK_STATUS(AMediaCodec_queueInputBuffer(mDecoder, bufferIndex, 0, size, pts, flags),
                      "AMediaCodec_queueInputBuffer failed");
-        ALOGV("input: id: %zu  size: %zu  pts: %d  flags: %d", bufferIndex, size, (int)pts, flags);
+        ALOGV("input: id: %zu  size: %zu  pts: %" PRId64 "  flags: %d", bufferIndex, size, pts,
+              flags);
         if (size > 0) {
             mOutputBuff->saveInPTS(pts);
             mDecInputCount++;
@@ -260,8 +261,8 @@
     if (bufferInfo->size > 0 && (bufferInfo->flags & AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG) == 0) {
         mDecOutputCount++;
     }
-    ALOGV("output: id: %zu  size: %d  pts: %d  flags: %d", bufferIndex, bufferInfo->size,
-          (int)bufferInfo->presentationTimeUs, bufferInfo->flags);
+    ALOGV("output: id: %zu  size: %d  pts: %" PRId64 "  flags: %d", bufferIndex, bufferInfo->size,
+          bufferInfo->presentationTimeUs, bufferInfo->flags);
     CHECK_STATUS(AMediaCodec_releaseOutputBuffer(mDecoder, bufferIndex, mWindow != nullptr),
                  "AMediaCodec_releaseOutputBuffer failed");
     return !hasSeenError();
@@ -291,8 +292,8 @@
             mEncOutputCount++;
         }
     }
-    ALOGV("output: id: %zu  size: %d  pts: %d  flags: %d", bufferIndex, info->size,
-          (int)info->presentationTimeUs, info->flags);
+    ALOGV("output: id: %zu  size: %d  pts: %" PRId64 "  flags: %d", bufferIndex, info->size,
+          info->presentationTimeUs, info->flags);
     CHECK_STATUS(AMediaCodec_releaseOutputBuffer(mEncoder, bufferIndex, false),
                  "AMediaCodec_releaseOutputBuffer failed");
     return !hasSeenError();
@@ -316,7 +317,7 @@
             } else if (bufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else if (bufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
-                ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", (int)bufferID);
+                ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", bufferID);
                 return false;
             }
         }
@@ -352,7 +353,7 @@
                 if (!enqueueDecoderEOS(bufferIndex)) return false;
             } else {
                 ALOGE("unexpected return value from *_dequeueInputBufferBuffer: %d",
-                      (int)bufferIndex);
+                      bufferIndex);
                 return false;
             }
         }
@@ -383,7 +384,7 @@
                 } else if (oBufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
                 } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
                 } else {
-                    ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", (int)oBufferID);
+                    ALOGE("unexpected return value from *_dequeueOutputBuffer: %zd", oBufferID);
                     return false;
                 }
             }
@@ -431,7 +432,7 @@
             } else if (oBufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
-                ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", (int)oBufferID);
+                ALOGE("unexpected return value from *_dequeueOutputBuffer: %zd", oBufferID);
                 return false;
             }
             ssize_t iBufferId = AMediaCodec_dequeueInputBuffer(mDecoder, kQDeQTimeOutUs);
@@ -440,7 +441,7 @@
                 frameCnt++;
             } else if (iBufferId == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else {
-                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", (int)iBufferId);
+                ALOGE("unexpected return value from *_dequeueInputBuffer: %zd", iBufferId);
                 return false;
             }
             if (mSawDecOutputEOS) AMediaCodec_signalEndOfInputStream(mEncoder);
diff --git a/tests/media/jni/NativeCodecEncoderTest.cpp b/tests/media/jni/NativeCodecEncoderTest.cpp
index 6748c31..8d16699 100644
--- a/tests/media/jni/NativeCodecEncoderTest.cpp
+++ b/tests/media/jni/NativeCodecEncoderTest.cpp
@@ -308,7 +308,8 @@
         }
         CHECK_STATUS(AMediaCodec_queueInputBuffer(mCodec, bufferIndex, 0, size, pts, flags),
                      "AMediaCodec_queueInputBuffer failed");
-        ALOGV("input: id: %zu  size: %d  pts: %d  flags: %d", bufferIndex, size, (int)pts, flags);
+        ALOGV("input: id: %zu  size: %d  pts: %" PRId64 "  flags: %d", bufferIndex, size, pts,
+              flags);
         mOutputBuff->saveInPTS(pts);
         mInputCount++;
     }
@@ -334,8 +335,8 @@
             mOutputCount++;
         }
     }
-    ALOGV("output: id: %zu  size: %d  pts: %d  flags: %d", bufferIndex, info->size,
-          (int)info->presentationTimeUs, info->flags);
+    ALOGV("output: id: %zu  size: %d  pts: %" PRId64 "  flags: %d", bufferIndex, info->size,
+          info->presentationTimeUs, info->flags);
     CHECK_STATUS(AMediaCodec_releaseOutputBuffer(mCodec, bufferIndex, false),
                  "AMediaCodec_releaseOutputBuffer failed");
     return !hasSeenError();
diff --git a/tests/media/jni/NativeCodecTestBase.cpp b/tests/media/jni/NativeCodecTestBase.cpp
index f5a0c21..4e13e9c 100644
--- a/tests/media/jni/NativeCodecTestBase.cpp
+++ b/tests/media/jni/NativeCodecTestBase.cpp
@@ -194,8 +194,9 @@
         if (lastPts < *it1) {
             lastPts = *it1;
         } else {
-            ALOGE("Timestamp ordering check failed: last timestamp: %d / current timestamp: %d",
-                  (int)lastPts, (int)*it1);
+            ALOGE("Timestamp ordering check failed: last timestamp: %" PRId64
+                  " / current timestamp: %" PRId64 "",
+                  lastPts, *it1);
             result = false;
             break;
         }
@@ -212,14 +213,15 @@
     if (outPtsArray != inpPtsArray) {
         if (outPtsArray.size() != inpPtsArray.size()) {
             ALOGE("input and output presentation timestamp list sizes are not identical sizes "
-                  "exp/rec %d/%d", (int)inpPtsArray.size(), (int)outPtsArray.size());
+                  "exp/rec %zu/%zu", inpPtsArray.size(), outPtsArray.size());
             isEqual = false;
         } else {
             int count = 0;
             for (auto it1 = outPtsArray.cbegin(), it2 = inpPtsArray.cbegin();
                  it1 < outPtsArray.cend(); it1++, it2++) {
                 if (*it1 != *it2) {
-                    ALOGE("input output pts mismatch, exp/rec %d/%d", (int)*it2, (int)*it1);
+                    ALOGE("input output pts mismatch, exp/rec %" PRId64 "/%" PRId64 "",
+                          *it2, *it1);
                     count++;
                 }
                 if (count == 20) {
@@ -237,15 +239,15 @@
     if (this == that) return true;
     if (outPtsArray != that->outPtsArray) {
         if (outPtsArray.size() != that->outPtsArray.size()) {
-            ALOGE("ref and test outputs presentation timestamp arrays are of unequal sizes %d, %d",
-                  (int)outPtsArray.size(), (int)that->outPtsArray.size());
+            ALOGE("ref and test outputs presentation timestamp arrays are of unequal sizes "
+                  "%zu, %zu", outPtsArray.size(), that->outPtsArray.size());
             return false;
         } else {
             int count = 0;
             for (auto it1 = outPtsArray.cbegin(), it2 = that->outPtsArray.cbegin();
                  it1 < outPtsArray.cend(); it1++, it2++) {
                 if (*it1 != *it2) {
-                    ALOGE("presentation timestamp exp/rec %d/%d", (int)*it1, (int)*it2);
+                    ALOGE("presentation timestamp exp/rec %" PRId64 "/%" PRId64 "", *it1, *it2);
                     count++;
                 }
                 if (count == 20) {
@@ -259,14 +261,14 @@
     if (crc32value != that->crc32value) {
         ALOGE("ref and test outputs checksum do not match %lu, %lu", crc32value, that->crc32value);
         if (memory.size() != that->memory.size()) {
-            ALOGE("ref and test outputs decoded buffer are of unequal sizes %d, %d",
-                  (int)memory.size(), (int)that->memory.size());
+            ALOGE("ref and test outputs decoded buffer are of unequal sizes %zu, %zu",
+                  memory.size(), that->memory.size());
         } else {
             int count = 0;
             for (auto it1 = memory.cbegin(), it2 = that->memory.cbegin(); it1 < memory.cend();
                  it1++, it2++) {
                 if (*it1 != *it2) {
-                    ALOGE("decoded sample exp/rec %d/%d", (int)*it1, (int)*it2);
+                    ALOGE("decoded sample exp/rec %d/%d", *it1, *it2);
                     count++;
                 }
                 if (count == 20) {
@@ -414,7 +416,7 @@
             } else if (oBufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
-                ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", (int)oBufferID);
+                ALOGE("unexpected return value from *_dequeueOutputBuffer: %zd", oBufferID);
                 return false;
             }
             ssize_t iBufferId = AMediaCodec_dequeueInputBuffer(mCodec, kQDeQTimeOutUs);
@@ -423,7 +425,7 @@
                 frameCnt++;
             } else if (iBufferId == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else {
-                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", (int)iBufferId);
+                ALOGE("unexpected return value from *_dequeueInputBuffer: %zd", iBufferId);
                 return false;
             }
         }
@@ -446,7 +448,7 @@
             if (bufferIndex >= 0) {
                 isOk = enqueueEOS(bufferIndex);
             } else {
-                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", (int)bufferIndex);
+                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", bufferIndex);
                 return false;
             }
         }
@@ -479,7 +481,7 @@
             } else if (bufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else if (bufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
-                ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", (int)bufferID);
+                ALOGE("unexpected return value from *_dequeueOutputBuffer: %d", bufferID);
                 return false;
             }
         }
diff --git a/tests/media/jni/NativeCodecUnitTest.cpp b/tests/media/jni/NativeCodecUnitTest.cpp
index 3709172..724bf7b 100644
--- a/tests/media/jni/NativeCodecUnitTest.cpp
+++ b/tests/media/jni/NativeCodecUnitTest.cpp
@@ -1191,8 +1191,8 @@
         } else {
             if (AMEDIA_OK == AMediaCodec_queueInputBuffer(mCodec, 0, 0, bufSize + 100, 0,
                                                           AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM)) {
-                ALOGE("queueInputBuffer succeeds for bad size %d, buffer capacity %d, ",
-                      (int)bufSize + 100, (int)bufSize);
+                ALOGE("queueInputBuffer succeeds for bad size %zu, buffer capacity %zu ",
+                      bufSize + 100, bufSize);
                 return false;
             }
         }
diff --git a/tests/media/jni/NativeExtractorTest.cpp b/tests/media/jni/NativeExtractorTest.cpp
index 016a188..2c41bb0 100644
--- a/tests/media/jni/NativeExtractorTest.cpp
+++ b/tests/media/jni/NativeExtractorTest.cpp
@@ -96,8 +96,8 @@
                     ALOGD(" Mime: %s mismatch for sample: %d", refMime, frameCount);
                     ALOGD(" flags exp/got: %d / %d", refSampleInfo.flags, testSampleInfo.flags);
                     ALOGD(" size exp/got: %d / %d ", refSampleInfo.size, testSampleInfo.size);
-                    ALOGD(" ts exp/got: %d / %d ", (int)refSampleInfo.presentationTimeUs,
-                          (int)testSampleInfo.presentationTimeUs);
+                    ALOGD(" ts exp/got: %" PRId64 " / %" PRId64 "",
+                          refSampleInfo.presentationTimeUs, testSampleInfo.presentationTimeUs);
                     areTracksIdentical = false;
                     break;
                 }
@@ -152,9 +152,9 @@
                     areTracksIdentical = false;
                     break;
                 }
-                ALOGV("Mime: %s Sample: %d flags: %d size: %d ts: %d", refMime, frameCount,
-                      refSampleInfo.flags, refSampleInfo.size,
-                      (int)refSampleInfo.presentationTimeUs);
+                ALOGV("Mime: %s Sample: %d flags: %d size: %d ts: % " PRId64 "", refMime,
+                      frameCount, refSampleInfo.flags, refSampleInfo.size,
+                      refSampleInfo.presentationTimeUs);
                 if (!haveRefSamples || frameCount >= sampleLimit) {
                     break;
                 }
@@ -402,8 +402,8 @@
             if (!isSampleInfoIdentical(&arg->mExpected, &received)) {
                 ALOGE(" flags exp/got: %d / %d", arg->mExpected.flags, received.flags);
                 ALOGE(" size exp/got: %d / %d ", arg->mExpected.size, received.size);
-                ALOGE(" ts exp/got: %d / %d ", (int)arg->mExpected.presentationTimeUs,
-                      (int)received.presentationTimeUs);
+                ALOGE(" ts exp/got: %" PRId64 " / %" PRId64 "", arg->mExpected.presentationTimeUs,
+                      received.presentationTimeUs);
                 errCnt++;
             }
         }
@@ -460,8 +460,8 @@
                 if (!result) {
                     ALOGE(" flags exp/got: %d / %d", refSampleInfo.flags, testSampleInfo.flags);
                     ALOGE(" size exp/got: %d / %d ", refSampleInfo.size, testSampleInfo.size);
-                    ALOGE(" ts exp/got: %d / %d ", (int)refSampleInfo.presentationTimeUs,
-                          (int)testSampleInfo.presentationTimeUs);
+                    ALOGE(" ts exp/got: %" PRId64 " / %" PRId64 "",
+                          refSampleInfo.presentationTimeUs, testSampleInfo.presentationTimeUs);
                 }
                 int refTrackIdx = AMediaExtractor_getSampleTrackIndex(refExtractor);
                 int testTrackIdx = AMediaExtractor_getSampleTrackIndex(testExtractor);
@@ -632,8 +632,8 @@
         std::shuffle(seekTestArgs.begin(), seekTestArgs.end(), std::default_random_engine(kSeed));
         int seekAccErrCnt = checkSeekPoints(csrcPath, cmime, seekTestArgs);
         if (seekAccErrCnt != 0) {
-            ALOGE("For %s seek chose inaccurate Sync point in: %d / %d", csrcPath, seekAccErrCnt,
-                  (int)seekTestArgs.size());
+            ALOGE("For %s seek chose inaccurate Sync point in: %d / %zu", csrcPath, seekAccErrCnt,
+                  seekTestArgs.size());
             isPass = false;
         } else {
             isPass = true;
@@ -705,8 +705,8 @@
                     ALOGE("seen mismatch seekTo(0, SEEK_TO_CLOSEST_SYNC)");
                     ALOGE(" flags exp/got: %d / %d", sampleInfoAtZero.flags, currInfo.flags);
                     ALOGE(" size exp/got: %d / %d ", sampleInfoAtZero.size, currInfo.size);
-                    ALOGE(" ts exp/got: %d / %d ", (int)sampleInfoAtZero.presentationTimeUs,
-                          (int)currInfo.presentationTimeUs);
+                    ALOGE(" ts exp/got: %" PRId64 " / %" PRId64 " ",
+                          sampleInfoAtZero.presentationTimeUs, currInfo.presentationTimeUs);
                     AMediaFormat_delete(format);
                     break;
                 }
@@ -717,8 +717,8 @@
                     ALOGE("seen mismatch seekTo(-1, SEEK_TO_CLOSEST_SYNC)");
                     ALOGE(" flags exp/got: %d / %d", sampleInfoAtZero.flags, currInfo.flags);
                     ALOGE(" size exp/got: %d / %d ", sampleInfoAtZero.size, currInfo.size);
-                    ALOGE(" ts exp/got: %d / %d ", (int)sampleInfoAtZero.presentationTimeUs,
-                          (int)currInfo.presentationTimeUs);
+                    ALOGE(" ts exp/got: %" PRId64 " / %" PRId64 "",
+                          sampleInfoAtZero.presentationTimeUs, currInfo.presentationTimeUs);
                     AMediaFormat_delete(format);
                     break;
                 }
diff --git a/tests/media/jni/NativeMediaCommon.h b/tests/media/jni/NativeMediaCommon.h
index ec5721c..b74eb17 100644
--- a/tests/media/jni/NativeMediaCommon.h
+++ b/tests/media/jni/NativeMediaCommon.h
@@ -17,6 +17,7 @@
 #ifndef MEDIACTSNATIVE_NATIVE_MEDIA_COMMON_H
 #define MEDIACTSNATIVE_NATIVE_MEDIA_COMMON_H
 
+#include <inttypes.h>
 #include <NdkMediaFormat.h>
 
 extern const char* AMEDIA_MIMETYPE_VIDEO_VP8;
diff --git a/tests/media/jni/NativeMuxerTest.cpp b/tests/media/jni/NativeMuxerTest.cpp
index 14b8584..cea162c7 100644
--- a/tests/media/jni/NativeMuxerTest.cpp
+++ b/tests/media/jni/NativeMuxerTest.cpp
@@ -205,11 +205,11 @@
             delete[] frameCount;
             return false;
         }
-        ALOGV("Track: %d Timestamp: %d", trackID, (int)info->presentationTimeUs);
+        ALOGV("Track: %d Timestamp: %" PRId64 "", trackID, info->presentationTimeUs);
         frameCount[index]++;
     }
     delete[] frameCount;
-    ALOGV("Total track samples %d", (int)mTrackIdxOrder.size());
+    ALOGV("Total track samples %zu", mTrackIdxOrder.size());
     return true;
 }
 
@@ -250,8 +250,8 @@
                                                     info) != AMEDIA_OK) {
                         return false;
                     }
-                    ALOGV("Track: %d Timestamp: %d", outIndexMap[idx],
-                          (int)info->presentationTimeUs);
+                    ALOGV("Track: %d Timestamp: %" PRId64 "", outIndexMap[idx],
+                          info->presentationTimeUs);
                 }
                 idx++;
             }
diff --git a/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java b/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java
index f1bc130..be0daae 100644
--- a/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java
+++ b/tests/tests/net/util/java/android/net/cts/util/CtsNetUtils.java
@@ -23,10 +23,11 @@
 import static android.net.NetworkCapabilities.TRANSPORT_TEST;
 import static android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION;
 
-import static com.android.compatibility.common.util.ShellIdentityUtils.invokeWithShellPermissions;
+import static com.android.testutils.TestPermissionUtil.runAsShell;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -71,7 +72,6 @@
 import java.net.Socket;
 import java.util.Arrays;
 import java.util.List;
-import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutionException;
@@ -219,13 +219,18 @@
             if (config == null) {
                 // TODO: this may not clear the BSSID blacklist, as opposed to
                 // mWifiManager.connect(config)
-                SystemUtil.runWithShellPermissionIdentity(() -> mWifiManager.reconnect(),
-                        NETWORK_SETTINGS);
+                assertTrue("Error reconnecting wifi", runAsShell(NETWORK_SETTINGS,
+                        mWifiManager::reconnect));
             } else {
                 // When running CTS, devices are expected to have wifi networks pre-configured.
                 // This condition is only hit on virtual devices.
-                SystemUtil.runWithShellPermissionIdentity(
-                        () -> mWifiManager.connect(config, null /* listener */), NETWORK_SETTINGS);
+                final Integer error = runAsShell(NETWORK_SETTINGS, () -> {
+                    final ConnectWifiListener listener = new ConnectWifiListener();
+                    mWifiManager.connect(config, listener);
+                    return listener.connectFuture.get(
+                            CONNECTIVITY_CHANGE_TIMEOUT_SECS, TimeUnit.SECONDS);
+                });
+                assertNull("Error connecting to wifi: " + error, error);
             }
             // Ensure we get an onAvailable callback and possibly a CONNECTIVITY_ACTION.
             wifiNetwork = callback.waitForAvailable();
@@ -242,8 +247,24 @@
         return wifiNetwork;
     }
 
+    private static class ConnectWifiListener implements WifiManager.ActionListener {
+        /**
+         * Future completed when the connect process ends. Provides the error code or null if none.
+         */
+        final CompletableFuture<Integer> connectFuture = new CompletableFuture<>();
+        @Override
+        public void onSuccess() {
+            connectFuture.complete(null);
+        }
+
+        @Override
+        public void onFailure(int reason) {
+            connectFuture.complete(reason);
+        }
+    }
+
     private WifiConfiguration maybeAddVirtualWifiConfiguration() {
-        final List<WifiConfiguration> configs = invokeWithShellPermissions(
+        final List<WifiConfiguration> configs = runAsShell(NETWORK_SETTINGS,
                 mWifiManager::getConfiguredNetworks);
         // If no network is configured, add a config for virtual access points if applicable
         if (configs.size() == 0) {
@@ -259,7 +280,7 @@
 
     private List<ScanResult> getWifiScanResults() {
         final CompletableFuture<List<ScanResult>> scanResultsFuture = new CompletableFuture<>();
-        SystemUtil.runWithShellPermissionIdentity(() -> {
+        runAsShell(NETWORK_SETTINGS, () -> {
             final BroadcastReceiver receiver = new BroadcastReceiver() {
                 @Override
                 public void onReceive(Context context, Intent intent) {
@@ -296,7 +317,7 @@
         virtualConfig.SSID = "\"" + virtualScanResult.SSID + "\"";
         virtualConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
 
-        SystemUtil.runWithShellPermissionIdentity(() -> {
+        runAsShell(NETWORK_SETTINGS, () -> {
             final int networkId = mWifiManager.addNetwork(virtualConfig);
             assertTrue(networkId >= 0);
             assertTrue(mWifiManager.enableNetwork(networkId, false /* attemptConnect */));
@@ -310,7 +331,7 @@
      * to them.
      */
     private void clearWifiBlacklist() {
-        SystemUtil.runWithShellPermissionIdentity(() -> {
+        runAsShell(NETWORK_SETTINGS, () -> {
             for (WifiConfiguration cfg : mWifiManager.getConfiguredNetworks()) {
                 assertTrue(mWifiManager.enableNetwork(cfg.networkId, false /* attemptConnect */));
             }
diff --git a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
index d0cb113..459ff27 100644
--- a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
+++ b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
@@ -61,9 +61,11 @@
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import java.util.Objects;
 import java.util.Random;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 
@@ -125,6 +127,9 @@
         List<Pair<Integer, String>> mCallStates = new ArrayList<>();
         EmergencyNumber mLastOutgoingEmergencyNumber;
 
+        LinkedBlockingQueue<Map<Integer, List<EmergencyNumber>>> mEmergencyNumberListQueue =
+               new LinkedBlockingQueue<>(2);
+
         @Override
         public void onCallStateChanged(int state, String number) {
             Log.i(TAG, "onCallStateChanged: state=" + state + ", number=" + number);
@@ -133,11 +138,24 @@
         }
 
         @Override
-        public void onOutgoingEmergencyCall(EmergencyNumber emergencyNumber) {
+        public void onOutgoingEmergencyCall(EmergencyNumber emergencyNumber, int subscriptionId) {
             Log.i(TAG, "onOutgoingEmergencyCall: emergencyNumber=" + emergencyNumber);
             mLastOutgoingEmergencyNumber = emergencyNumber;
             mCallbackSemaphore.release();
         }
+
+        @Override
+        public void onEmergencyNumberListChanged(
+                Map<Integer, List<EmergencyNumber>> emergencyNumberList) {
+            Log.i(TAG, "onEmergencyNumberChanged, total size=" + emergencyNumberList.values()
+                    .stream().mapToInt(List::size).sum());
+            mEmergencyNumberListQueue.offer(emergencyNumberList);
+        }
+
+        public Map<Integer, List<EmergencyNumber>> waitForEmergencyNumberListUpdate(
+                long timeoutMillis) throws Throwable {
+            return mEmergencyNumberListQueue.poll(timeoutMillis, TimeUnit.MILLISECONDS);
+        }
     }
 
     boolean mShouldTestTelecom = true;
@@ -176,8 +194,9 @@
                 mPhoneStateListener = new TestPhoneStateListener();
                 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
                     (tm) -> tm.listen(mPhoneStateListener,
-                        PhoneStateListener.LISTEN_CALL_STATE | PhoneStateListener
-                            .LISTEN_OUTGOING_EMERGENCY_CALL));
+                        PhoneStateListener.LISTEN_CALL_STATE
+                                | PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_CALL
+                                | PhoneStateListener.LISTEN_EMERGENCY_NUMBER_LIST));
                 registeredLatch.countDown();
             }
         });
diff --git a/tests/tests/telecom/src/android/telecom/cts/OutgoingCallTest.java b/tests/tests/telecom/src/android/telecom/cts/OutgoingCallTest.java
index 0c5b3d3..5a75fbc 100644
--- a/tests/tests/telecom/src/android/telecom/cts/OutgoingCallTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/OutgoingCallTest.java
@@ -29,9 +29,13 @@
 import android.telecom.TelecomManager;
 import android.telephony.PhoneStateListener;
 import android.telephony.TelephonyManager;
+import android.telephony.emergency.EmergencyNumber;
 
 import com.android.compatibility.common.util.SystemUtil;
 
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 import java.util.concurrent.TimeUnit;
@@ -118,14 +122,45 @@
         assertNotAudioRoute(mInCallCallbacks.getService(), CallAudioState.ROUTE_SPEAKER);
     }
 
-    public void testPhoneStateListenerInvokedOnOutgoingEmergencyCall() throws Exception {
+    public void testPhoneStateListenerInvokedOnOutgoingEmergencyCall() throws Throwable {
         if (!mShouldTestTelecom) {
             return;
         }
         TestUtils.setSystemDialerOverride(getInstrumentation());
+        TestUtils.setTestEmergencyPhoneAccountPackageFilter(getInstrumentation(), mContext);
         TestUtils.addTestEmergencyNumber(getInstrumentation(), TEST_EMERGENCY_NUMBER);
-        mTelecomManager.placeCall(Uri.fromParts("tel", TEST_EMERGENCY_NUMBER, null), null);
-        verifyPhoneStateListenerCallbacksForEmergencyCall(TEST_EMERGENCY_NUMBER);
+        Map<Integer, List<EmergencyNumber>> emergencyNumbers = null;
+
+        for (int i = 0; i < 5; i++) {
+            emergencyNumbers = mPhoneStateListener.waitForEmergencyNumberListUpdate(
+                    TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+            assertNotNull("Never got an update that the test emergency number was registered",
+                    emergencyNumbers);
+            if (doesEmergencyNumberListContainTestNumber(emergencyNumbers)) {
+                break;
+            }
+        }
+        assertTrue("Emergency number list from telephony still doesn't have the test number",
+                doesEmergencyNumberListContainTestNumber(emergencyNumbers));
+
+        try {
+            Bundle extras = new Bundle();
+            extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
+                    TestUtils.TEST_PHONE_ACCOUNT_HANDLE);
+            mTelecomManager.placeCall(Uri.fromParts("tel", TEST_EMERGENCY_NUMBER, null), extras);
+
+            verifyPhoneStateListenerCallbacksForEmergencyCall(TEST_EMERGENCY_NUMBER);
+        } finally {
+            TestUtils.removeTestEmergencyNumber(getInstrumentation(), TEST_EMERGENCY_NUMBER);
+            TestUtils.clearTestEmergencyPhoneAccountPackageFilter(getInstrumentation());
+        }
+    }
+
+    private boolean doesEmergencyNumberListContainTestNumber(
+            Map<Integer, List<EmergencyNumber>> emergencyNumbers) {
+        return emergencyNumbers.values().stream().flatMap(List::stream)
+                .anyMatch(numberObj ->
+                        Objects.equals(numberObj.getNumber(), TEST_EMERGENCY_NUMBER));
     }
 
     public void testPhoneStateListenerInvokedOnOutgoingCall() throws Exception {
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/DataCallResponseTest.java b/tests/tests/telephony/current/src/android/telephony/cts/DataCallResponseTest.java
index 1ec1c81..96985cd 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/DataCallResponseTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/DataCallResponseTest.java
@@ -16,6 +16,9 @@
 
 package android.telephony.cts;
 
+import static android.telephony.data.DataCallResponse.HANDOVER_FAILURE_MODE_DO_FALLBACK;
+import static android.telephony.data.DataCallResponse.HANDOVER_FAILURE_MODE_LEGACY;
+
 import static com.google.common.truth.Truth.assertThat;
 
 import android.net.InetAddresses;
@@ -47,6 +50,7 @@
             Arrays.asList(InetAddresses.parseNumericAddress("22.33.44.55"));
     private static final int MTU_V4 = 1440;
     private static final int MTU_V6 = 1400;
+    private static final int HANDOVER_FAILURE_MODE = HANDOVER_FAILURE_MODE_DO_FALLBACK;
 
     @Test
     public void testConstructorAndGetters() {
@@ -63,6 +67,7 @@
                 .setPcscfAddresses(PCSCFS)
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
+                .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
                 .build();
 
         assertThat(response.getCause()).isEqualTo(CAUSE);
@@ -77,6 +82,7 @@
         assertThat(response.getPcscfAddresses()).isEqualTo(PCSCFS);
         assertThat(response.getMtuV4()).isEqualTo(MTU_V4);
         assertThat(response.getMtuV6()).isEqualTo(MTU_V6);
+        assertThat(response.getHandoverFailureMode()).isEqualTo(HANDOVER_FAILURE_MODE_DO_FALLBACK);
     }
 
     @Test
@@ -94,6 +100,7 @@
                 .setPcscfAddresses(PCSCFS)
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
+                .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
                 .build();
 
         DataCallResponse equalsResponse = new DataCallResponse.Builder()
@@ -109,6 +116,7 @@
                 .setPcscfAddresses(PCSCFS)
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
+                .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
                 .build();
 
         assertThat(response).isEqualTo(equalsResponse);
@@ -129,6 +137,7 @@
                 .setPcscfAddresses(PCSCFS)
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
+                .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
                 .build();
 
         DataCallResponse notEqualsResponse = new DataCallResponse.Builder()
@@ -144,6 +153,7 @@
                 .setPcscfAddresses(PCSCFS)
                 .setMtuV4(1441)
                 .setMtuV6(1440)
+                .setHandoverFailureMode(HANDOVER_FAILURE_MODE_LEGACY)
                 .build();
 
         assertThat(response).isNotEqualTo(notEqualsResponse);
@@ -166,6 +176,7 @@
                 .setPcscfAddresses(PCSCFS)
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
+                .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
                 .build();
 
         Parcel stateParcel = Parcel.obtain();
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
index c1b67c1..926b32c 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
@@ -22,6 +22,7 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -52,6 +53,7 @@
 import android.telephony.Annotation.RadioPowerState;
 import android.telephony.AvailableNetworkInfo;
 import android.telephony.CallAttributes;
+import android.telephony.CallForwardingInfo;
 import android.telephony.CallQuality;
 import android.telephony.CarrierConfigManager;
 import android.telephony.CellLocation;
@@ -95,8 +97,10 @@
 import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Consumer;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
@@ -123,6 +127,7 @@
     private String mSelfCertHash;
 
     private static final int TOLERANCE = 1000;
+    private static final int TIMEOUT_FOR_NETWORK_OPS = TOLERANCE * 10;
     private PhoneStateListener mListener;
     private static ConnectivityManager mCm;
     private static final String TAG = "TelephonyManagerTest";
@@ -566,12 +571,12 @@
                 TelephonyManager::getAndUpdateDefaultRespondViaMessageApplication);
     }
 
-    /**
-     * Due to the corresponding API is hidden in R and will be public in S, this test
-     * is commented and will be un-commented in Android S.
-     *
     @Test
-    public void testGetCallForwarding() {
+    public void testGetCallForwarding() throws Exception {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
         List<Integer> callForwardingReasons = new ArrayList<>();
         callForwardingReasons.add(CallForwardingInfo.REASON_UNCONDITIONAL);
         callForwardingReasons.add(CallForwardingInfo.REASON_BUSY);
@@ -580,35 +585,61 @@
         callForwardingReasons.add(CallForwardingInfo.REASON_ALL);
         callForwardingReasons.add(CallForwardingInfo.REASON_ALL_CONDITIONAL);
 
-        Set<Integer> callForwardingStatus = new HashSet<Integer>();
-        callForwardingStatus.add(CallForwardingInfo.STATUS_INACTIVE);
-        callForwardingStatus.add(CallForwardingInfo.STATUS_ACTIVE);
-        callForwardingStatus.add(CallForwardingInfo.STATUS_FDN_CHECK_FAILURE);
-        callForwardingStatus.add(CallForwardingInfo.STATUS_UNKNOWN_ERROR);
-        callForwardingStatus.add(CallForwardingInfo.STATUS_NOT_SUPPORTED);
+        Set<Integer> callForwardingErrors = new HashSet<Integer>();
+        callForwardingErrors.add(TelephonyManager.CallForwardingInfoCallback
+                .RESULT_ERROR_FDN_CHECK_FAILURE);
+        callForwardingErrors.add(TelephonyManager.CallForwardingInfoCallback.RESULT_ERROR_UNKNOWN);
+        callForwardingErrors.add(TelephonyManager.CallForwardingInfoCallback
+                .RESULT_ERROR_NOT_SUPPORTED);
 
         for (int callForwardingReasonToGet : callForwardingReasons) {
             Log.d(TAG, "[testGetCallForwarding] callForwardingReasonToGet: "
                     + callForwardingReasonToGet);
-            CallForwardingInfo callForwardingInfo =
-                    ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
-                            (tm) -> tm.getCallForwarding(callForwardingReasonToGet));
+            AtomicReference<CallForwardingInfo> receivedForwardingInfo = new AtomicReference<>();
+            AtomicReference<Integer> receivedErrorCode = new AtomicReference<>();
+            CountDownLatch latch = new CountDownLatch(1);
+            TelephonyManager.CallForwardingInfoCallback callback =
+                    new TelephonyManager.CallForwardingInfoCallback() {
+                        @Override
+                        public void onCallForwardingInfoAvailable(CallForwardingInfo info) {
+                            receivedForwardingInfo.set(info);
+                            latch.countDown();
+                        }
 
-            assertNotNull(callForwardingInfo);
-            assertTrue(callForwardingStatus.contains(callForwardingInfo.getStatus()));
-            assertTrue(callForwardingReasons.contains(callForwardingInfo.getReason()));
-            callForwardingInfo.getNumber();
-            assertTrue(callForwardingInfo.getTimeoutSeconds() >= 0);
+                        @Override
+                        public void onError(int error) {
+                            receivedErrorCode.set(error);
+                            latch.countDown();
+                        }
+            };
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.getCallForwarding(callForwardingReasonToGet,
+                            getContext().getMainExecutor(), callback));
+
+            assertTrue(latch.await(TIMEOUT_FOR_NETWORK_OPS, TimeUnit.MILLISECONDS));
+            // Make sure only one of the callbacks gets invoked
+            assertTrue((receivedForwardingInfo.get() != null) ^ (receivedErrorCode.get() != null));
+            if (receivedForwardingInfo.get() != null) {
+                CallForwardingInfo info = receivedForwardingInfo.get();
+                assertTrue(callForwardingReasons.contains(info.getReason()));
+                if (info.isEnabled()) {
+                    assertNotNull(info.getNumber());
+                    assertTrue(info.getTimeoutSeconds() >= 0);
+                }
+            }
+
+            if (receivedErrorCode.get() != null) {
+                assertTrue(callForwardingErrors.contains(receivedErrorCode.get()));
+            }
         }
     }
-     */
 
-    /**
-     * Due to the corresponding API is hidden in R and will be public in S, this test
-     * is commented and will be un-commented in Android S.
-     *
     @Test
-    public void testSetCallForwarding() {
+    public void testSetCallForwarding() throws Exception {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
         List<Integer> callForwardingReasons = new ArrayList<>();
         callForwardingReasons.add(CallForwardingInfo.REASON_UNCONDITIONAL);
         callForwardingReasons.add(CallForwardingInfo.REASON_BUSY);
@@ -619,68 +650,107 @@
 
         // Enable Call Forwarding
         for (int callForwardingReasonToEnable : callForwardingReasons) {
+            CountDownLatch latch = new CountDownLatch(1);
+            // Disregard success or failure; just make sure it reports back.
+            Consumer<Integer> ignoringResultListener = (x) -> latch.countDown();
+
             final CallForwardingInfo callForwardingInfoToEnable = new CallForwardingInfo(
-                    CallForwardingInfo.STATUS_ACTIVE,
+                    true,
                     callForwardingReasonToEnable,
                     TEST_FORWARD_NUMBER,
                     // time seconds
                     1);
-            Log.d(TAG, "[testSetCallForwarding] Enable Call Forwarding. Status: "
-                    + CallForwardingInfo.STATUS_ACTIVE + " Reason: "
+            Log.d(TAG, "[testSetCallForwarding] Enable Call Forwarding. Reason: "
                     + callForwardingReasonToEnable + " Number: " + TEST_FORWARD_NUMBER
                     + " Time Seconds: 1");
-            ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
-                    (tm) -> tm.setCallForwarding(callForwardingInfoToEnable));
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setCallForwarding(callForwardingInfoToEnable,
+                            getContext().getMainExecutor(), ignoringResultListener));
+            // TODO: this takes way too long on a real network (upwards of 40s).
+            // assertTrue("No response for forwarding for reason " + callForwardingReasonToEnable,
+            //        latch.await(TIMEOUT_FOR_NETWORK_OPS * 3, TimeUnit.MILLISECONDS));
         }
 
         // Disable Call Forwarding
         for (int callForwardingReasonToDisable : callForwardingReasons) {
+            CountDownLatch latch = new CountDownLatch(1);
+            // Disregard success or failure; just make sure it reports back.
+            Consumer<Integer> ignoringResultListener = (x) -> latch.countDown();
+
             final CallForwardingInfo callForwardingInfoToDisable = new CallForwardingInfo(
-                    CallForwardingInfo.STATUS_INACTIVE,
+                    false,
                     callForwardingReasonToDisable,
                     TEST_FORWARD_NUMBER,
                     // time seconds
                     1);
-            Log.d(TAG, "[testSetCallForwarding] Disable Call Forwarding. Status: "
-                    + CallForwardingInfo.STATUS_INACTIVE + " Reason: "
+            Log.d(TAG, "[testSetCallForwarding] Disable Call Forwarding. Reason: "
                     + callForwardingReasonToDisable + " Number: " + TEST_FORWARD_NUMBER
                     + " Time Seconds: 1");
-            ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
-                    (tm) -> tm.setCallForwarding(callForwardingInfoToDisable));
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setCallForwarding(callForwardingInfoToDisable,
+                            getContext().getMainExecutor(), ignoringResultListener));
+            // TODO: this takes way too long on a real network (upwards of 40s).
+            //assertTrue("No response for forwarding for reason " + callForwardingReasonToDisable,
+            //        latch.await(TIMEOUT_FOR_NETWORK_OPS * 3, TimeUnit.MILLISECONDS));
         }
     }
-    */
 
-    /**
-     * Due to the corresponding API is hidden in R and will be public in S, this test
-     * is commented and will be un-commented in Android S.
-     *
     @Test
-    public void testGetCallWaitingStatus() {
-        Set<Integer> callWaitingStatus = new HashSet<Integer>();
-        callWaitingStatus.add(TelephonyManager.CALL_WAITING_STATUS_ACTIVE);
-        callWaitingStatus.add(TelephonyManager.CALL_WAITING_STATUS_INACTIVE);
-        callWaitingStatus.add(TelephonyManager.CALL_WAITING_STATUS_UNKNOWN_ERROR);
-        callWaitingStatus.add(TelephonyManager.CALL_WAITING_STATUS_NOT_SUPPORTED);
+    public void testGetCallWaitingStatus() throws Exception {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+        Set<Integer> validCallWaitingStatuses = new HashSet<Integer>();
+        validCallWaitingStatuses.add(TelephonyManager.CALL_WAITING_STATUS_ENABLED);
+        validCallWaitingStatuses.add(TelephonyManager.CALL_WAITING_STATUS_DISABLED);
+        validCallWaitingStatuses.add(TelephonyManager.CALL_WAITING_STATUS_UNKNOWN_ERROR);
+        validCallWaitingStatuses.add(TelephonyManager.CALL_WAITING_STATUS_NOT_SUPPORTED);
 
-        int status = ShellIdentityUtils.invokeMethodWithShellPermissions(
-                mTelephonyManager, (tm) -> tm.getCallWaitingStatus());
-        assertTrue(callWaitingStatus.contains(status));
+        LinkedBlockingQueue<Integer> callWaitingStatusResult = new LinkedBlockingQueue<>(1);
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager, (tm) -> tm.getCallWaitingStatus(getContext().getMainExecutor(),
+                        callWaitingStatusResult::offer));
+        assertTrue(validCallWaitingStatuses.contains(
+                callWaitingStatusResult.poll(TIMEOUT_FOR_NETWORK_OPS, TimeUnit.MILLISECONDS)));
     }
-     */
 
-    /**
-     * Due to the corresponding API is hidden in R and will be public in S, this test
-     * is commented and will be un-commented in Android S.
-     *
     @Test
-    public void testSetCallWaitingStatus() {
-        ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
-                (tm) -> tm.setCallWaitingStatus(true));
-        ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
-                (tm) -> tm.setCallWaitingStatus(false));
+    public void testSetCallWaitingStatus() throws Exception {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+        Set<Integer> validCallWaitingErrors = new HashSet<Integer>();
+        validCallWaitingErrors.add(TelephonyManager.CALL_WAITING_STATUS_UNKNOWN_ERROR);
+        validCallWaitingErrors.add(TelephonyManager.CALL_WAITING_STATUS_NOT_SUPPORTED);
+        Executor executor = getContext().getMainExecutor();
+        {
+            LinkedBlockingQueue<Integer> callWaitingResult = new LinkedBlockingQueue<>(1);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setCallWaitingEnabled(true, executor, callWaitingResult::offer));
+            Integer result = callWaitingResult.poll(TIMEOUT_FOR_NETWORK_OPS, TimeUnit.MILLISECONDS);
+            assertNotNull("Never got callback from set call waiting", result);
+            if (result != TelephonyManager.CALL_WAITING_STATUS_ENABLED) {
+                assertTrue("Call waiting callback got an invalid value: " + result,
+                        validCallWaitingErrors.contains(result));
+            }
+        }
+
+        {
+            LinkedBlockingQueue<Integer> callWaitingResult = new LinkedBlockingQueue<>(1);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setCallWaitingEnabled(false, executor, callWaitingResult::offer));
+            Integer result = callWaitingResult.poll(TIMEOUT_FOR_NETWORK_OPS, TimeUnit.MILLISECONDS);
+            assertNotNull("Never got callback from set call waiting", result);
+            if (result != TelephonyManager.CALL_WAITING_STATUS_DISABLED) {
+                assertTrue("Call waiting callback got an invalid value: " + result,
+                        validCallWaitingErrors.contains(result));
+            }
+        }
     }
-     */
 
     @Test
     public void testGetRadioHalVersion() {
@@ -2655,6 +2725,70 @@
                 TelephonyManager::isDataEnabled);
     }
 
+    @Test
+    public void testDataDuringVoiceCallPolicy() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        ShellIdentityUtils.ShellPermissionMethodHelper<Boolean, TelephonyManager> getPolicyHelper =
+                (tm) -> tm.isMobileDataPolicyEnabled(
+                        TelephonyManager.MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL);
+
+        boolean allowDataDuringVoiceCall = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, getPolicyHelper);
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager, (tm) -> tm.setMobileDataPolicyEnabledStatus(
+                        TelephonyManager.MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL,
+                        !allowDataDuringVoiceCall));
+
+        assertNotEquals(allowDataDuringVoiceCall,
+                ShellIdentityUtils.invokeMethodWithShellPermissions(
+                        mTelephonyManager, getPolicyHelper));
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager, (tm) -> tm.setMobileDataPolicyEnabledStatus(
+                        TelephonyManager.MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL,
+                        allowDataDuringVoiceCall));
+
+        assertEquals(allowDataDuringVoiceCall,
+                ShellIdentityUtils.invokeMethodWithShellPermissions(
+                        mTelephonyManager, getPolicyHelper));
+    }
+
+    @Test
+    public void testAlwaysAllowMmsDataPolicy() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        ShellIdentityUtils.ShellPermissionMethodHelper<Boolean, TelephonyManager> getPolicyHelper =
+                (tm) -> tm.isMobileDataPolicyEnabled(
+                        TelephonyManager.MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED);
+
+        boolean mmsAlwaysAllowed = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, getPolicyHelper);
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager, (tm) -> tm.setMobileDataPolicyEnabledStatus(
+                        TelephonyManager.MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED,
+                        !mmsAlwaysAllowed));
+
+        assertNotEquals(mmsAlwaysAllowed,
+                ShellIdentityUtils.invokeMethodWithShellPermissions(
+                        mTelephonyManager, getPolicyHelper));
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager, (tm) -> tm.setMobileDataPolicyEnabledStatus(
+                        TelephonyManager.MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED,
+                        mmsAlwaysAllowed));
+
+        assertEquals(mmsAlwaysAllowed,
+                ShellIdentityUtils.invokeMethodWithShellPermissions(
+                        mTelephonyManager, getPolicyHelper));
+    }
+
     /**
      * Validate Emergency Number address that only contains the dialable character.
      *